<gh_stars>0
from model import Item
import inspect
import os
import random
import sqlite3
import string

CHARS = string.ascii_letters + string.digits + string.punctuation
PASSWORD_LENTH = 10
# create dir for db
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename)) + '\\res\\'
if not os.path.exists(path):
    os.mkdir(path)
# connect to db
database = sqlite3.connect(path + 'passwords.db')
with database:
    cursor = database.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS passwords (service TEXT, login TEXT, password TEXT)""")


def generate_password():
    """
    create password given length
    """
    global CHARS, PASSWORD_LENTH
    password = ''
    for _ in range(PASSWORD_LENTH):
        password += random.choice(CHARS)
    return password


def encrypt_password(password, key):
    """
    crypt password with key, that given from user
    """
    global CHARS
    key_index = 0
    new_password = ''
    for i in key:
        for j in range(len(CHARS)):
            if i == CHARS[j]:
                key_index += j
    key_index /= len(key)
    key_index = int(key_index)
    for i in password:  # first symbol in password
        for j in range(len(CHARS)):
            password_index = 0
            if i == CHARS[j]:
                password_index = j + key_index
                if password_index >= len(CHARS):
                    password_index -= len(CHARS)
                new_password += CHARS[password_index]
    return new_password


def decrypt_password(password, key):
    """
    decrypt password with key, that given from user
    """
    global CHARS
    key_index = 0
    new_password = ''
    for i in key:
        for j in range(len(CHARS)):
            if i == CHARS[j]:
                key_index += j
    key_index /= len(key)
    key_index = int(key_index)
    for i in password:  # first symbol in password
        for j in range(len(CHARS)):
            password_index = 0
            if i == CHARS[j]:
                password_index = j - key_index
                if password_index < 0:
                    password_index += len(CHARS)
                new_password += CHARS[password_index]
    return new_password


def get_exists_user_data(func_name):
    """
    get service and login, that exists in db, from user
    """

    global cursor
    change = input('Вывести уч. записи y/n? ')
    if change == 'y':
        cursor.execute("""SELECT service FROM passwords""")
        services = cursor.fetchall()
        if not services:
            print("Нет ни одной уч. записи\n")
            return None 
        services = set(services)
        for i in services:
            print(i[0])
    elif change == 'n':
        pass
    else:
        print('Неверная команда')
        return None 
    data = Item()
    data.service = input('От чего пароль? ')
    cursor.execute("""SELECT login FROM passwords WHERE service = ?""", (data.service,))
    logins = cursor.fetchall()
    # if not exists this login in db
    if not logins:
        print('Нет такой уч. записи\n')
        return None 
    print('Уч. записи в этом сервисе:')
    for i in logins:
        print(i[0])
    data.login = input('Логин ')
    for i in logins:
        if not data.login in i[0]:
            print('Нет такой уч. записи\n')
            return None 
    if delete_writing.__name__ == func_name:
        data.key = None
    else:
        data.key = input('Ключ шифрования ')
        # run current function
    if not data.service or not data.login or not data.key:
        print('Неверная команда')   
        return None
    return data



def get_not_exists_user_data():
    """
    get user data, that not exists in db
    """
    global cursor
    data = Item()
    data.service = input('От чего пароль? ')
    data.login = input('Логин ')
    data.key = input('Ключ шифрования ')
    if not data.service and not data.login:
        print('Введите корректные данные\n')
        return None
    return data



def read_writing():
    global cursor
    data = get_exists_user_data(read_writing.__name__)
    if data is None:
        return
    cursor.execute("""SELECT password FROM passwords WHERE service = ? AND login = ? """,
                   (data.service, data.login))
    password = cursor.fetchone()[0]
    decrypted_password = decrypt_password(password, data.key)
    print(f'Пароль {decrypted_password}')
    database.commit()


def add_writing():
    global cursor
    data = get_not_exists_user_data()
    if data is None:
        return
    cursor.execute("""SELECT password FROM passwords WHERE service = ? AND login = ?""", (data.service, data.login))
    if not cursor.fetchone() is None:
        print('Такая уч. запись уже существует\n')
    else:
        password = generate_password()
        try:
            encrypted_password = encrypt_password(password, data.key)
        except TypeError:
            encrypted_password = password
        cursor.execute("""INSERT INTO passwords(service, login, password) VALUES(?, ?, ?) """,
                       (data.service, data.login, encrypted_password))
        print(f'Пароль для {data.service} - {password}')
    database.commit()


def rewrite_writing():
    global cursor
    data = get_exists_user_data(rewrite_writing.__name__)
    if data is None:
        return
    choice = input('Что поменять?(serv/log/pass) ')
    if choice == 'serv':
        new_service = input('Новое название сервиса ')
        cursor.execute("""UPDATE passwords SET service = ? WHERE service = ? AND login = ? """,
                       (new_service, data.service, data.login))
        print(f'Новое название сервиса - {new_service}')
    elif choice == 'log':
        new_login = input('Новый логин ')
        cursor.execute("""UPDATE passwords SET login = ? WHERE service = ? AND login = ? """,
                       (new_login, data.service, data.login))
        print(f'Новый логин - {new_login}')
    elif choice == 'pass':
        ans = input('Вы уверены y/n? ')
        if ans == 'y':
            password = generate_password()
            try:
                encrypted_password = encrypt_password(password, data.key)
            except TypeError:
                return
            cursor.execute("""UPDATE passwords SET password = ? WHERE service = ? AND login = ? """,
                           (encrypted_password, data.service, data.login))
            print(f'Новый пароль - {password}')
        elif ans == 'n':
            print('Отмена ')
            return
        else:
            print('Неверная команда')
            return
    else:
        print('Неверная команда ')
        return
    database.commit()


def delete_writing():
    global cursor
    data = get_exists_user_data(delete_writing.__name__)
    if data is None:
        return
    choice = input('Вы уверены y/n? ')
    if choice == 'y':
        cursor.execute("""DELETE FROM passwords WHERE service = ? AND login = ?""",
                       (data.service, data.login))
        print('Запись удалена')
    elif choice == 'n':
        print('Отмена ')
        return
    else:
        print('Неверная команда')
    database.commit()


def create_only_password():
    """
    generate password without add it in db
    """
    print(f'Новый пароль - {generate_password()}')

from model import Item
import inspect
import os
import random
import sqlite3
import string

CHARS = string.ascii_letters + string.digits + string.punctuation
PASSWORD_LENTH = 10
# create dir for db
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename)) + '\\res\\'
if not os.path.exists(path):
    os.mkdir(path)
# connect to db
database = sqlite3.connect(path + 'passwords.db')
with database:
    cursor = database.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS passwords (service TEXT, login TEXT, password TEXT)""")


def generate_password():
    """
    create password given length
    """
    global CHARS, PASSWORD_LENTH
    password = ''
    for _ in range(PASSWORD_LENTH):
        password += random.choice(CHARS)
    return password


def encrypt_password(password, key):
    """
    crypt password with key, that given from user
    """
    global CHARS
    key_index = 0
    new_password = ''
    for i in key:
        for j in range(len(CHARS)):
            if i == CHARS[j]:
                key_index += j
    key_index /= len(key)
    key_index = int(key_index)
    for i in password:  # first symbol in password
        for j in range(len(CHARS)):
            password_index = 0
            if i == CHARS[j]:
                password_index = j + key_index
                if password_index >= len(CHARS):
                    password_index -= len(CHARS)
                new_password += CHARS[password_index]
    return new_password


def decrypt_password(password, key):
    """
    decrypt password with key, that given from user
    """
    global CHARS
    key_index = 0
    new_password = ''
    for i in key:
        for j in range(len(CHARS)):
            if i == CHARS[j]:
                key_index += j
    key_index /= len(key)
    key_index = int(key_index)
    for i in password:  # first symbol in password
        for j in range(len(CHARS)):
            password_index = 0
            if i == CHARS[j]:
                password_index = j - key_index
                if password_index < 0:
                    password_index += len(CHARS)
                new_password += CHARS[password_index]
    return new_password


def get_exists_user_data(func_name):
    """
    get service and login, that exists in db, from user
    """

    global cursor
    change = input('Вывести уч. записи y/n? ')
    if change == 'y':
        cursor.execute("""SELECT service FROM passwords""")
        services = cursor.fetchall()
        if not services:
            print("Нет ни одной уч. записи\n")
            return None 
        services = set(services)
        for i in services:
            print(i[0])
    elif change == 'n':
        pass
    else:
        print('Неверная команда')
        return None 
    data = Item()
    data.service = input('От чего пароль? ')
    cursor.execute("""SELECT login FROM passwords WHERE service = ?""", (data.service,))
    logins = cursor.fetchall()
    # if not exists this login in db
    if not logins:
        print('Нет такой уч. записи\n')
        return None 
    print('Уч. записи в этом сервисе:')
    for i in logins:
        print(i[0])
    data.login = input('Логин ')
    for i in logins:
        if not data.login in i[0]:
            print('Нет такой уч. записи\n')
            return None 
    if delete_writing.__name__ == func_name:
        data.key = None
    else:
        data.key = input('Ключ шифрования ')
        # run current function
    if not data.service or not data.login or not data.key:
        print('Неверная команда')   
        return None
    return data



def get_not_exists_user_data():
    """
    get user data, that not exists in db
    """
    global cursor
    data = Item()
    data.service = input('От чего пароль? ')
    data.login = input('Логин ')
    data.key = input('Ключ шифрования ')
    if not data.service and not data.login:
        print('Введите корректные данные\n')
        return None
    return data



def read_writing():
    global cursor
    data = get_exists_user_data(read_writing.__name__)
    if data is None:
        return
    cursor.execute("""SELECT password FROM passwords WHERE service = ? AND login = ? """,
                   (data.service, data.login))
    password = cursor.fetchone()[0]
    decrypted_password = decrypt_password(password, data.key)
    print(f'Пароль {decrypted_password}')
    database.commit()


def add_writing():
    global cursor
    data = get_not_exists_user_data()
    if data is None:
        return
    cursor.execute("""SELECT password FROM passwords WHERE service = ? AND login = ?""", (data.service, data.login))
    if not cursor.fetchone() is None:
        print('Такая уч. запись уже существует\n')
    else:
        password = generate_password()
        try:
            encrypted_password = encrypt_password(password, data.key)
        except TypeError:
            encrypted_password = password
        cursor.execute("""INSERT INTO passwords(service, login, password) VALUES(?, ?, ?) """,
                       (data.service, data.login, encrypted_password))
        print(f'Пароль для {data.service} - {password}')
    database.commit()


def rewrite_writing():
    global cursor
    data = get_exists_user_data(rewrite_writing.__name__)
    if data is None:
        return
    choice = input('Что поменять?(serv/log/pass) ')
    if choice == 'serv':
        new_service = input('Новое название сервиса ')
        cursor.execute("""UPDATE passwords SET service = ? WHERE service = ? AND login = ? """,
                       (new_service, data.service, data.login))
        print(f'Новое название сервиса - {new_service}')
    elif choice == 'log':
        new_login = input('Новый логин ')
        cursor.execute("""UPDATE passwords SET login = ? WHERE service = ? AND login = ? """,
                       (new_login, data.service, data.login))
        print(f'Новый логин - {new_login}')
    elif choice == 'pass':
        ans = input('Вы уверены y/n? ')
        if ans == 'y':
            password = generate_password()
            try:
                encrypted_password = encrypt_password(password, data.key)
            except TypeError:
                return
            cursor.execute("""UPDATE passwords SET password = ? WHERE service = ? AND login = ? """,
                           (encrypted_password, data.service, data.login))
            print(f'Новый пароль - {password}')
        elif ans == 'n':
            print('Отмена ')
            return
        else:
            print('Неверная команда')
            return
    else:
        print('Неверная команда ')
        return
    database.commit()


def delete_writing():
    global cursor
    data = get_exists_user_data(delete_writing.__name__)
    if data is None:
        return
    choice = input('Вы уверены y/n? ')
    if choice == 'y':
        cursor.execute("""DELETE FROM passwords WHERE service = ? AND login = ?""",
                       (data.service, data.login))
        print('Запись удалена')
    elif choice == 'n':
        print('Отмена ')
        return
    else:
        print('Неверная команда')
    database.commit()


def create_only_password():
    """
    generate password without add it in db
    """
    print(f'Новый пароль - {generate_password()}')
# create dir for db # connect to db CREATE TABLE IF NOT EXISTS passwords (service TEXT, login TEXT, password TEXT) create password given length crypt password with key, that given from user # first symbol in password decrypt password with key, that given from user # first symbol in password get service and login, that exists in db, from user SELECT service FROM passwords SELECT login FROM passwords WHERE service = ? # if not exists this login in db # run current function get user data, that not exists in db SELECT password FROM passwords WHERE service = ? AND login = ? SELECT password FROM passwords WHERE service = ? AND login = ? INSERT INTO passwords(service, login, password) VALUES(?, ?, ?) UPDATE passwords SET service = ? WHERE service = ? AND login = ? UPDATE passwords SET login = ? WHERE service = ? AND login = ? UPDATE passwords SET password = ? WHERE service = ? AND login = ? DELETE FROM passwords WHERE service = ? AND login = ? generate password without add it in db