예제 #1
0
 def show_validation(self):
     Utility.clear()
     if self.validate() == 0:
         print("Validates.")
     else:
         print("Does NOT validate.")
     input("Press 'Enter' to continue: ")
예제 #2
0
    def show_add_element(self, element=None):
        menu = None
        # Get the element from the user.
        if element is None:
            menu = True
            Utility.clear()
            # Generate new element.
            element = self._generate_libtype_element()
            # Return if element is still None.
            if element is None:
                input("Press 'Enter' to return to menu: ")
                return

            print("Adding item:")
            print(element)
            answer = Utility.get_answer_yn("Add item?")
            # User wants to quit.
            if answer == "n":
                return

        # Add item.
        if self.add_element(element) == 0:
            print("The item {} has been added successfully.".format(element))
        else:
            print("The item {} has not been added.".format(element))

        if menu:
            input("Press 'Enter' to return to menu: ")
예제 #3
0
    def show_restore(self):
        Utility.clear()
        backupfile = self._xmlfile + ".back"
        if os.path.isfile(backupfile):
            # Validate backup file before continue.
            if Utility.validate(self._xsdfile, backupfile) != 0:
                print("'{}' is not a valid library file.".format(
                    self._xmlfile))
                print("Nothing has changed.")
                input("Press 'Enter' to continue: ")
                return
            # Ask user for overwriting existing library file.
            overwrite = Utility.get_answer_yn(
                "This operation will overwrite existing library if any. Continue?"
            )

            # Making sure that only Y or y will overwrite the backup.
            if overwrite != "y":
                print("Nothing has changed.")
                input("Press 'Enter' to continue: ")
                return

            # Restore library file, overwriting existing one if any.
            if self.restore() == 0:
                print("Library file has been restored successfully.")
            else:
                print("Library restoration process has failed.")
                print(
                    "Make sure a [valid] '{}' file exists and you have write privilege in containing folder."
                    .format(backupfile))
        else:
            print("No backup file has been found.")
        input("Press 'Enter' to continue: ")
예제 #4
0
 def show_search_elements(self, element=None, value=None, ascending=True):
     menu = None
     # Get all elements
     if element is None:
         menu = True
         # Get user input.
         element = self.get_sorting_element()
         value = input("Enter a value to search for: ")
         elements = self.search_elements(element, value,
                                         self.get_sorting_order())
         Utility.clear()
     else:
         elements = self.search_elements(element, value, ascending)
     # Display results
     if isinstance(elements, int):
         print("Invalid storage file {}.".format(self._xmlfile))
     elif elements is None:
         print("No item with '{}' containing '{}' has been found.".format(
             element.title(), value))
     else:
         # Show table of results.
         self.show_table(elements)
     # Pause if the method has been called without an element.
     if menu:
         print()
         input("Press 'Enter' to return to menu: ")
예제 #5
0
    def show_menu(self):
        # Initialize local variables
        avtypes = self.library_types()
        avchoices = range(len(avtypes) + 1)
        choice = None

        # Generate menu
        while choice not in avchoices:
            # Clear display.
            Utility.clear()
            # Display menu
            print("Available library types:")
            index = 0
            for t in avtypes:
                index += 1
                print("{}. {}".format(index, t.title()))
            print("0. Quit")
            # Get user choice.
            try:
                choice = int(input("Enter your choice: "))
            except ValueError:
                choice = None

            # Exit menu.
            if choice == 0:
                return
            elif choice in avchoices:
                self.load_library(avtypes[choice - 1])
            choice = None
    def _generate_installer(self, game):
        Utility.clear()
        # Display header.
        print("Installer Editor")
        print()
        if "installer" in game:
            removelist = []
            # Generate range of menu values once.
            choices = range(1, 4)
            for installer in game["installer"]:
                print("Installer:")
                print("    System: {}".format(installer["system"]))
                if "lastupdated" in installer:
                    print("    Last updated: {}".format(
                        installer["lastupdated"]))
                if "filename" in installer:
                    print("    File(s): {}".format(installer["filename"]))

                # Display menu
                print("1. Keep and continue")
                print("2. Remove installer")
                print("3. Edit installer")
                # Get action from the user.
                choice = None
                # Generate menu
                while choice not in choices:
                    # Get user choice.
                    try:
                        choice = int(input("Enter your choice: "))
                    except ValueError:
                        choice = None

                    # React to user choice.
                    if choice == 1:
                        # Pass for 1.
                        # Alternatively break out of the loop.
                        pass
                    elif choice == 2:
                        # Add elements to removal list.
                        removelist.append(installer)
                        print("Installer has been removed.")
                    elif choice == 3:
                        self._get_installer_values(installer)
                    else:
                        choice = None
            # Remove marked installers permanently.
            for rvalue in removelist:
                game["installer"].remove(rvalue)
            # If list is empty remove respective game dictionary key.
            if len(game["installer"]) == 0:
                del game["installer"]
        # Add new installer.
        game = self._generate_new_installer(game)

        return game
    def _get_installer_values(self, installer=None):
        Utility.clear()
        # Display header.
        if installer is None:
            print("New", end=" ")
            installer = {"system": None}
        print("Installer")
        print()
        # Get installer's values.
        # Get system.
        systems = ['Windows', 'Mac', 'Linux', 'Other']
        schoices = range(1, 5)
        system = None
        while system not in systems:
            # Display menu
            print("System{}: ".format(
                "" if installer["system"] is None else "[" +
                installer["system"] + "]"))
            for s in systems:
                print("{}. {}".format(systems.index(s) + 1, s))
            # Get user choice.
            try:
                choice = input("Enter your choice: ")
                if choice == "":
                    system = installer["system"]
                else:
                    choice = int(choice)
                    if choice in schoices:
                        system = systems[choice - 1]
            except ValueError:
                choice = None
        installer["system"] = system
        # Get lastupdated.
        lastupdated = None
        while lastupdated is None:
            print("Date should be written in form YYYY-MM-DD.")
            lastupdated = input("Last updated at{}: ".format(
                "[" + installer["lastupdated"] +
                "]" if "lastupdated" in installer else ""))
            # Check if value is a valid date.
            valid = Utility.validate_date(lastupdated)
            if valid is not None:
                installer["lastupdated"] = valid
            elif lastupdated == "":
                # Pass for 1.
                # Alternatively break out of the loop.
                pass
            else:
                lastupdated = None
        # Get filenames.
        installer = self._generate_filename(installer)

        return installer
    def _generate_libtype_element(self, element=None):
        # Display header.
        if element is None:
            print("New", end=" ")
            element = {"title": None, "shop": None, "finished": None}
        print("Game Editor")
        print()
        # Get game's elements.
        title = ""
        while title == "":
            title = input(
                "Title{}: ".format("" if element["title"] is None else "[" +
                                   element["title"] + "]"))
            if element["title"] is not None and title == "":
                title = element["title"]
        # Exit editor if the user is trying to create a game, which already exists.
        if element["title"] is None and self.get_element(title) is not None:
            print("Game {} already exists.".format(title))
            return None
        # Exit editor if new title already exists.
        if element["title"] is not None:
            if title != element["title"] and self.get_element(
                    title) is not None:
                print("Title '{}' has already been used for a game.".format(
                    title))
                return None

        element["title"] = title

        shop = ""
        while shop == "":
            shop = input(
                "Shop{}: ".format("" if element["shop"] is None else "[" +
                                  element["shop"] + "]"))
            if element["shop"] is not None and shop == "":
                shop = element["shop"]
        element["shop"] = shop

        finished = Utility.get_answer_yn(
            "Finished{}:".format("" if element["finished"] is None else "[" +
                                 element["finished"] + "]"))
        if finished == "y":
            element["finished"] = "Yes"
        else:
            element["finished"] = "No"

        # Get game's installer elements.
        if Utility.get_answer_yn("Open installer editor?") == "y":
            element = self._generate_installer(element)
        # Return game dictionary.
        return element
예제 #9
0
    def show_remove_element(self, element=None):
        menu = None
        # Get the element's title from the user.
        if element is None:
            menu = True
            Utility.clear()
            element = input("Enter the {} of the item to be removed: ".format(
                self._uniquekey))
        # Remove item.
        if self.remove_element(element) == 0:
            print("The item {} has been removed successfully.".format(element))
        else:
            print("The item {} has not been removed.".format(element))

        if menu:
            input("Press 'Enter' to return to menu: ")
예제 #10
0
    def validate_configuration(self):
        # Validate configuration.
        if Utility.validate(self.__confxsd, self.__confxml) == 0:
            # Validation was successful.
            print("Validates")
        else:
            # Validation has failed.
            print("Configuration does not validate.")
            # Ask user for creating new configuration.
            newconf = ""
            while newconf != "y" and newconf != "n":
                newconf = Utility.get_answer_yn(
                    "Create new configuration files (will overwrite existed files)?"
                )

            if newconf == "y":
                # Create new configuration.
                self.configure()
예제 #11
0
 def show_edit_element(self, element=None):
     menu = None
     # Get the element's unique key from the user.
     if element is None:
         menu = True
         Utility.clear()
         element = input("Enter the {} of the item to be edited: ".format(
             self._uniquekey))
     # Get element.
     item = self.get_element(element)
     if item is None:
         print("No item with {} '{}' found.".format(self._uniquekey,
                                                    element))
     elif isinstance(item, int):
         print("Invalid storage file {}.".format(self._xmlfile))
     else:
         # Create python dictionary parsing element's values.
         itemdict = self._xmlitem_to_dict(item)
         # Edit item.
         itemdict = self._generate_libtype_element(itemdict)
         # Check if itemdict contains values.
         if itemdict is not None:
             #confirm before save.
             print("Saving item:")
             print(itemdict)
             answer = Utility.get_answer_yn("Save item?")
             # User wants to quit.
             if answer == "n":
                 return
             # Persist changes.
             try:
                 if self.edit_element(element, itemdict) == 0:
                     print(
                         "The edited item {} has been saved successfully.".
                         format(element))
                 else:
                     print("The edited item {} has not been saved.".format(
                         element))
             except OSError:
                 print(
                     "Temporary file ha not been removed, after the edited item {} has been saved."
                     .format(element))
     if menu:
         input("Press 'Enter' to return to menu: ")
예제 #12
0
    def _generate_libtype_element(self, element=None):
        # Display header.
        if element is None:
            print("New", end=" ")
            element = {"title": None, "formats": None}
        print("video Item Editor")
        print()
        # Get item's elements.
        title = ""
        while title == "":
            title = input(
                "Title{}: ".format("" if element["title"] is None else "[" +
                                   element["title"] + "]"))
            if element["title"] is not None and title == "":
                title = element["title"]
        # Exit editor if the user is trying to create an item, which already exists.
        if element["title"] is None and self.get_element(title) is not None:
            print("Item {} already exists.".format(title))
            return None
        # Exit editor if new title already exists.
        if element["title"] is not None:
            if title != element["title"] and self.get_element(
                    title) is not None:
                print("Title '{}' has already been used for an item.".format(
                    title))
                return None

        element["title"] = title

        # Edit mandatory lists.
        element = self._generate_list(
            element, "formats", ["DVD", "MP4", "AVI", "Blu-ray", "Other"])
        # Edit optional lists.
        element = self._generate_list(element, "genres", mandatory=False)

        # Edit optional elements.
        releasedate = None
        while releasedate is None:
            releasedate = input(
                "Publication date{} [YYYY-MM-DD or leave empty to remove]: ".
                format("[" + element["releasedate"] +
                       "]" if "releasedate" in element else ""))
            if releasedate == "":
                if "releasedate" in element:
                    del element["releasedate"]
            else:
                releasedate = Utility.validate_date(releasedate)
                if releasedate is not None:
                    element["releasedate"] = releasedate

        element = self._edit_optional_tag(element, "label")
        element = self._edit_optional_tag(element, "shop")

        # Return video item dictionary.
        return element
 def _edit_optional_tag(self, element, tag):
     choice = Utility.get_answer_yn("{} {}:".format("Edit" if tag in element else "Create", tag))
     if choice == "y":
         value = input("{}{} [leave empty to remove]: ".format(tag, "[" + element[tag] + "]" if tag in element else ""))
         if value == "":
             # Remove tag if exists.
             if tag in element:
                 del element[tag]
             return element
         element[tag] = value
     return element
예제 #14
0
 def show_all_elements(self, element=None, ascending=True, menu=None):
     # Get all elements
     if menu is None:
         elements = self.get_all_elements(element, ascending)
     else:
         # Get user input.
         elements = self.get_all_elements(self.get_sorting_element(),
                                          self.get_sorting_order())
         Utility.clear()
     # Display results
     if isinstance(elements, int):
         print("Invalid storage file {}.".format(self._xmlfile))
     elif elements is None:
         print("The library is empty.")
     else:
         # Show table of results.
         self.show_table(elements)
     # Pause if the method has been called without an element.
     if menu is not None:
         print()
         input("Press 'Enter' to return to menu: ")
 def _generate_new_installer(self, game):
     # Add new installer.
     installers = []
     while Utility.get_answer_yn("Add new installer?") == "y":
         newinst = self._get_installer_values()
         installers.append(newinst)
     # Add installers to game.
     if installers:
         if "installer" in game:
             game["installer"] += installers
         else:
             game["installer"] = installers
     return game
예제 #16
0
    def get_sorting_element(self):
        # Generate menu
        choices = range(1, len(self._sortingtags) + 1)
        choice = None
        while choice not in choices:
            # Clear display.
            Utility.clear()
            # Display menu
            print("Element [to sort by, search for, etc]:")
            i = 0
            for sorttag in self._sortingtags:
                i += 1
                print("{}. {}".format(i, sorttag))
            # Get user choice.
            try:
                choice = input("Enter your choice [default 1]: ")
                if choice == "":
                    return self._sortingtags[0]
                choice = int(choice)
            except ValueError:
                choice = None

        return self._sortingtags[choice - 1]
예제 #17
0
    def show_utility_menu(self):
        # Initialize local variables
        avchoices = range(1)
        choice = None

        # Generate menu
        while choice not in avchoices:
            # Clear display.
            Utility.clear()
            # Display menu
            print("Available storage utilities:")
            print("1. Validate library storage")
            print("2. Backup library")
            print("3. Restore library from backup")
            print("4. Create new empty library")
            print("5. Restore library schema")
            print("0. Back")
            # Get user choice.
            try:
                choice = int(input("Enter your choice: "))
            except ValueError:
                choice = None

            # React to user choice.
            if choice == 0:
                return
            elif choice == 1:
                self.show_validation()
            elif choice == 2:
                self.show_backup()
            elif choice == 3:
                self.show_restore()
            elif choice == 4:
                self.show_create_library()
            elif choice == 5:
                self.show_restore_schema()
            choice = None
예제 #18
0
    def show_menu(self):
        # Initialize local variables
        avchoices = range(7)
        choice = None

        # Generate menu
        while choice not in avchoices:
            # Clear display.
            Utility.clear()
            # Display menu
            print("Available actions for library {}:".format(
                self._libtype.upper()))
            print("1. Display all items")
            print("2. Display item by {}".format(self._uniquekey))
            print("3. Search for items")
            print("4. Add new item")
            print("5. Edit existing item")
            print("6. Remove item")
            print("9. Storage utilities")
            print("0. Exit library")
            # Get user choice.
            try:
                choice = int(input("Enter your choice: "))
            except ValueError:
                choice = None

            # React to user choice.
            if choice == 0:
                return
            elif choice == 1:
                Utility.clear()
                self.show_all_elements(menu=True)
            elif choice == 2:
                Utility.clear()
                self.show_element()
            elif choice == 3:
                Utility.clear()
                self.show_search_elements()
            elif choice == 4:
                self.show_add_element()
            elif choice == 5:
                self.show_edit_element()
            elif choice == 6:
                self.show_remove_element()
            elif choice == 9:
                self.show_utility_menu()
            choice = None
예제 #19
0
    def show_backup(self):
        Utility.clear()
        if os.path.isfile(self._xmlfile + ".back"):
            # Ask user for overwriting existing backup file.
            overwrite = Utility.get_answer_yn(
                "A backup file already exists. Overwrite?")

            # Making sure that only Y or y will overwrite the backup.
            if overwrite != "y":
                print("Nothing has changed.")
                input("Press 'Enter' to continue: ")
                return

        # If there isn't any backup already or the user has entered Y or y
        # create a new backup, overwriting existing one if any.
        if self.backup() == 0:
            print("New backup file has been created successfully.")
        else:
            print("Backup process has failed.")
            print(
                "Make sure a [valid] '{}' file exists and you have write privilege in containing folder."
                .format(self._xmlfile))

        input("Press 'Enter' to continue: ")
예제 #20
0
    def get_sorting_order(self):
        # Generate menu
        choices = range(1, 3)
        choice = None
        while choice not in choices:
            # Clear display.
            Utility.clear()
            # Display menu
            print("Order:")
            print("1. Ascending")
            print("2. Descending")
            # Get user choice.
            try:
                choice = input("Enter your choice [default 1]: ")
                if choice == "":
                    return True
                choice = int(choice)
            except ValueError:
                choice = None

        if choice == 1:
            return True

        return False
예제 #21
0
    def show_create_library(self):
        Utility.clear()
        if os.path.isfile(self._xmlfile):
            # Ask user for overwriting existing library.
            overwrite = Utility.get_answer_yn(
                "This operation will overwrite the existing library. Continue?"
            )

            # Making sure that only Y or y will overwrite the existing library.
            if overwrite != "y":
                print("Nothing has changed.")
                input("Press 'Enter' to continue: ")
                return

        # If there isn't any library file already or the user has entered Y or y
        # create a new empty library, overwriting existing one if any.
        if self.create_library() == 0:
            print("New empty library has been created successfully.")
        else:
            print("New library creation process has failed.")
            print("Make sure you have write privilege in '{}' folder.".format(
                os.path.join(self._storageroot, self._libtype)))

        input("Press 'Enter' to continue: ")
예제 #22
0
    def show_restore_schema(self):
        Utility.clear()
        if os.path.isfile(self._xsdfile):
            # Ask user for overwriting existing schema file.
            overwrite = Utility.get_answer_yn(
                "This operation will overwrite the existing library schema. Continue?"
            )

            # Making sure that only Y or y will overwrite the existing schema.
            if overwrite != "y":
                print("Nothing has changed.")
                input("Press 'Enter' to continue: ")
                return

        # If there isn't any schema file already or the user has entered Y or y
        # restore the default library schema, overwriting existing one if any.
        if self.restore_schema() == 0:
            print("Default library schema has been restored successfully.")
        else:
            print("Library schema restoration process has failed.")
            print("Make sure you have write privilege in '{}' folder.".format(
                os.path.join(self._storageroot, self._libtype)))

        input("Press 'Enter' to continue: ")
예제 #23
0
    def _write_tree(self, nodes):
        # Create the xml tree.
        root = etree.XML("""
<library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="{}"></library>
            """.format(os.path.basename(self._xsdfile)))
        for node in nodes:
            root.append(node)
        # Generate new tree.
        xmlout = etree.ElementTree(root)
        # Validate tree.
        if Utility.validate_tree(self._xsdfile, xmlout) != 0:
            return 3
        # Write to file.
        try:
            xmlout.write(self._xmlfile,
                         xml_declaration=True,
                         encoding="UTF-8",
                         pretty_print=True)
            return 0
        except OSError:
            return 2
예제 #24
0
 def validate(self):
     return Utility.validate(self._xsdfile, self._xmlfile)
예제 #25
0
    def _generate_libtype_element(self, element=None):
        # Display header.
        if element is None:
            print("New", end=" ")
            element = {"title": None, "artist": None, "formats": None}
        print("Music Item Editor")
        print()
        # Get item's elements.
        title = ""
        while title == "":
            title = input(
                "Title{}: ".format("" if element["title"] is None else "[" +
                                   element["title"] + "]"))
            if element["title"] is not None and title == "":
                title = element["title"]
        # Exit editor if the user is trying to create an item, which already exists.
        if element["title"] is None and self.get_element(title) is not None:
            print("Item {} already exists.".format(title))
            return None
        # Exit editor if new title already exists.
        if element["title"] is not None:
            if title != element["title"] and self.get_element(
                    title) is not None:
                print("Title '{}' has already been used for an item.".format(
                    title))
                return None

        element["title"] = title

        # Edit mandatory elements.
        element = self._edit_mandatory_tag(element, "artist")

        # Edit mandatory lists.
        element = self._generate_list(element, "formats",
                                      ["CD", "MP3", "FLAC", "OGG", "Other"])
        # Edit optional lists.
        element = self._generate_list(element, "genres", mandatory=False)
        element = self._generate_list(element, "tracks", mandatory=False)
        # Check for track duplicates.
        # It not the most efficient way, but it needs no more methods right now.
        # Should be refactored later.
        while "tracks" in element and len(element["tracks"]) != len(
                set(element["tracks"])):
            # Edit tracks.
            print("Track list '{}' contains duplicates. Please remove them.".
                  format(element["tracks"]))
            element = self._generate_list(element, "tracks", mandatory=False)

        # Edit optional elements.
        releasedate = None
        while releasedate is None:
            releasedate = input(
                "Publication date{} [YYYY-MM-DD or leave empty to remove]: ".
                format("[" + element["releasedate"] +
                       "]" if "releasedate" in element else ""))
            if releasedate == "":
                if "releasedate" in element:
                    del element["releasedate"]
            else:
                releasedate = Utility.validate_date(releasedate)
                if releasedate is not None:
                    element["releasedate"] = releasedate

        element = self._edit_optional_tag(element, "label")
        element = self._edit_optional_tag(element, "shop")

        # Return music item dictionary.
        return element
예제 #26
0
 def __invalid_configuration_exit(self):
     # Load configuration
     if Utility.validate(self.__confxsd, self.__confxml) != 0:
         # Validation has failed.
         print("Invalid configuration. Please reconfigure the application")
         sys.exit(2)
    def _generate_libtype_element(self, element = None):
        # Display header.
        if element is None:
            print("New", end = " ")
            element = {"title": None, "authors": None, "category": None,
                       "formats": None, "isbn": None, "finished": None}
        print("Book Editor")
        print()
        # Get book's elements.
        isbn = ""
        while isbn == "":
            isbn = input("ISBN{}: ".format("" if element["isbn"] is None else "[" + element["isbn"] + "]"))
            if element["isbn"] is not None and isbn == "":
                isbn = element["isbn"]
            # Check if ISBN has 13 digits.
            pattern = re.compile("^\d{13}$")
            match = pattern.match(isbn)
            if match is None:
                print("ISBN should be 13 digits.".format(isbn))
                return None
        # Exit editor if the user is trying to create a book, which already exists.
        if element["isbn"] is None and self.get_element(isbn) is not None:
            print("Book {} already exists.".format(isbn))
            return None
        # Exit editor if new isbn already exists.
        if element["isbn"] is not None:
            if isbn != element["isbn"] and self.get_element(isbn) is not None:
                print("ISBN '{}' has already been used for a book.".format(isbn))
                return None

        element["isbn"] = isbn

        # Edit mandatory elements.
        element = self._edit_mandatory_tag(element, "title")
        element = self._edit_mandatory_tag(element, "category")

        # Edit mandatory lists.
        element = self._generate_mandatory_list(element, "authors")
        element = self._generate_mandatory_list(element, "formats", ["Hardback", "Paperback", "eBook", "Other"])

        finished = Utility.get_answer_yn("Finished{}:".format("" if element["finished"] is None else "[" + element["finished"] + "]"))
        if finished == "y":
            element["finished"] = "Yes"
        else:
            element["finished"] = "No"

        # Edit optional elements.
        publicationdate = None
        while publicationdate is None:
            publicationdate = input("Publication date{} [YYYY-MM-DD or leave empty to remove]: ".format("[" + element["publicationdate"] + "]" if "publicationdate" in element else ""))
            if publicationdate == "":
                if "publicationdate" in element:
                    del element["publicationdate"]
            else:
                publicationdate = Utility.validate_date(publicationdate)
                if publicationdate is not None:
                    element["publicationdate"] = publicationdate

        element = self._edit_optional_tag(element, "publisher")
        element = self._edit_optional_tag(element, "edition")
        element = self._edit_optional_tag(element, "pagenumber")
        element = self._edit_optional_tag(element, "lastpageread")
        element = self._edit_optional_tag(element, "shop")

        # Return book dictionary.
        return element