Exemplo n.º 1
0
    def __init__(self):
        self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = {}
        self.db_path = "lists/"

        self._load_initial_state()
        self._init_callbacks()
        self._loop()
Exemplo n.º 2
0
 def __init__(self, conn, addr, *args, **kwargs):
     self.conn = conn
     self.addr = addr
     self.isLive = True
     self.conn.send(b'Connection accepted by server.')
     self.receiveThread = threading.Thread(target=self.recv)
     self.receiveThread.start()
     self.commandParser = CommandParser()
     self.id = None
     self.isInitialized = False
Exemplo n.º 3
0
 def __init__(self, screenObj, quit_signal):
     """Initialize all the things the client will need to control the entire user session"""
     # initialize screen
     self.screen = Screen(screenObj, self.do_command)
     self.screen.draw_screen()
     # Start listening for messages in the buffer
     self.buffer = queue.SimpleQueue()
     self.parse_message_thread = threading.Thread(target=self.parse_messages, daemon=True)
     self.parse_message_thread.start()
     # We are passed a signal to quit the program
     self.quit_signal = quit_signal
     # Initialize various helper classes
     self.settings = Settings()
     self.command_parser = CommandParser()
     # Create state the client needs to track
     self.irc = False
     self.connected = False
     self.reset_state()
     # This needs to be done after reset_state()
     self.server_parser = ServerParser(self.nick, self.set_nick)
     self.screen.put_line('>>WWWelcome to the wwwiggleVerse!!!')
     self.screen.put_line('>>This is free software, type /version for details')
     # for _ in range (3):
     #     with open('test.txt') as f:
     #         for line in f.readlines():
     #             self.screen.put_line(line)
Exemplo n.º 4
0
    def create(self):
        """
        returns a list of commmandparser.CommandParser seperated
        by the proper Pipe
        """
        lst = []

        for i, t in enumerate(self.tokens):
            if t in '|| | && & >> > << <'.split():
                lst.append(PIPES[t])

            elif self.tokens[i - 1] in '<'.split():
                lst.append(open(t))

            elif self.tokens[i - 1] in '<<':
                lst.append(open(t, 'r+'))

            elif self.tokens[i - 1] == '>>':
                lst.append(open(t, 'a'))

            elif self.tokens[i - 1] == '>':
                lst.append(open(t, 'w'))

            else:
                lst.append(CommandParser(t))

        return lst
Exemplo n.º 5
0
async def command_ygg(app: GraiaMiraiApplication, group: Group,
                      _gm: GroupMessage):
    CP = CommandParser(_gm, settings.commandSymbol)
    _playerName = CP.Command.args if CP.Command.args else CP.quote_plain_message
    _player = PlayerProfile(_playerName)
    _message = _player.getYgg()
    await app.sendGroupMessage(group, MessageChain.create(_message))
Exemplo n.º 6
0
async def command_ban(app: GraiaMiraiApplication, group: Group,
                      _gm: GroupMessage):
    CP = CommandParser(_gm, settings.commandSymbol)

    def add() -> str:
        _l = str()
        for t in CP.at:
            targetGP = groupPermissions(t.target)
            if not targetGP.isAdmin():
                _result = targetGP.blockme()
                _message = f'{t.display} {tF.ban.add_succ}\n' if _result else f'{t.display} {tF.ban.add_fail}\n'
                _l = f'{_l}{_message}'
        return _l.strip('\n')

    def remove() -> str:
        _l = str()
        for t in CP.at:
            targetGP = groupPermissions(t.target)
            _result = targetGP.unblockme()
            _message = f'{t.display} {tF.ban.remove_succ}\n' if _result else f'{t.display} {tF.ban.remove_fail}\n'
            _l = f'{_l}{_message}'
        return _l.strip('\n')

    if CP.Command.args:
        subCommand = CP.Command.argsList[0]
        if subCommand == 'add':
            await app.sendGroupMessage(group,
                                       MessageChain.create([Plain(add())]))
        if subCommand == 'remove':
            await app.sendGroupMessage(group,
                                       MessageChain.create([Plain(remove())]))
Exemplo n.º 7
0
class Chickenfoot:

    def __init__(self):
        self.modules = {}
        self.communicator = None
        self.cparser = CommandParser()

    def init_from_file(self, filename):
        json_file_content = open(filename, 'r').read()
        params = json.loads(json_file_content)
        if 'nanpy_dev' in params['communication']:
            serial_manager.connect(params['communication']['nanpy_dev'])
        self.set_communication(params['communication']['type'], **params['communication']['parameters'])
        for module in params['modules']:
            self.add_module(module['name'], module['type'], **module['parameters'])

    def set_communication(self, comm_name, **data):
        self.communicator = get_communication(comm_name, **data)

    def add_module(self, id, module_name, **data):
        self.modules[id] = get_module(module_name, **data)

    def listen(self):
        self.communicator.listen()
        while 1:
            data = self.communicator.receive()
            if data:
                (module, action, parameters) = self.cparser.parse(data)
                if parameters:
                    self.modules[module].execute(action, **parameters)
                else:
                    self.modules[module].execute(action)
        self.communicator.close()
Exemplo n.º 8
0
class Chickenfoot:
    def __init__(self):
        self.modules = {}
        self.communicator = None
        self.cparser = CommandParser()

    def init_from_file(self, filename):
        json_file_content = open(filename, 'r').read()
        params = json.loads(json_file_content)
        if 'nanpy_dev' in params['communication']:
            serial_manager.connect(params['communication']['nanpy_dev'])
        self.set_communication(params['communication']['type'],
                               **params['communication']['parameters'])
        for module in params['modules']:
            self.add_module(module['name'], module['type'],
                            **module['parameters'])

    def set_communication(self, comm_name, **data):
        self.communicator = get_communication(comm_name, **data)

    def add_module(self, id, module_name, **data):
        self.modules[id] = get_module(module_name, **data)

    def listen(self):
        self.communicator.listen()
        while 1:
            data = self.communicator.receive()
            if data:
                (module, action, parameters) = self.cparser.parse(data)
                if parameters:
                    self.modules[module].execute(action, **parameters)
                else:
                    self.modules[module].execute(action)
        self.communicator.close()
Exemplo n.º 9
0
    def __init__(self):
        self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = []

        self._load_initial_state()
        self._init_callbacks()
        self._loop()
Exemplo n.º 10
0
    def __init__(self):
        self.cp = CommandParser()
        self.lists = {}
        self.db_path = "lists/"
        self.adapter = SQLRelationList(self.db_path)

        self._load_initial_state()
        self._init_callbacks()
        self._loop()
Exemplo n.º 11
0
 def __init__(self):
     self.db_path = "maillist"
     self.conn=sqlite3.connect(self.db_path)
     self.create_table(self.conn.cursor())
     self.factory = MailListDataBaseFactory(self.conn)
     self.cp = CommandParser()
     self.lists = {}
     self._load_initial_state()
     self._init_callbacks()
     self._loop()
Exemplo n.º 12
0
async def command_ot(app: GraiaMiraiApplication, group: Group,
                     _gm: GroupMessage):
    CP = CommandParser(_gm, settings.commandSymbol)
    atList: List[Optional[At]] = [At(t.target)
                                  for t in CP.at] if CP.at != [] else []
    await app.sendGroupMessage(
        group,
        MessageChain.create([
            *atList,
            Image.fromLocalFile('./images/off-topic.png'),
            *([Plain(tF.ot)] if group.id == settings.specialqq.littleskin_main
              else [])  # 仅在 LittleSkin 主群中启用此文本消息
        ]))
Exemplo n.º 13
0
class Connection:

    def __init__(self, conn, addr, *args, **kwargs):
        self.conn = conn
        self.addr = addr
        self.isLive = True
        self.conn.send(b'Connection accepted by server.')
        self.receiveThread = threading.Thread(target=self.recv)
        self.receiveThread.start()
        self.commandParser = CommandParser()
        self.id = None
        self.isInitialized = False

    def recv(self):
        while self.isLive:
            try:
                data = self.conn.recv(1024)
                data = data.decode('utf-8')
                commandType, commandData = self.commandParser.parseCommand(data)
                self.executeCommand(commandType, commandData)
            except BrokenPipeError as e:
                self.isLive = False
                self.conn.close()
                print('Connection closed.')
                sys.exit(0)
            except ConnectionResetError as e:
                print(e)
    
    def executeCommand(self, commandType, commandData):
        if commandType == 'quit':
            self.sendData('closing')
            self.closeConnection()
        if commandType == 'init':
            self.id = commandData
            self.isInitialized = True
            print('Connection id initialize to: ', self.id)

    def sendData(self, dataString):
        data = bytes(dataString, 'utf-8')
        try:
            self.conn.send(data)
        except BrokenPipeError as e:
            self.isLive = False
            self.conn.close()
        except ConnectionResetError as e:
            pass

    def closeConnection(self):
        self.conn.close()
        self.isLive = False
Exemplo n.º 14
0
async def parse_csl_log(app: GraiaMiraiApplication, group: Group,
                        _gm: GroupMessage):
    await app.sendGroupMessage(
        group, MessageChain.create([Plain(tF.csl_log_parsing)]))
    CP = CommandParser(_gm, settings.commandSymbol)
    fromLs = group.id in [
        settings.specialqq.littleskin_main, settings.specialqq.littleskin_cafe
    ]
    try:
        _message = aoscPastebin(CP.plain_message, fromLittleSkin=fromLs)
        await app.sendGroupMessage(group,
                                   MessageChain.create([Plain(_message)]))
    except Exception as e:
        await app.sendGroupMessage(group,
                                   MessageChain.create([Plain(repr(e))]))
Exemplo n.º 15
0
async def command_view(app: GraiaMiraiApplication, group: Group,
                       _gm: GroupMessage):
    CP = CommandParser(_gm, settings.commandSymbol)
    _textureHash = CP.Command.args
    if not _textureHash:
        await app.sendGroupMessage(
            group, MessageChain.create([Plain(tF.view_no_hash_error)]))
    elif len(_textureHash) != 64:
        await app.sendGroupMessage(
            group, MessageChain.create([Plain(tF.view_hash_length_error)]))
    else:
        _image_message = PlayerProfile.getPreviewByHash(_textureHash)
        if _image_message:
            await app.sendGroupMessage(group,
                                       MessageChain.create([_image_message]))
        else:
            await app.sendGroupMessage(
                group, MessageChain.create([Plain(tF.view_not_200_error)]))
Exemplo n.º 16
0
    def __init__(self):
        #self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = {}

    # --- DATABASE hendeling  ---
        self.db_path = "lists/"
        self.db_name = "database.db"
        self.db_conn = None  # keeps the connection to the database

        self.db_maillists = " maillsits (id INTEGER PRIMERY KEY, name text"
        self.db_subsrcibers = " subscribers (id INTEGER PRIMERY KEY," +\
                              "name text, email text)"
        self.db_list_to_subs = " list_to_subscribers (list_id int," +\
                               " subscribers_id int)"

        self.__ensure_database()
    # --- End Database handeling ---

        self._load_initial_state()
        self._init_callbacks()
        self._loop()
Exemplo n.º 17
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = {}
        self.db_path = "lists/"

        self._load_initial_state()
        self._init_callbacks()
        self._loop()

    def create_list_callback(self, arguments):
        name = " ".join(arguments)

        maillist = self.factory.create(name)
        maillist_adapter = MailListFileAdapter(self.db_path, maillist)
        maillist_adapter.save()

        self.lists[maillist.get_id()] = (maillist, maillist_adapter)

    def add_subscriber_callback(self, arguments):
        list_id = int("".join(arguments))
        name = input("name>")
        email = input("email>")

        self.lists[list_id][0].add_subscriber(name, email)
        self._notify_save(list_id)

    def show_lists_callback(self, arguments):
        for list_id in self.lists:
            current_list = self.lists[list_id][0]
            print("[{}] {}".format(list_id, current_list.get_name()))

    def show_list_callback(self, arguments):
        list_id = int("".join(arguments))

        if list_id in self.lists:
            subscribers = self.lists[list_id][0].get_subscribers()
            for s in subscribers:
                print("{} - {}".format(s[0], s[1]))
        else:
            print("List with id <{}> was not found".format(list_id))

    def exit_callback(self, arguments):
        sys.exit(0)

    def _load_initial_state(self):
        dir_lists = map(basename, glob(self.db_path + "*"))

        for list_file in dir_lists:
            adapter = MailListFileAdapter(self.db_path)
            parsed_list = adapter.load(list_file)

            maillist_adapter = MailListFileAdapter(self.db_path, parsed_list)

            self.lists[parsed_list.get_id()] = (parsed_list, maillist_adapter)

    def _init_callbacks(self):
        self.cp.on("create", self.create_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("exit", self.exit_callback)
        # TODO - implement the rest of the callbacks

    def _notify_save(self, list_id):
        self.lists[list_id][1].save()

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 18
0
 def setUp(self):
     self.cp = CommandParser()
Exemplo n.º 19
0
class CommandParserTest(unittest.TestCase):
    """docstring for CommandParserTest"""
    def setUp(self):
        self.cp = CommandParser()
        self.called = False

    def test_on_with_single_command(self):
        def callback(arguments):
            self.called = True
            self.assertEqual(0, len(arguments))

        self.cp.on("command", callback)
        self.cp.take_command("command")

        self.assertTrue(self.called)

    def test_on_with_full_command(self):
        def callback(arguments):
            self.called = True

            self.assertEqual(["1", "2"], arguments)

        self.cp.on("delete_subscriber", callback)
        self.cp.take_command("delete_subscriber 1 2")

        self.assertTrue(self.called)

    def test_on_with_command_not_found(self):
        def callback(arguments):
            self.called = True

        self.cp.on("something", callback)
        result = self.cp.take_command("something_else")

        self.assertFalse(self.called)
        self.assertIsNone(result)
Exemplo n.º 20
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = {}
        self.db_path = "lists/"

        self._load_initial_state()
        self._init_callbacks()
        self._loop()

    def create_list_callback(self, arguments):
        name = " ".join(arguments)

        maillist = self.factory.create(name)
        maillist_adapter = MailListFileAdapter(self.db_path, maillist)
        maillist_adapter.save()

        self.lists[maillist.get_id()] = (maillist, maillist_adapter)

    def add_subscriber_callback(self, arguments):
        list_id = int("".join(arguments))
        name = input("name>")
        email = input("email>")

        self.lists[list_id][0].add_subscriber(name, email)
        self._notify_save(list_id)

    def show_lists_callback(self, arguments):
        for list_id in self.lists:
            current_list = self.lists[list_id][0]
            print("[{}] {}".format(list_id,
                                   current_list.get_name()))

    def show_list_callback(self, arguments):
        list_id = int("".join(arguments))

        if list_id in self.lists:
            subscribers = self.lists[list_id][0].get_subscribers()
            for s in subscribers:
                print("{} - {}".format(s[0], s[1]))
        else:
            print("List with id <{}> was not found".format(list_id))

    def exit_callback(self, arguments):
        sys.exit(0)

    def _load_initial_state(self):
        dir_lists = map(basename, glob(self.db_path + "*"))

        for list_file in dir_lists:
            adapter = MailListFileAdapter(self.db_path)
            parsed_list = adapter.load(list_file)

            maillist_adapter = MailListFileAdapter(self.db_path, parsed_list)

            self.lists[parsed_list.get_id()] = (parsed_list, maillist_adapter)

    def _init_callbacks(self):
        self.cp.on("create", self.create_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("exit", self.exit_callback)
        # TODO - implement the rest of the callbacks

    def _notify_save(self, list_id):
        self.lists[list_id][1].save()

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 21
0
 def __init__(self, database_name):
     self.cp = CommandParser()
     self.db = DBinterface(database_name)
     self.zoos = self.db.update_zoos()
     self._init_callbacks()
     self._loop()
Exemplo n.º 22
0
 def __init__(self):
     self.modules = {}
     self.communicator = None
     self.cparser = CommandParser()
Exemplo n.º 23
0
class CommandParserTest(unittest.TestCase):
    """docstring for CommandParserTest"""

    def setUp(self):
        self.cp = CommandParser()
        self.called = False

    def test_on_with_single_command(self):
        def callback(arguments):
            self.called = True
            self.assertEqual(0, len(arguments))

        self.cp.on("command", callback)
        self.cp.take_command("command")

        self.assertTrue(self.called)

    def test_on_with_full_command(self):
        def callback(arguments):
            self.called = True

            self.assertEqual(["1", "2"], arguments)

        self.cp.on("delete_subscriber", callback)
        self.cp.take_command("delete_subscriber 1 2")

        self.assertTrue(self.called)

    def test_on_with_command_not_found(self):
        def callback(arguments):
            self.called = True

        self.cp.on("something", callback)
        result = self.cp.take_command("something_else")

        self.assertFalse(self.called)
        self.assertIsNone(result)
Exemplo n.º 24
0
 def __init__(self):
     self.cp = CommandParser()
     self.mail_lists = []
     self.update_mail_lists(self.mail_lists)
     self._init_callbacks()
     self._loop()
Exemplo n.º 25
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = {}
        self.db_path = "lists/"

        self._load_initial_state()
        self._init_callbacks()
        self._loop()

    def create_list_callback(self, arguments):
        if len(str(arguments)) == 4:
            print("Invalid listname!")
        else:
            used_names = self.show_lists_callback("1")
            new_args = str(arguments)
            if new_args[2:-2] in used_names:
                print ("There is already a list with that name!")
            else:
                conn = sqlite3.connect("mail_list_database.db")
                cursor = conn.cursor()
                result = cursor.execute('''INSERT INTO maillist(name)
                                    VALUES (?)''', (arguments))
                conn.commit()
                conn.close()


    def add_subscriber_callback(self, arguments):
        list_id = arguments[0]
        conn = sqlite3.connect("mail_list_database.db")
        cursor = conn.cursor()
        name = input("name>")
        email = input("email>")
        result1 = cursor.execute('''SELECT subs_id
                                    FROM subscribers
                                    WHERE name = ? and email = ?''', (name, email))
        final_res = cursor.fetchone()
        if final_res is None:
            print(cursor.fetchone())
            result2 = cursor.execute('''INSERT INTO subscribers(name, email)
                                        VALUES(?, ?)''', (name, email))

            result3 = cursor.execute('''SELECT subs_id
                                        FROM subscribers
                                        WHERE name = ? and email = ?''', (name, email))
            result_from_3rd_query = cursor.fetchone()
            res3 = int(result_from_3rd_query[0])

            result4 = cursor.execute(''' INSERT INTO maillist_to_subscribers(list_id, subscribesr_id)
                                        VALUES (?, ?)''', (list_id, res3))
        else:
            result_from_1st_query = final_res
            res1 = int(result_from_1st_query[0])
            result5 = cursor.execute('''SELECT list_id
                                        FROM maillist_to_subscribers
                                        WHERE subscribesr_id = (?)''', str(res1))
            lists = []
            for row in result5:
                lists.append(int(row[0]))
            if int(list_id) in lists:
                print ("The subscriber is already in that list")
            else:
                result6 = cursor.execute('''INSERT INTO maillist_to_subscribers(list_id, subscribesr_id)
                                            VALUES (?,?)''', (list_id, res1) )
        conn.commit()
        conn.close()

    def show_lists_callback(self, want_return=0):
        conn = sqlite3.connect("mail_list_database.db")
        cursor = conn.cursor()
        list_names = []
        list_ids = []
        result = cursor.execute("SELECT * FROM maillist")
        for row in result:
            list_ids.append(row[0])
            list_names.append(row[1])
        conn.close()
        the_wish = len(want_return)
        if the_wish == 0:
            for row in range(0, len(list_ids)):
                print("{" + str(list_ids[row]) + "} " + list_names[row])
        else:
            return(list_names)


    def show_list_callback(self, arguments):
        conn = sqlite3.connect("mail_list_database.db")
        cursor = conn.cursor()

        used_names = self.show_lists_callback("1")
        integer_argument = int(arguments[0])
        if integer_argument > len(used_names):
            print ("There is no list with this identifier!")
        else:
            result = cursor.execute('''SELECT DISTINCT subscribers.name, subscribers.email
                FROM subscribers INNER JOIN maillist_to_subscribers ON subscribers.subs_id = maillist_to_subscribers.subscribesr_id
                INNER JOIN maillist ON maillist_to_subscribers.list_id = ?''', (arguments))
            counter = 1
            for row in result:
                print("{" + str(counter) + "} " + str(row[0]) + " - " + str(row[1]) )
                counter += 1
            conn.commit()
            conn.close()


    def exit_callback(self, arguments):
        sys.exit(0)

    def _load_initial_state(self):
        dir_lists = map(basename, glob(self.db_path + "*"))

        for list_file in dir_lists:
            adapter = MailListFileAdapter(self.db_path)
            parsed_list = adapter.load(list_file)

            maillist_adapter = MailListFileAdapter(self.db_path, parsed_list)

            self.lists[parsed_list.get_id()] = (parsed_list, maillist_adapter)

    def _init_callbacks(self):
        self.cp.on("create", self.create_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("exit", self.exit_callback)
        # TODO - implement the rest of the callbacks

    def _notify_save(self, list_id):
        self.lists[list_id][1].save()

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 26
0
 def __init__(self, database_name):
     self.cp = CommandParser()
     self.db = Database(database_name)
     self._init_callbacks()
     self._loop()
Exemplo n.º 27
0
class Store():
    """docstring for Command-line Interface"""
    def __init__(self, database_name):
        self.cp = CommandParser()
        self.db = Database(database_name)
        self._init_callbacks()
        self._loop()

    def callback_import_products_json(self, arguments):
        json_filename = " ".join(arguments)
        if self.db.import_products_json(json_filename) is True:
            return "{} imported.".format(json_filename[:-5])
        else:
            return "{} could not be imported.".format(json_filename)

    def callback_export_products_json(self, arguments):
        json_filename = " ".join(arguments)
        opened_file = open(json_filename, "w")
        opened_file.write(self.db.export_products_json())
        opened_file.close()
        return "Products exported to {}".format(json_filename)

    def callback_unknown_command(self, arguments):
        message = ("Error: Unknown Command!",
                   "Why don't you enter help to see available commands?")
        return "\n".join(message)

    def callback_list_products(self, arguments):
        return self.db.list_products()

    def callback_add_product(self, arguments):
        name = str(input("name>"))
        price_per_kg = str(input("price per kg>"))
        quantity_in_kg = str(input("quantity in kg>"))
        if self.db.add_product(name, price_per_kg, quantity_in_kg):
            return "{} added to products.".format(name)

    def callback_delete_product(self, arguments):
        product_id = arguments[0]
        name = self.db.fetch_product_name(product_id)
        if self.db.delete_product(product_id) is True:
            return "{} deleted.".format(name)

    def callback_update_product(self, arguments):
        product_id = arguments[0]
        old_name = self.db.fetch_product_name(product_id)
        new_name = str(input("name>"))
        price_per_kg = str(input("price per kg>"))
        quantity_in_kg = str(input("quantity in kg>"))
        if self.db.update_product(new_name, price_per_kg,
                                  quantity_in_kg) is True:
            return "{} updated to {}.".format(old_name, new_name)

    def callback_import_customers_json(self, arguments):
        json_filename = " ".join(arguments)
        if self.db.import_customers_json(json_filename) is True:
            return "Imported customers from json_filename"

    def callback_list_customers(self, arguments):
        return self.db.list_customers()

    def callback_add_customer(self, arguments):
        name = input("name>")
        kg_bought = input("kg bought>")
        money_spent = input("money spent>")
        if self.db.add_customer(self, name, kg_bought, money_spent) is True:
            return "Added {}.".format(name)

    def callback_delete_customer(self, arguments):
        customer_id = arguments[0]
        if self.db.delete_customer(customer_id) is True:
            return "Deleted {}.".format(
                self.db.fetch_customer_name(customer_id))

    def callback_update_customer(self, arguments):
        customer_id = arguments[0]
        name = input("name>")
        kg_bought = input("kg bought>")
        money_spent = input("money spent>")
        if self.db.update_customer(self, name, kg_bought, money_spent,
                                   customer_id) is True:
            return "Updated {}".format(self.db)

    def callback_export_customers_json(self, arguments):
        json_filename = " ".join(arguments)
        opened_file = open(json_filename, "w")
        opened_file.write(self.db.export_customers_json())
        opened_file.close()
        return "Exported customers to {}".format(json_filename)

    def callback_help(self, arguments):
        help_message_products = (
            "* import_products_json <json_filename> - Adds products from the json file to the database.",
            "* list_products - Prints out all products in the following format: \"[id] name - price_per_kg BGN - quantity kg\"",
            "* add_product - Prompts for data, needed to add a new product to the database.",
            "* delete_product <product_id> - Removes the product matching the product id in the database.",
            "* update_product <product_id> - Updates the product data matching the product id in the database.",
            "* export_products_json <json_filename> - Exports the products to a json file."
        )
        help_message_customers = (
            "* import_json_customers <json_filename> - Adds customers from the json file to the database.",
            "* list_customers - Prints out all customers in the following format: \"[id] name - kg_bought kg - money_spent BGN\"",
            "* add_customer - Prompts for data, needed to add a new customer to the database.",
            "* delete_customer <customer_id> - Removes the customer matching the customer id in the database.",
            "* update_customer <customer_id> - Updates the customer data matching the customer id in the database.",
            "* export_customers_json <json_filename> - Exports the customers in the database to a json file."
        )
        return "\n".join(help_message_products + help_message_customers)

    def _init_callbacks(self):
        self.cp.on("list_products", self.callback_list_products)
        self.cp.on("list_customers", self.callback_list_customers)
        self.cp.on("add_product", self.callback_add_product)
        self.cp.on("add_customer", self.callback_add_customer)
        self.cp.on("update_product", self.callback_update_product)
        self.cp.on("update_customer", self.callback_update_customer)
        self.cp.on("delete_product", self.callback_delete_product)
        self.cp.on("delete_customer", self.callback_delete_customer)
        self.cp.on("import_products_json", self.callback_import_products_json)
        self.cp.on("import_customers_json",
                   self.callback_import_customers_json)
        self.cp.on("export_products_json", self.callback_export_products_json)
        self.cp.on("export_customers_json",
                   self.callback_export_customers_json)
        self.cp.on("help", self.callback_help)

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 28
0
class CLI():
    """docstring for CLI"""
    def __init__(self):
        self.cp = CommandParser()
        self.fh = FileHandler()
        self._init_callbacks()
        self._loop()

    def callback_create_attendance_file(self, arguments):
        if self.fh.create_attendance_file() is True:
            return "New file created and loaded: {}".format(
                self.fh.get_current_open_file())
        elif self.fh.create_attendance_file() is False:
            return "You already have a file for today it is: {}".format(
                self.fh.get_current_open_file())

    def callback_change_current_date(self, arguments):
        if self.fh.change_current_date(arguments) is True:
            return "Date changed to {}/{}/{}\nCurrent file saved & discarded.\nYou can create or load.".format(
                arguments[0], arguments[1], arguments[2])

    def callback_add_attendance(self, arguments):
        try:
            student = "{} {}".format(arguments[0], arguments[1])
        except IndexError:
            return "Error: Please enter student as FirstName LastName"

        if self.fh.is_student_attending(student) is True:
            return "{} is already attending!".format(student)
        elif self.fh.is_student_attending(student) is False:
            if self.fh.add_attendance(student) is True:
                return "{} is now attending!".format(student)
            elif self.fh.add_attendance(student) is False:
                return "Create or load a file before adding!"
        elif self.fh.is_student_attending(student) is None:
            return "{} is not in our records.".format(student)

    def callback_list_files(self, arguments):
        return self.fh.list_attendance_files()

    def callback_help(self, arguments):
        help_message = [
            "Available commands are:", "* create", "* change_date", "* add",
            "* list", "* load", "* status", "* statistics"
        ]
        return "\n".join(help_message)

    def callback_load(self, arguments):
        try:
            file_id = arguments[0]
        except IndexError:
            return "Error: No ID given"
        if self.fh.load_attendance_file(file_id) is True:
            return "Loaded {}".format(self.fh.get_current_open_file())
        elif self.fh.load_attendance_file(file_id) is False:
            return "Error: Invalid ID. Use list before using load."

    def callback_status(self, arguments):
        return self.fh.list_attending_students()

    def callback_statistics(self, arguments):
        return self.fh.get_statistics()

    def _init_callbacks(self):
        self.cp.on("create", self.callback_create_attendance_file)
        self.cp.on("change_date", self.callback_change_current_date)
        self.cp.on("add", self.callback_add_attendance)
        self.cp.on("list", self.callback_list_files)
        self.cp.on("help", self.callback_help)
        self.cp.on("load", self.callback_load)
        self.cp.on("status", self.callback_status)
        self.cp.on("statistics", self.callback_statistics)

    def _loop(self):
        while True:
            command = input("command>")
            self.cp.take_command(command)
Exemplo n.º 29
0
 def __init__(self):
     self.cp = CommandParser()
     self.fh = FileHandler()
     self._init_callbacks()
     self._loop()
Exemplo n.º 30
0
class Interface():
    """Mail list interface"""
    def __init__(self):
        self.cp = CommandParser()
        self.mail_lists = []
        self.update_mail_lists(self.mail_lists)
        self._init_callbacks()
        self._loop()

    def callback_show_lists(self, arguments):
        output = []
        for i, mail_object in enumerate(self.mail_lists):
            output.append("[{}] {}".format(i+1, mail_object._name))
        return "\n".join(output)

    def callback_show_list(self, arguments):
        unique_list_identifier = int(arguments[0]) - 1
        try:
            return self.mail_lists[unique_list_identifier].show_subscribers()
        except IndexError:
            return "List with unique identifier {} was not found!".format(unique_list_identifier+1)

    def callback_add_subscriber(self, arguments):
        unique_list_identifier = arguments[0]
        desired_list = self.mail_lists[int(unique_list_identifier) - 1]
        name = str(input("name>"))
        email = str(input("email>"))
        if desired_list.add_subscriber(name, email) is True:
            desired_list.save("file")
            return "{} was added to {}.".format(name, desired_list._name)
        return "Subscriber with email <{}> already exists.".format(email)

    def callback_remove_subscriber(self, arguments):
        unique_list_identifier = int(arguments[0]) - 1
        subscriber_id = int(arguments[1]) - 1
        desired_list = self.mail_lists[unique_list_identifier]
        subscriber_name = desired_list.get_subscriber_name(subscriber_id)
        if desired_list.remove_subscriber(subscriber_name) is True:
            desired_list.save("file")
            return "<{}> was removed from <{}>.".format(subscriber_name, desired_list._name)
        return "Subscriber <{}> was not found in <{}>.".format(subscriber_name, desired_list._name)

    def callback_update_subscriber(self, arguments):
        unique_list_identifier = int(arguments[0]) - 1
        subscriber_id = int(arguments[1]) - 1
        desired_list = self.mail_lists[unique_list_identifier]
        subscriber_name = desired_list.get_subscriber_name(subscriber_id)
        subscriber_email = desired_list.get_subscriber_email(subscriber_id)
        print("Updating <{}> - <{}>\nPress Enter if you want the field to remain the same".format(subscriber_name, subscriber_email))
        new_name = input("new name>")
        new_email = input("new email>")

        if new_name == "":
            if new_email == "":
                return "Nothing to update."
            else:
                desired_list.update_subscriber(subscriber_name, subscriber_name, new_email)
                desired_list.save("file")
                return "Updated <{}> - <{}>.".format(subscriber_name, new_email)
        elif new_email == "":
            if new_name == "":
                return "Nothing to update."
            else:
                desired_list.update_subscriber(subscriber_name, new_name, subscriber_email)
                desired_list.save("file")
                return "Updated <{}> - <{}>.".format(new_name, subscriber_email)
        else:
            desired_list.update_subscriber(subscriber_name, new_name, new_email)
            desired_list.save("file")
            return "Updated <{}> - <{}>.".format(new_name, new_email)

    def callback_create_maillist(self, arguments):
        list_name = arguments[0]
        mail_list = Database(list_name)
        self.mail_lists.append(mail_list)
        mail_list.save("file")
        return "New list <{}> was created.".format(list_name)

    def callback_delete_maillist(self, arguments):
        unique_list_identifier = int(arguments[0]) - 1
        desired_list = self.mail_lists[unique_list_identifier]
        if desired_list.remove_list() is True:
            return "{} was deleted.".format(desired_list.get_name())
        return "You crazy bastard. Stop playing with fire!"

    def callback_update_maillist(self, arguments):
        unique_list_identifier = int(arguments[0]) - 1
        new_list_name = arguments[1]
        to_be_deleted_list = self.mail_lists[unique_list_identifier]
        old_name = to_be_deleted_list._name
        old_subscribers = to_be_deleted_list._subscribers
        self.mail_lists.pop(unique_list_identifier)
        mail_list = Database(new_list_name)
        mail_list._subscribers = old_subscribers
        self.mail_lists.append(mail_list)
        mail_list.save("file")
        remove("./Lists/{}".format(to_be_deleted_list.get_file_name()))
        return "Updated <{}> to <{}>".format(old_name, mail_list._name)

    def callback_search_by_email(self, arguments):
        found_in_lists = []
        needle_email = arguments[0]
        for maillist_object in self.mail_lists:
            if maillist_object.has_subscriber_with_email(needle_email) is True:
                found_in_lists.append(maillist_object._name)
        return "\n".join(found_in_lists)

    def callback_merge_lists(self, arguments):
        list_id_a = int(arguments[0]) - 1
        list_id_b = int(arguments[1]) - 1
        new_list_name = arguments[2]
        list_a = self.mail_lists[list_id_a]
        list_b = self.mail_lists[list_id_b]
        a_subscribers = list_a._subscribers
        b_subscribers = list_b._subscribers
        a_name = list_a._name
        b_name = list_b._name
        mail_list = Database(new_list_name)
        mail_list._subscribers = dict(a_subscribers, **b_subscribers)
        self.mail_lists.append(mail_list)
        return "Merged <{}> and <{}> into <{}>".format(a_name, b_name, new_list_name)

    def callback_export_json(self, arguments):
        unique_list_identifier = int(arguments[0]) - 1
        desired_list = self.mail_lists[unique_list_identifier]
        desired_list.save("json")
        return "Exported <{}> to <{}.json>".format(desired_list.get_name(), desired_list.get_file_name())

    def callback_welcome(self):
        return "Hello Stranger! This is a cutting-edge, console-based mail-list!\nType help, to see a list of commands."

    def callback_help(self, arguments):
        help_message = ("Here is a full list of commands:",
                        "* show_lists - Prints all lists to the screen. Each list is assigned with a unique identifier",
                        "* show_list <unique_list_identifier> - Prints all people, one person at a line, that are subscribed for the list. The format is: <Name> - <Email>",
                        "* add <unique_list_identifier> - Starts the procedure for adding a person to a mail list. The program prompts for name and email.",
                        "* update_subscriber <unique_list_identifier> <unique_name_identifier> - updates the information for the given subscriber in the given list",
                        "* remove_subscriber <unique_list_identifier> <unique_name_identifier> - Removes the given subscriber from the given list",
                        "* create <list_name> - Creates a new empty list, with the given name.",
                        "* update <unique_list_identifier>  <new_list_name> - Updates the given list with a new name.",
                        "* search_email <email> - Performs a search into all lists to see if the given email is present. Shows all lists, where the email was found.",
                        "* merge_lists <list_identifier_1> <list_identifier_2> <new_list_name> - merges list1 and list2 into a new list, with the given name.",
                        "* export <unique_list_identifier> - Exports the given list into JSON file, named just like the list. All white spaces are replaced by underscores.",
                        "* exit - this will quit the program")
        return "\n".join(help_message)

    def callback_exit(self):
        exit("Exiting.")

    def update_mail_lists(self, arguments):
        for filename in self.fetch_maillists():
            opened_file = open(filename, "r")
            contents = opened_file.readlines()
            filename = filename.split("/")[2]
            maillist = Database(filename)
            for record in contents:
                record = record.split(" - ")
                maillist.add_subscriber(record[0], record[1].rstrip())
            self.mail_lists.append(maillist)
            opened_file.close()

    def fetch_maillists(self):
        return glob("./Lists/*[!.json]")

    def _init_callbacks(self):
        print(self.callback_welcome())
        self.cp.on("show_lists", self.callback_show_lists)
        self.cp.on("show_list", self.callback_show_list)
        self.cp.on("add", self.callback_add_subscriber)
        self.cp.on("update_subscriber", self.callback_update_subscriber)
        self.cp.on("remove_subscriber", self.callback_remove_subscriber)
        self.cp.on("create", self.callback_create_maillist)
        self.cp.on("update", self.callback_update_maillist)
        self.cp.on("search_email", self.callback_search_by_email)
        self.cp.on("merge", self.callback_merge_lists)
        self.cp.on("export", self.callback_export_json)
        self.cp.on("help", self.callback_help)
        self.cp.on("exit", self.callback_exit)

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 31
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        #self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = {}

    # --- DATABASE hendeling  ---
        self.db_path = "lists/"
        self.db_name = "database.db"
        self.db_conn = None  # keeps the connection to the database

        self.db_maillists = " maillsits (id INTEGER PRIMERY KEY, name text"
        self.db_subsrcibers = " subscribers (id INTEGER PRIMERY KEY," +\
                              "name text, email text)"
        self.db_list_to_subs = " list_to_subscribers (list_id int," +\
                               " subscribers_id int)"

        self.__ensure_database()
    # --- End Database handeling ---

        self._load_initial_state()
        self._init_callbacks()
        self._loop()

    def __ensure_database(self):
        self.db_conn = sqlite3.connect(self.db_path + self.db_name)
        command = "CREATE TABLE IF NOT EXISTS"

      # Lists all the tables
        list_of_tables = [self.db_maillist,
                          self.db_subsrcibers, self.db_list_to_subs]
      # Creates all the tables of the database
        for table in list_of_tables:
            self.db_conn.execute(command + table)

    def create_list_callback(self, arguments):
        name = " ".join(arguments)

        maillist = MailList(-1, name)
        maillist_adapter = MailListFileAdapter(self.db_path, maillist)
        maillist_adapter.save()

        self.lists[maillist.get_id()] = (maillist, maillist_adapter)

    def add_subscriber_callback(self, arguments):
        list_id = int("".join(arguments))
        name = input("name>")
        email = input("email>")

        self.lists[list_id][0].add_subscriber(name, email)
        self._notify_save(list_id)

    def show_lists_callback(self, arguments):
        for list_id in self.lists:
            current_list = self.lists[list_id][0]
            print("[{}] {}".format(list_id,
                                   current_list.get_name()))

    def show_list_callback(self, arguments):
        list_id = int("".join(arguments))

        if list_id in self.lists:
            subscribers = self.lists[list_id][0].get_subscribers()
            for s in subscribers:
                print("{} - {}".format(s[0], s[1]))
        else:
            print("List with id <{}> was not found".format(list_id))

    def exit_callback(self, arguments):
        sys.exit(0)

    def _load_initial_state(self):
        dir_lists = map(basename, glob(self.db_path + "*"))

        for list_file in dir_lists:
            adapter = MailListFileAdapter(self.db_path)
            parsed_list = adapter.load(list_file)

            maillist_adapter = MailListFileAdapter(self.db_path, parsed_list)

            self.lists[parsed_list.get_id()] = (parsed_list, maillist_adapter)

    def _init_callbacks(self):
        self.cp.on("create", self.create_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("exit", self.exit_callback)
        # TODO - implement the rest of the callbacks

    def _notify_save(self, list_id):
        self.lists[list_id][1].save()

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 32
0
 def __init__(self):
     self.cp = CommandParser()
     self.db = db_interface.DBInterface("mail_lists.db")
     self._init_callbacks()
     self._loop()
Exemplo n.º 33
0
 def setUp(self):
     self.cp = CommandParser()
     self.called = False
Exemplo n.º 34
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        self.cp = CommandParser()
        self.db = db_interface.DBInterface("mail_lists.db")
        self._init_callbacks()
        self._loop()

    def create_list_callback(self, arguments):
        name = " ".join(arguments)
        if self.db.create_maillist(name) is True:
            return "<{}> was created.".format(name)
        else:
            return "<{}> failed to create.".format(name)

    def add_subscriber_callback(self, arguments):
        list_id = arguments[0]
        name = input("name>")
        email = input("email>")

        if self.db.add_subscriber(name, email, list_id) is True:
            list_name = self.db.fetch_maillist_name_by_id(list_id)["name"]
            return "{} added to list {}".format(name, list_name)
        else:
            return "Failed to add <{}> to list <{}>."

    def show_lists_callback(self, arguments):
        output_message = []
        for dictionary in self.db.fetch_maillists():
            string = "[{}] <{}>".format(dictionary["id"], dictionary["name"])
            output_message.append(string)
        return "\n".join(output_message)

    def show_list_callback(self, arguments):
        try:
            list_id = int("".join(arguments))
        except ValueError:
            return "Error: Invalid list id."
        output_message = []
        try:
            subscribers = self.db.fetch_subscribers(list_id)
            list_name = self.db.fetch_maillist_name_by_id(list_id)["name"]
            output_message.append("~~~~~~~<{}>~~~~~~~".format(list_name))
            for line in subscribers:
                output_message.append("[{}] <{}> - <{}>".format(
                    line["subscriber_id"], line["name"], line["email"]))
        except TypeError:
            output_message.append(
                "List with id <{}> was not found.".format(list_id))
        return "\n".join(output_message)

    def delete_mail_list_callback(self, arguments):
        maillist_id = " ".join(arguments)
        self.db.delete_maillist_by_id(maillist_id)
        return "Mail list with id {} was deleted.".format(maillist_id)

    def update_mail_list_name_callback(self, arguments):
        maillist_id = arguments[0]
        arguments.remove(maillist_id)
        new_name = " ".join(arguments)
        if self.db.update_maillist_name(maillist_id, new_name) is True:
            return "Mail list with id {} updated to <{}>.".format(
                maillist_id, new_name)
        else:
            return "Mail list with id {} not found.".format(maillist_id)

    def update_subscriber_callback(self, arguments):
        list_id = arguments[0]
        subscriber_id = arguments[1]
        name = str(input("name>"))
        email = str(input("email>"))
        data = {}
        data["name"] = name
        data["email"] = email
        self.db.update_subscriber(list_id, subscriber_id, data)
        return "Updated <{}>.".format(data["name"])

    def remove_subscriber_callback(self, arguments):
        list_id = arguments[0]
        subscriber_id = arguments[1]
        if self.db.delete_subscriber(list_id, subscriber_id) is True:
            return "{} deleted from {}".format()

    def search_email_callback(self, arguments):
        email = arguments[0]
        found_in_lists = self.db.fetch_maillists_by_subscriber_email(email)
        output_message = []
        for a_list in found_in_lists:
            output_message.append("[{}] {}".format(a_list["id"],
                                                   a_list["name"]))
        return "\n".join(output_message)

    def merge_lists_callback(self, arguments):
        list_id_a = arguments[0]
        list_id_b = arguments[1]
        arguments.remove(list_id_a)
        arguments.remove(list_id_b)
        new_list_name = " ".join(arguments)
        self.db.merge_lists(list_id_a, list_id_b, new_list_name)
        return "Merged lists with ids {} and {} to <{}>".format(
            list_id_a, list_id_b, new_list_name)

    def export_json_callback(self, arguments):
        list_id = arguments[0]
        json_contents = self.db.export_json(list_id)
        list_name = self.db.fetch_maillist_name_by_id(list_id)["name"].replace(
            " ", "_")
        file_name = "{}.json".format(list_name)
        opened_file = open(file_name, "w")
        opened_file.write(json_contents)
        opened_file.close()
        return "{} exported to {}".format(list_name, file_name)

    def help_callback(self, arguments):
        output_message = (
            "Here is a full list of commands:",
            "* show_lists - Prints all lists to the screen. Each list is assigned with a unique identifier",
            "* show_list <unique_list_identifier> - Prints all people, one person at a line, that are subscribed for the list. The format is: <Name> - <Email>",
            "* add <unique_list_identifier> - Starts the procedure for adding a person to a mail list. The program prompts for name and email.",
            "* update_subscriber <unique_list_identifier> <unique_name_identifier> - updates the information for the given subscriber in the given list",
            "* remove_subscriber <unique_list_identifier> <unique_name_identifier> - Removes the given subscriber from the given list",
            "* create <list_name> - Creates a new empty list, with the given name.",
            "* update <unique_list_identifier>  <new_list_name> - Updates the given list with a new name.",
            "* delete <unique_list_identifier> - Deletes the given list from the database.",
            "* search_email <email> - Performs a search into all lists to see if the given email is present. Shows all lists, where the email was found.",
            "* merge_lists <list_identifier_1> <list_identifier_2> <new_list_name> - merges list1 and list2 into a new list, with the given name.",
            "* export <unique_list_identifier> - Exports the given list into JSON file, named just like the list. All white spaces are replaced by underscores.",
            "* exit - this will quit the program")
        return "\n".join(output_message)

    def exit_callback(self, arguments):
        exit(0)

    def _init_callbacks(self):
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("update_subscriber", self.update_subscriber_callback)
        self.cp.on("remove_subscriber", self.remove_subscriber_callback)
        self.cp.on("delete", self.delete_mail_list_callback)
        self.cp.on("create", self.create_list_callback)
        self.cp.on("update", self.update_mail_list_name_callback)
        self.cp.on("search_email", self.search_email_callback)
        self.cp.on("merge_lists", self.merge_lists_callback)
        self.cp.on("export_json", self.export_json_callback)
        self.cp.on("exit", self.exit_callback)
        self.cp.on("help", self.help_callback)

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 35
0
class CLI():
    """docstring for CLI"""
    def __init__(self):
        self.cp = CommandParser()
        self.fh = FileHandler()
        self._init_callbacks()
        self._loop()

    def callback_take(self, arguments):
        try:
            name = arguments[0]
            price = int(arguments[1])
        except IndexError:
            return "Error: Give arguments as \"take <name> <price>\""
        if self.fh.take_order(name, price) is True:
            return "Taking order from {} for {}".format(name, price)

    def callback_status(self, arguments):
        return self.fh.list_orders()

    def callback_save(self, arguments):
        if self.fh.save_file() is True:
            return "Saved."

    def callback_list(self, arguments):
        return self.fh.list_files()

    def callback_load(self, arguments):
        try:
            list_id = int(arguments[0]) - 1
        except IndexError:
            return "Error: Invalid List ID."
        if self.fh.load_file(list_id) is None:
            return "Use list command before loading."
        elif self.fh.load_file(list_id) is False:
            return "You have not saved the current order.\nIf you wish to discard it, type load <number> again."
        elif self.fh.load_file(list_id) is True:
            return "Loaded {}.".format(self.fh.fetch_file_name(list_id))

    def callback_history(self, arguments):
        return self.fh.fetch_history()

    def callback_finish(self, arguments):
        return exit()

    def callback_help(self, arguments):
        help_message = ("Error: Unknown command!", "Try one of the following:",
                        " take <name> <price>", " status", " save", " list",
                        " load <number>", " finish")
        return "\n".join(help_message)

    def _init_callbacks(self):
        self.cp.on("take", self.callback_take)
        self.cp.on("status", self.callback_status)
        self.cp.on("save", self.callback_save)
        self.cp.on("list", self.callback_list)
        self.cp.on("load", self.callback_load)
        self.cp.on("finish", self.callback_finish)
        self.cp.on("help", self.callback_help)
        self.cp.on("history", self.callback_history)

    def _loop(self):
        while True:
            command = input("command>")
            self.cp.take_command(command)
Exemplo n.º 36
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        self.db_path = "maillist"
        self.conn=sqlite3.connect(self.db_path)
        self.create_table(self.conn.cursor())
        self.factory = MailListDataBaseFactory(self.conn)
        self.cp = CommandParser()
        self.lists = {}
        self._load_initial_state()
        self._init_callbacks()
        self._loop()
    def create_table(self,cursor):
        cursor.execute(''' CREATE TABLE IF NOT EXISTS maillist
            (maillist_id INTEGER PRIMARY KEY, name text)''')
        cursor.execute(''' CREATE TABLE IF NOT EXISTS subscribers
            (subscriber_id INTEGER PRIMARY KEY, name text, email text)''')
        cursor.execute(''' CREATE TABLE IF NOT EXISTS maillists_to_subscribers
            (maillist_id int, subscriber_id int)''')
    def create_list_callback(self, arguments):
        name = " ".join(arguments)

        maillist = self.factory.create(name)
        maillist_adapter = MailListDataBaseAdapter(self.db_path,maillist)
        maillist_adapter.save()
        self.lists[maillist.get_id()] = (maillist, maillist_adapter)

    def add_subscriber_callback(self, arguments):
        list_id = int("".join(arguments))
        if not list_id in self.lists:
            print("Id is incorrect, try again.")
        else:
            name = input("name>")
            email = input("email>")

            self.lists[list_id][0].add_subscriber(name, email)
            #TODO: function which add subscriber into tables

    def show_lists_callback(self, arguments):
        for list_id in self.lists:
            current_list = self.lists[list_id][0]
            print("[{}] {}".format(list_id,
                                   current_list.get_name()))

    def show_list_callback(self, arguments):
        list_id = int("".join(arguments))

        if list_id in self.lists:
            subscribers = self.lists[list_id][0].get_subscribers()
            for s in subscribers:
                print("{} - {}".format(s[0], s[1]))
        else:
            print("List with id <{}> was not found".format(list_id))

    def exit_callback(self, arguments):
        sys.exit(0)

    def _load_initial_state(self):
        c=self.conn;
        ids_of_maillists=c.execute("SELECT maillist_id FROM maillist").fetchall()
        for id in ids_of_maillists:
            adapter=MailListDataBaseAdapter("maillist")
            maillist=adapter.load(id[0])
            self.lists[id[0]]=(maillist,adapter)
    def _init_callbacks(self):
        self.cp.on("create", self.create_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("exit", self.exit_callback)
        # TODO - implement the rest of the callbacks

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 37
0
class ZooSim():
    def __init__(self, database_name):
        self.cp = CommandParser()
        self.db = DBinterface(database_name)
        self.zoos = self.db.update_zoos()
        self._init_callbacks()
        self._loop()

    def callback_list_animal_species(self, arguments):
        output = []
        for i, specie in enumerate(self.db.fetch_species()):
            output.append("[{}] {}".format(i+1, specie["species"]))
        return "\n".join(output)

    def callback_list_zoos(self, arguments):
        output_list = []
        for i, zoo in enumerate(self.db.get_zoos()):
            output_list.append("[{}] <{}> <{}> <${}>".format(i+1, zoo["name"], zoo["capacity"], zoo["budget"]))
        return "\n".join(output_list)

    def callback_create_zoo(self, arguments):
        name = input("name>")
        capacity = input("capacity>")
        budget = input("budget>")
        zoo = self.db.create_zoo(name, capacity, budget)
        if zoo is False:
            return "Zoo with name <{}> already exists. Try to be more original!".format(name)
        self.zoos.append(zoo)
        return "Zoo <{}> created.".format(name)

    def callback_see_animals(self, arguments):
        zoo_id = arguments[0]
        try:
            desired_zoo = self.zoos[int(zoo_id)-1]
        except (ValueError, IndexError):
            return "No zoo with id <{}>.".format(zoo_id)
        return desired_zoo.see_animals()

    def callback_exit(self, arguments):
        exit(0)

    def callback_add_animal(self, arguments):
        zoo_id = int(arguments[0]) - 1
        desired_zoo = self.zoos[zoo_id]
        zoo_name = desired_zoo.get_name()
        species = input("species>")
        age = int(input("age>"))
        name = input("name>")
        gender = input("gender>")
        weight = float(input("weight>"))
        animal = self.db.create_animal(zoo_name, species, age, name, gender, weight)
        if animal is False:
            return "Failed to add <{}> the <{}>. He/she already exists!".format(name, species)
        if desired_zoo.add_animal(animal) is True:
            return "Added <{}> to zoo <{}>".format(name, desired_zoo.get_name())
        return "Failed to add <{}> the <{}>. Zoo <{}> is already full!".format(name, species, zoo_name)

    def callback_remove_animal(self, arguments):
        zoo_id = int(arguments[0]) - 1
        animal_id = int(arguments[0]) - 1
        desired_zoo = self.zoos[zoo_id]
        try:
            desired_zoo.remove_animal(animal_id)
        except IndexError:
            return "Animal with ID <{}>, doesn't exist in Zoo <{}>".format(animal_id, desired_zoo.get_name())
        return "Removed animal from zoo <{}>".format(desired_zoo.get_name())

    def callback_simulate_time(self, arguments):
        zoo_id = int(arguments[0]) - 1
        zoo_object = self.zoos[zoo_id]
        period_type = arguments[1]
        period = int(arguments[2])
        simulation = TimeSpanSimulator(zoo_object, period_type, period)

    def callback_help(self, arguments):
        help_message = ("* list_species - lists known animal species",
                        "* list_zoos - lists all created zoos",
                        "* see_animals <zoo_id> - lists all animal from the zoo matching the zoo_id (use list_zoos before hand)",
                        "* create_zoo - creates a zoo. Science!",
                        "* accommodate <zoo_id> - accommodates an animal in the zoo matching the zoo_id",
                        "* move_to_habitat <zoo_id> - releases an animal from the zoo matching the zoo_id",
                        "* simulate <zoo_id> <period_type> <period> - simulates a time span for the given zoo",
                        "* exit - exits. Yes, it does.")
        return "\n".join(help_message)

    def _init_callbacks(self):
        self.cp.on("list_species", self.callback_list_animal_species)
        self.cp.on("list_zoos", self.callback_list_zoos)
        self.cp.on("see_animals", self.callback_see_animals)
        self.cp.on("create_zoo", self.callback_create_zoo)
        self.cp.on("accommodate", self.callback_add_animal)
        self.cp.on("move_to_habitat", self.callback_remove_animal)
        self.cp.on("simulate", self.callback_simulate_time)
        self.cp.on("help", self.callback_help)
        self.cp.on("exit", self.callback_exit)

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 38
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        self.cp = CommandParser()
        self.lists = {}
        self.db_path = "lists/"
        self.adapter = SQLRelationList(self.db_path)

        self._load_initial_state()
        self._init_callbacks()
        self._loop()

    def create_list_callback(self, arguments):
        name = " ".join(arguments)
        maillist = MailList(name)
        list_id = self.adapter.sql_mail.save(name)
        self.lists[list_id] = maillist

    def add_subscriber_callback(self, arguments):
        list_id = int("".join(arguments))
        name = input("name>")
        email = input("email>")
        subscriber = Subscriber(name, email)

        if self.lists[list_id].add_subscriber(subscriber):
        #add subscriber to the database and get subscriber id
            subscriber_id = self.adapter.sql_subscriber_table.save(subscriber)
        #add the list_id<->subscriber_id relation to the relation table
            self.adapter.add_relation(list_id, subscriber_id)
        # self._notify_save(list_id)

    def show_lists_callback(self, arguments):
        for list_id in self.lists:
            current_list = self.lists[list_id]
            print("[{}] {}".format(list_id,
                                   current_list.get_name()))

    def show_list_callback(self, arguments):
        list_id = int("".join(arguments))

        if list_id in self.lists:
            subscribers = self.lists[list_id].get_subscribers()
            for s in subscribers:
                print("{} - {}".format(s[0], s[1]))
        else:
            print("List with id <{}> was not found".format(list_id))

    def exit_callback(self, arguments):
        sys.exit(0)

#load all lists in the database into self.lists
    def _load_initial_state(self):
        lists = self.adapter.sql_mail.get_lists()
        for unparsed_list in lists:
            list_id = unparsed_list[0]
            list_name = unparsed_list[1]
            maillist = MailList(list_name)
            #load list subscribers
            subscribers = self.adapter.get_subscribers_in_list(list_id)
            for subscriber in subscribers:
                maillist.subscribers.append(subscriber)
            self.lists[list_id] = maillist

    def _init_callbacks(self):
        self.cp.on("create", self.create_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("exit", self.exit_callback)
        # TODO - implement the rest of the callbacks

    # def _notify_save(self, list_id):
    #     self.lists[list_id].save()

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 39
0
 def __init__(self):
     self.modules = {}
     self.communicator = None
     self.services = None
     self.cparser = CommandParser()
Exemplo n.º 40
0
class MailListProgram():
    """docstring for MailListProgram"""
    def __init__(self):
        self.factory = MailListFactory()
        self.cp = CommandParser()
        self.lists = []

        self._load_initial_state()
        self._init_callbacks()
        self._loop()

    def create_list_callback(self, arguments):
        name = " ".join(arguments)

        maillist = self.factory.create(name)
        maillist_adapter = MailListFileAdapter(self.db_path, maillist)
        maillist_adapter.save()

        self.lists.append(maillist.get_name())
        print(self.lists)

    def add_subscriber_callback(self, arguments):
        list_id = int("".join(arguments))
        name = input("name>")
        email = input("email>")
        subscriber = Subscriber(name, email)
        subscriber.save()
        self.db_path = sqlite3.connect("maillist.db")
        self.cursor = self.db_path.cursor()
        self.cursor.execute("""CREATE TABLE IF NOT EXISTS relations
                            (list_id, subscriber_id)""")
        query = ("""INSERT INTO relations(list_id, subscriber_id)
                    VALUES(?, ?)""")
        data = [list_id, subscriber.id]
        print(data)
        self.cursor.execute(query, data)
        self.db_path.commit()
        self.db_path.close()

    def show_lists_callback(self, arguments):
        for list_id in self.lists:
            current_list = self.lists[list_id][0]
            print("[{}] {}".format(list_id,
                                   current_list.get_name()))

    def show_list_callback(self, arguments):
        list_id = int("".join(arguments))

        if list_id in self.lists:
            subscribers = self.lists[list_id][0].get_subscribers()
            for s in subscribers:
                print("{} - {}".format(s[0], s[1]))
        else:
            print("List with id <{}> was not found".format(list_id))

    def exit_callback(self, arguments):
        sys.exit(0)

    def _load_initial_state(self):
        if os.path.isfile("maillist.db"):
            self.db_path = sqlite3.connect("maillist.db")
            self.cursor = self.db_path.cursor()
            lists_data = self.cursor.execute("""SELECT name FROM Lists""")
            for list in lists_data:
                self.lists.append(list[0])

    def _init_callbacks(self):
        self.cp.on("create", self.create_list_callback)
        self.cp.on("add", self.add_subscriber_callback)
        self.cp.on("show_lists", self.show_lists_callback)
        self.cp.on("show_list", self.show_list_callback)
        self.cp.on("exit", self.exit_callback)
        # TODO - implement the rest of the callbacks

    def _notify_save(self, list_id):
        self.lists[list_id - 1].save()

    def _loop(self):
        while True:
            command = input(">")
            self.cp.take_command(command)
Exemplo n.º 41
0
 def setUp(self):
     self.cp = CommandParser()
     self.called = False
Exemplo n.º 42
0
class TestCommandParser(unittest.TestCase):
    def setUp(self):
        self.cp = CommandParser()
        
    def testSayCommand(self):
        self.assertEqual('PRIVMS #dickler :hello to everyone', self.cp.parse('say #dickler hello to everyone'))