Пример #1
0
class TestUser:
    def setup(self):
        self.user = User("Pavel", "password")

    def teardown(self):
        del self.user

    def test_presence(self):
        to_send = {
            "action": "presence",
            "time": time.time(),
            "type": "status",
            "user": {
                "account_name": 'Pavel',
                "status": "Yes, I'm here"
            }
        }

        assert json.dumps(to_send) == self.user.presence()

    def test_message(self):
        to_send = {
            "action": "msg",
            "time": time.time(),
            "to": "Admin",
            "from": "Pavel",
            "encoding": "ascii",
            "message": "First message"
        }

        assert json.dumps(to_send) == self.user.message(
            "admin", "First message")
Пример #2
0
def login():
    username = ""
    errors = {}
    global user
    if request.method == "POST":
        username = request.form.get("username").strip()
        if not username:
            errors["username"] = "******"

        password = request.form.get("password").strip()
        if not password:
            errors["password"] = "******"

        if len(errors) == 0:
            with database.connect() as conn:
                tmp = database.login(conn, username, password)
                if tmp == -1:
                    errors["username"] = username + " does not exist"
                elif tmp == -2:
                    errors["password"] = "******"
                else:
                    user = User(tmp[0][0], tmp[0][1], tmp[0][2], tmp[0][3])
                    print("Successfully Logged In!")
                    return redirect("/")

    return render_template("login.html",
                           username=username,
                           errors=errors,
                           tab="login",
                           user=user)
Пример #3
0
def getAllUsers(conn, order):
    c = conn.cursor()
    sql = "SELECT username, displayName, password, rank FROM users ORDER BY " + order
    if order == "rank":
        sql += " DESC"
    c.execute(sql)
    arr = c.fetchall()
    return [User(i[0], i[1], i[2], i[3]) for i in arr]
Пример #4
0
 def test_create_presence(self):
     # без параметров
     message = self.user.create_presence()
     assert message['action'] == "presence"
     # берем разницу во времени
     assert abs(message['time'] - time.time()) < 0.1
     assert message["account_name"] == 'Leo'
     # с параметром имя
     message = self.user.create_presence()
     assert message["account_name"] == 'Leo'
     # неверный тип
     with raises(TypeError):
         self.user.create_presence(200)
     with raises(TypeError):
         self.user.create_presence(None)
     # Имя пользователя слишком длинное
     with raises(ToLongError):
         u = User('11111111111111111111111111')
         u.create_presence()
Пример #5
0
async def main():
    longpoll = Api(
        token=group_token,
        group_id=group_id,
    )
    user = User(
        token=user_token,
        group_id=group_id,
    )

    async with longpoll as api:
        async for event in api.listen():
            await user.approve_request(event['user_id'])
Пример #6
0
def signup():
    username = ""
    displayName = ""
    errors = {}
    global user
    if request.method == "POST":
        with database.connect() as conn:
            username = request.form.get("username")
            if not username:
                errors["username"] = "******"
            elif len(username.split()) > 1 or username != username.strip():
                errors["username"] = "******"
            elif not database.unique(conn, "username", username):
                errors["username"] = username + " has been taken"

            displayName = request.form.get("displayName")
            if not displayName:
                errors["displayName"] = "enter a display name"
            elif displayName != displayName.strip():
                errors[
                    "displayName"] = "display name cannot start or end with spaces"
            elif not database.unique(conn, "displayName", displayName):
                errors["displayName"] = displayName + " has been taken"

            password = request.form.get("password")
            if not password:
                errors["password"] = "******"
            elif len(password.split()) > 1 or password != password.strip():
                errors["password"] = "******"

            confirmPassword = request.form.get("confirmPassword")
            if not confirmPassword:
                errors["confirmPassword"] = "******"
            elif password != None and password != confirmPassword:
                errors["confirmPassword"] = "******"

            if len(errors) == 0:
                user = User(username, displayName, password, 0)
                database.addUser(conn, user)
                return redirect("/")

    return render_template("signup.html",
                           username=username,
                           displayName=displayName,
                           errors=errors,
                           tab="signup",
                           user=user)
Пример #7
0
def main(args):
    # First we crate server.
    user_client = User()

    main_widget = MainWidget(None)
    login_menu = LoginMenu(user_client, main_widget)
    main_widget.change_main_widget(login_menu)

    # Urwid-asyncio mumbo jumbo, tl;dr is that
    # you need to run both urwid interface and server backend
    # at the same time so first you initialize (but not start)
    # Urwid loop
    aloop = asyncio.get_event_loop()
    ev_loop = urwid.AsyncioEventLoop(loop=aloop)
    loop = urwid.MainLoop(main_widget, event_loop=ev_loop)

    # And here you specify that alongside urwid you run server
    # All is set up - here execution starts
    loop.run()
Пример #8
0
import sys
import Pyro4
import Pyro4.util
import sys
from client import User

nameserver = Pyro4.locateNS()
uri = nameserver.lookup("TSChatNow")
# this is the ts chat now server
app = Pyro4.Proxy(uri)
user = User()
user.initiate_chatapp(app)
        addr = 'localhost'

    try:
        port = int(sys.argv[2])
    except IndexError:
        port = 7777
    except ValueError:
        print('Порт должен быть целым числом')
        sys.exit()

    try:
        name = sys.argv[3]
    except IndexError:
        name = 'ConsoleGuest'

    client = User(name, addr, port)
    client.connect()

    listener = ConsoleReceiver(client.sock, client.request_queue)
    th_listen = threading.Thread(target=listener.poll)
    th_listen.daemon = True
    th_listen.start()

    while True:
        message_str = input('<<')
        if message_str.startswith('add'):
            try:
                username = message_str.split()[1]
            except IndexError:
                print('Не указано имя пользователя')
            else:
Пример #10
0
class TestUser:
    def setup(self):
        self.user = User('Leo')

    # МОДУЛЬНЫЕ ТЕСТЫ
    def test_create_presence(self):
        # без параметров
        message = self.user.create_presence()
        assert message['action'] == "presence"
        # берем разницу во времени
        assert abs(message['time'] - time.time()) < 0.1
        assert message["account_name"] == 'Leo'
        # с параметром имя
        message = self.user.create_presence()
        assert message["account_name"] == 'Leo'
        # неверный тип
        with raises(TypeError):
            self.user.create_presence(200)
        with raises(TypeError):
            self.user.create_presence(None)
        # Имя пользователя слишком длинное
        with raises(ToLongError):
            u = User('11111111111111111111111111')
            u.create_presence()

    def test_translate_response(self):
        # неправильный тип
        with raises(TypeError):
            self.user.translate_response(100)
        # неверная длина кода ответа
        with raises(ResponseCodeError):
            self.user.translate_response({'response': '5'})
        # нету ключа response
        with raises(WrongDictError):
            self.user.translate_response({'one': 'two'})
        # неверный код ответа
        with raises(ResponseCodeError):
            self.user.translate_response({'response': 700})
        # все правильно
        assert self.user.translate_response({'response': 200}) == {
            'response': 200
        }

    def test_create_message(self):
        msg = self.user.create_message('to', 'hello')
        assert msg['action'] == 'msg'
        # берем разницу во времени
        assert abs(msg['time'] - time.time()) < 0.1
        assert msg['to'] == 'to'
        assert msg['from'] == 'Leo'
        assert msg['message'] == 'hello'
    def start_chat(self):
        #name, password, result = AuthenticateDialog().get_username()

        # Создать контроллер
        self.client = User(self.name, self.password, addr, port)
        #print("Публичный ключ: {}, Приватный ключ: {} ".format(self.client.user_pub, self.client.user_priv))
        self.window.setWindowTitle("Мессенджер - {}".format(self.name))
        self.setGuiConnected(True)
        try:
            response = self.client.connect()
            if ERROR in response:
                if str(response[ERROR]) == str(WRONG_LOGIN):
                    self.show_error_msg('Неверный логин', QMessageBox.Critical)
                    self.client.disconnect()
                    self.setGuiConnected(False)
                    self.window.listWidgetContacts.clear()
                elif str(response[ERROR]) == str(WRONG_PASSWORD):
                    self.show_error_msg('Неверный пароль',
                                        QMessageBox.Critical)
                    self.client.disconnect()
                    self.setGuiConnected(False)
                    self.window.listWidgetContacts.clear()
            elif RESPONSE in response:
                if str(response[RESPONSE]) == str(OK):
                    self.receiver = GuiReceiver(self.client.sock,
                                                self.client.request_queue)
                    self.receiver.gotData.connect(self.update_chat)
                    self.receiver.gotCryptoData.connect(
                        self.append_user_public_keys)
                    # Создание потока и помещение объекта-монитора в этот поток
                    self.thread = QThread()
                    self.receiver.moveToThread(self.thread)

                    # ---------- Важная часть - связывание сигналов и слотов ----------
                    # При запуске потока будет вызван метод search_text
                    self.thread.started.connect(self.receiver.poll)

                    # При завершении поиска необходимо завершить поток и изменить GUI
                    self.receiver.finished.connect(self.thread.quit)
                    self.receiver.finished.connect(self.finished)

                    # Запуск потока, который запустит self.monitor.search_text
                    self.thread.start()

                    self.contact_list, self.quantity = self.client.get_contacts(
                    )

                    if self.quantity < 0:
                        self.show_error_msg('У вас еще нет контактов!',
                                            QMessageBox.Warning)
                        return
                    for user_name in self.contact_list:
                        user_public_keys_dict = {
                            "name": user_name,
                            "is_send_public_key": False,
                            "is_received_public_key": False,
                            "public_key": None
                        }
                        self.client.user_public_keys.append(
                            user_public_keys_dict)

                    # грузим контакты в список сразу при запуске приложения
                    self.load_contacts(self.contact_list)
                else:
                    raise ConnectionRefusedError
        except ConnectionRefusedError as e:
            print('Сервер недоступен')
            self.show_error_msg('Сервер недоступен!', QMessageBox.Critical)
            sys.exit()
        except Exception as e:
            print("Ошибка в функции start_chat:", e)
Пример #12
0
def getUser(conn, username):
    c = conn.cursor()
    sql = "SELECT username, displayName, password, rank FROM users WHERE username = ?"
    c.execute(sql, (username, ))
    arr = c.fetchall()
    return User(arr[0][0], arr[0][1], arr[0][2], arr[0][3])
Пример #13
0
def seed_db():
	db.session.add(User(username="******", email='*****@*****.**', password='******'))
	db.session.add(User(username="******", email='*****@*****.**', password='******'))
	db.session.commit()
Пример #14
0
try:
    addr = sys.argv[1]
except IndexError:
    addr = 'localhost'
try:
    prt = int(sys.argv[2])
except IndexError:
    prt = 7777
except ValueError:
    sys.exit(0)
try:
    name = sys.argv[3]
except IndexError:
    name = 'Leo'

client = User(name)
client.start()

listener = ConsoleReceiver(client.sock, client.receiver_queue)
thread_listener = Thread(target=listener.pull)
thread_listener.daemon = True
thread_listener.start()

speaker = Sender(client.sock, client.login, client.sender_queue)
thread_speaker = Thread(target=speaker.pull)
thread_speaker.daemon = True
thread_speaker.start()

while True:
    # Получаем запрос/текст от пользователя
    text = input('<< ')
Пример #15
0
 def setup(self):
     self.user = User('Leo')
Пример #16
0
try:
    port = int(sys.argv[2])
except IndexError:
    port = 7777
except ValueError:
    print('Порт должен быть целым числом')
    sys.exit(0)
try:
    name = sys.argv[3]
    print(name)
except IndexError:
    name = 'GuiGuest'

app = QtWidgets.QApplication(sys.argv)
window = uic.loadUi('sv_main.ui')
client = User(name, addr, port)
client.connect()
listener = GuiReceiver(client.sock, client.request_queue)


@pyqtSlot(str)
def update_chat(data):
    try:
        msg = data
        window.listWidgetMessages.addItem(msg)
    except Exception as e:
        print(e)


listener.gotData.connect(update_chat)
th = QThread()
Пример #17
0
            r.raw.decode_content = True
            shutil.copyfileobj(r.raw, f)
            print("{} downloaded.".format(file_name))

    else:
        print("{} skipped.".format(file_name))


if __name__ == '__main__':
    webbrowser.open_new_tab(
        'https://oauth.vk.com/authorize?client_id=6449285&response_type=token&scope=84&redirect_uri=https://limitedeternity.github.io/VK-SavedImagesDownloader/'
    )

    try:
        access_token = input("Place access token here: ")
        user = User(token=access_token)
        vk_api = user.auth()
        print("Authorization successful.")

    except Exception:
        print("Your input data seems to be wrong. Please try again!")
        sys.exit(1)

    except KeyboardInterrupt:
        print("Keyboard interrupt detected!")
        sys.exit(0)

    try:
        start_time = time.time()
        creds = user.get_credentials(vk_api)
        folder = create_folder(creds)
class GraphicChat(QtWidgets.QMainWindow):
    sentData = pyqtSignal(str)

    def __init__(self, name, password, parent=None):
        super().__init__(parent)
        self.package_dir = os.path.abspath(os.path.dirname(__file__))
        self.ui_path = os.path.join(dir + '/gui/ui/', 'client_chat.ui')
        self.window = uic.loadUi(self.ui_path)
        self.vbar = self.window.listWidgetMessages.verticalScrollBar()
        self.name = name
        self.password = password

        # список лэйаутов чата вида 'contact':[index, QVBoxLayout].
        # Каждому контакту свой лэйаут
        self.chat_stackedLayout = QStackedLayout()
        self.chat_layout_indexes = {}

        self.init_ui()

    def init_ui(self):
        self.window.pushButtonAddContact.clicked.connect(self.add_contact)
        self.window.pushButtonDelContact.clicked.connect(self.del_contact)
        self.window.connectButton.clicked.connect(self.start_chat)
        self.window.disconnectButton.clicked.connect(self.finished)
        self.window.pushButtonSend.clicked.connect(self.send_message)
        self.window.clearTextButton.clicked.connect(self.clear_text)
        self.window.show()

    def stop_chat(self):
        ''' Остановка входящих соединений '''
        if self.receiver is not None:
            self.receiver.stop()

    def finished(self):
        ''' Действия при отключении
        '''
        self.receiver.stop()
        self.client.disconnect()
        self.setGuiConnected(False)
        self.window.listWidgetContacts.clear()

    def load_contacts(self, contacts):
        """получение списка контактов"""
        # Чистим список
        self.window.listWidgetContacts.clear()
        # Добавим
        for contact in contacts:
            self.window.listWidgetContacts.addItem(str(contact))

    def add_contact(self):
        """Добавление контакта"""
        # Получаем имя из QTextEdit
        try:
            username = self.window.textEditUsername.toPlainText()
            if username:
                # Соединение
                #client.connect()
                self.client.add_contact(username)
                self.window.listWidgetContacts.addItem(username)
                self.window.textEditUsername.clear()
                # отключаемся
                #client.disconnect()
        except Exception as e:
            print("Ошибка в функции add_contact:", e)

    def del_contact(self):
        try:
            current_item = self.window.listWidgetContacts.currentItem()
            username = current_item.text()
            # Соединение
            #client.connect()
            self.client.del_contact(username)
            # отключаемся
            #client.disconnect()
            current_item = self.window.listWidgetContacts.takeItem(
                self.window.listWidgetContacts.row(current_item))
            del current_item
        except Exception as e:
            print("Ошибка в функции del_contact:", e)

    def send_message(self):
        text = self.window.textEditMessage.toPlainText()
        if text:
            try:
                selected_index = self.window.listWidgetContacts.currentIndex()
                if selected_index:
                    user_name = selected_index.data()
                    # Соединение
                    #client.connect()
                    for dict_public_key in self.client.user_public_keys:
                        # При отправки сообщение сначала отправляем один раз одному из клиентов Публичный ключ
                        if dict_public_key[
                                "name"] == user_name and dict_public_key[
                                    "is_send_public_key"] == False:
                            dict_public_key["is_send_public_key"] = True
                            self.client.send_crypto(user_name,
                                                    self.client.user_pub.n)
                            self.window.listWidgetMessages.addItem(
                                "Публичный ключ от пользователя {} еще не получен, "
                                "но наш публичный ключ отправлен попробуйте еще раз"
                                .format(user_name))
                            # Еще бы неплохо получать ответ от пользователя что он получил ключ
                        # Если у нас сохранен публичный ключ клиента то шифруем им сообщение
                        if dict_public_key["name"] == user_name and dict_public_key["is_received_public_key"] == True \
                                and dict_public_key["public_key"] != None:
                            message = text.encode("utf-8")
                            public_key = rsa.PublicKey(
                                dict_public_key["public_key"], 65537)
                            crypto = rsa.encrypt(message, public_key)
                            self.client.send_message(
                                user_name, crypto.decode("ISO-8859-1"))
                    # отключаемся
                    #client.disconnect()
                    msg = ' {}: {}'.format(name, text)
                    self.window.listWidgetMessages.addItem(msg)
                self.window.textEditMessage.clear()
            except Exception as e:
                print("Ошибка в функции graphic_chat.send_message:", e)

    def setGuiConnected(self, enabled):
        ''' Настройка GUI при подключении/отключении
        '''
        self.window.listWidgetMessages.setEnabled(enabled)
        self.window.textEditMessage.setEnabled(enabled)
        self.window.pushButtonSend.setEnabled(enabled)
        self.window.clearTextButton.setEnabled(enabled)
        self.window.connectButton.setEnabled(not enabled)
        self.window.disconnectButton.setEnabled(enabled)
        self.window.listWidgetContacts.setEnabled(enabled)
        self.window.textEditUsername.setEnabled(enabled)
        self.window.textEditUsername.setEnabled(enabled)
        self.window.pushButtonAddContact.setEnabled(enabled)
        self.window.pushButtonDelContact.setEnabled(enabled)

    def clear_text(self):
        self.window.listWidgetMessages.clear()

    def start_chat(self):
        #name, password, result = AuthenticateDialog().get_username()

        # Создать контроллер
        self.client = User(self.name, self.password, addr, port)
        #print("Публичный ключ: {}, Приватный ключ: {} ".format(self.client.user_pub, self.client.user_priv))
        self.window.setWindowTitle("Мессенджер - {}".format(self.name))
        self.setGuiConnected(True)
        try:
            response = self.client.connect()
            if ERROR in response:
                if str(response[ERROR]) == str(WRONG_LOGIN):
                    self.show_error_msg('Неверный логин', QMessageBox.Critical)
                    self.client.disconnect()
                    self.setGuiConnected(False)
                    self.window.listWidgetContacts.clear()
                elif str(response[ERROR]) == str(WRONG_PASSWORD):
                    self.show_error_msg('Неверный пароль',
                                        QMessageBox.Critical)
                    self.client.disconnect()
                    self.setGuiConnected(False)
                    self.window.listWidgetContacts.clear()
            elif RESPONSE in response:
                if str(response[RESPONSE]) == str(OK):
                    self.receiver = GuiReceiver(self.client.sock,
                                                self.client.request_queue)
                    self.receiver.gotData.connect(self.update_chat)
                    self.receiver.gotCryptoData.connect(
                        self.append_user_public_keys)
                    # Создание потока и помещение объекта-монитора в этот поток
                    self.thread = QThread()
                    self.receiver.moveToThread(self.thread)

                    # ---------- Важная часть - связывание сигналов и слотов ----------
                    # При запуске потока будет вызван метод search_text
                    self.thread.started.connect(self.receiver.poll)

                    # При завершении поиска необходимо завершить поток и изменить GUI
                    self.receiver.finished.connect(self.thread.quit)
                    self.receiver.finished.connect(self.finished)

                    # Запуск потока, который запустит self.monitor.search_text
                    self.thread.start()

                    self.contact_list, self.quantity = self.client.get_contacts(
                    )

                    if self.quantity < 0:
                        self.show_error_msg('У вас еще нет контактов!',
                                            QMessageBox.Warning)
                        return
                    for user_name in self.contact_list:
                        user_public_keys_dict = {
                            "name": user_name,
                            "is_send_public_key": False,
                            "is_received_public_key": False,
                            "public_key": None
                        }
                        self.client.user_public_keys.append(
                            user_public_keys_dict)

                    # грузим контакты в список сразу при запуске приложения
                    self.load_contacts(self.contact_list)
                else:
                    raise ConnectionRefusedError
        except ConnectionRefusedError as e:
            print('Сервер недоступен')
            self.show_error_msg('Сервер недоступен!', QMessageBox.Critical)
            sys.exit()
        except Exception as e:
            print("Ошибка в функции start_chat:", e)

    def show_error_msg(self, text, status):
        msg = QMessageBox()
        msg.setText(text)
        msg.setIcon(status)
        msg.setStandardButtons(QMessageBox.Ok)
        msg.exec_()

    @pyqtSlot(tuple)
    def update_chat(self, data):
        try:
            from_, message = data
            #print(from_, message.encode("ISO-8859-1"))
            message = rsa.decrypt(message.encode("ISO-8859-1"),
                                  self.client.user_priv)
            msg = '{}: >>> {}'.format(from_, message.decode("utf-8"))
            self.window.listWidgetMessages.addItem(msg)
        except rsa.DecryptionError as e:
            print(e)
        except Exception as e:
            print("Ошибка в функции update_chat:", e)

    @pyqtSlot(tuple)
    def append_user_public_keys(self, data):
        try:
            user_name, public_key = data
            for dict_public_key in self.client.user_public_keys:
                if dict_public_key["name"] == user_name and dict_public_key[
                        "is_received_public_key"] == False:
                    dict_public_key["public_key"] = public_key
                    dict_public_key["is_received_public_key"] = True
                    print(
                        'Получен первичный ключ от пользователя {} public_key: {}'
                        .format(user_name, public_key))
                    self.window.listWidgetMessages.addItem(
                        'Получен первичный ключ от пользователя {} public_key: {}'
                        .format(user_name, public_key))
                    if dict_public_key["name"] == user_name and dict_public_key[
                            "is_send_public_key"] == False:
                        # Отсылаем в ответ наш публичный ключ
                        self.client.send_crypto(user_name,
                                                self.client.user_pub.n)
                        dict_public_key["is_send_public_key"] = True

        except Exception as e:
            print("Ошибка в функции append_user_public_keys:", e)
Пример #19
0
 def setup(self):
     self.user = User("Pavel", "password")