Пример #1
0
 def setUp(self, mockBooks_API, mockLibrary_DB):
     self.library = Library()
     self.patron = Patron("bob", "bobson", 41, 1)
     self.library.api = mockBooks_API
     self.library.db = mockLibrary_DB
     mockBooks_API.get_ebooks.return_value = [{
         'title': 'The Count of Monte Cristo',
         "ebook_count": 1
     }, {
         'title': 'A Tale of Two Cities',
         "ebook_count": 1
     }, {
         'title': '1984',
         "ebook_count": 1
     }, {
         'title': 'Slaughterhouse 5',
         "ebook_count": 1
     }, {
         'title': 'Breakfast of Champions',
         "ebook_count": 1
     }]
     mockBooks_API.books_by_author.return_value = [
         'Slaughterhouse 5', 'Breakfast of Champions'
     ]
     mockBooks_API.get_book_info.return_value = [{
         'title': 'The Count of Monte Cristo',
         "ebook_count": 1,
         'publisher': 'Penguin',
         'publish_year': '1844',
         'language': "french"
     }]
     mockLibrary_DB.patrons = [self.patron]
     mockLibrary_DB.update_patron = self.mock_update_patron
     mockLibrary_DB.insert_patron.return_value = 1
     mockLibrary_DB.retrieve_patron = self.mock_retrieve_patron
Пример #2
0
    def test_should_fetch_track_details(self):
        library = Library(self.library_name).create(self.folder_name)
        library_filter = library.view().by("ALBUM").filter()
        album_title = library_filter.ids[0]
        track = library_filter.using(album_title).ids[0]
        track_id = track["_id"]

        tags = library.track_details(track_id)
        self.assertTrue(tags)
Пример #3
0
 def setUp(self) -> None:
     self.CuT = Library()
     self.CuT.db.close_db()
     self.patron = Mock()
     self.book_title_there = 'Adventures of Elvis'
     self.book_title_not_there = 'Adventures of Dino'
     self.book_title_language = 'Harry Potter'
     self.book_author = 'Dummy Name'
     self.first_name = 'Sam'
     self.last_name = 'Wheeler'
     self.age = 27
     self.member_id = 100001
Пример #4
0
    def editLibrary(self, lib: Library) -> None:

        dlg: DetailsDialog = DetailsDialog(
            BackendTabs[cast(Type[Backend], type(lib.getBackend()))], lib,
            self)

        success: int = dlg.exec_()

        if not success:
            return

        lib.save()
        self.libraries_model.updateLibrary(lib)
Пример #5
0
    def test_make_nested_view(self):
        library = Library(self.library_name).create(self.folder_name, None)
        tracks = (
            library.view()
            .by("COMPOSER")
            .by("GENRE")
            .by("ALBUM")
            .filter()
            .using("Mendelssohn")
            .using("Chamber Music")
            .using("A")
            .ids
        )

        self.assertIsNotNone(tracks)
Пример #6
0
 def __init__(self):
     print '''Would you like to:
     1. Go somewhere
     2. Call someone
     3. Read a book
     4. Play video games
     '''
     choice = raw_input(">: ")
     if choice == "1":
         print '''Where would you like to go?
         1. Library
         2. Gym
         3. Supermarket
         '''
         choice = raw_input(">: ")
         if choice == "1":
             Library()
         elif choice == "2":
             Gym()
         else:
             Groceries()
     elif choice == "2":
         Call()
     elif choice == "3":
         Book()
     else:
         VideoGames()
Пример #7
0
 def __change_library(self, new_library):
     if self.selected_library:
         self.selected_library['selected'].set(False)
     self.selected_library = new_library
     self.selected_library['selected'].set(True)
     self.library = Library(self.selected_library['name']).restore()
     for listener in self.library_listeners:
         listener.on_library_change(self.library)
Пример #8
0
 def __init__(self):
     super().__init__()
     self.library = Library('music').create(folder_name, Listener())
     views = ['COMPOSER', 'GENRE', 'ALBUM', 'ARTIST']
     library_view = self.library.view()
     for view in views:
         self.filters = library_view.by(view)
     self.filters = self.filters.filter()
     self.track_selection = False
Пример #9
0
    def test_should_save_tags(self):
        library = Library(self.library_name).create(self.folder_name, None)
        library_filter = library.view().by("ALBUM").filter()
        album_title = library_filter.ids[0]
        track = library_filter.using(album_title).ids[0]
        track_id = track["_id"]
        tags = library.track_details(track_id)
        from time import time

        now = str(time() * 1000)
        tags["ALBUM"] = now

        library.store(track_id, tags)

        path = tags["PATH"]
        from tags.tagreader import TagReader

        saved_tags = TagReader().readfile(path)
        self.assertEquals(now, saved_tags["ALBUM"])
Пример #10
0
    def test_should_store_document(self):
        library = Library(self.library_name).create(self.folder_name, None)
        library_filter = library.view().by("ALBUM").filter()
        album_title = library_filter.ids[0]
        track = library_filter.using(album_title).ids[0]
        track_id = track["_id"]
        tags = library.track_details(track_id)
        from time import time

        now = str(time() * 1000)
        tags["ALBUM"] = now

        library.store(track_id, tags)

        from pymongo import MongoClient

        client = MongoClient()
        db = client[self.library_name]
        self.assertEquals(now, db.tags.find_one({"_id": track_id})["ALBUM"])
Пример #11
0
def movies(request):
    items_filter = request.GET.get('filter')
    page_number = request.GET.get('page', 1)

    Library.sync()

    items = MediaPart.objects.order_by('-media__movie__added_at')
    if items_filter == 'invalid':
        items = items.exclude(path=models.F('best_path'))
    else:
        items = items.all()

    paginator = Paginator(items, page_size)
    page = paginator.get_page(page_number)

    context = {
        'items': page,
    }

    return render(request, 'movies/index.html', context)
Пример #12
0
 def create_library():
     name = library_name.get()
     path = library_path.get()
     print("Creating Library {} at {}".format(name, path))
     new_library = {
         "name": name,
         "path": path,
         "selected": BooleanVar(False)
     }
     dialog.destroy()
     config['libraries'].append(new_library)
     self.library = Library(new_library['name']).create(new_library['path'], self.status_bar)
     self.__change_library(new_library)
Пример #13
0
    def showAddDialog(self, tab: Type[BackendTab]) -> None:

        library: Library = Library()

        dlg: DetailsDialog = DetailsDialog(tab, library, self)
        success: int = dlg.exec_()

        if not success:
            return

        library.save()
        self._library_manager.addLibrary(library)

        self.libraries_model.reloadLibraries()
Пример #14
0
    def indexFolderStructure(self, lib: Library) -> Node:

        tree: Node = Node()
        tree.setDirectory()

        backend: Backend = cast(Backend, lib.getBackend())

        open: queue.Queue[Node] = queue.Queue()

        open.put(tree)

        while not open.empty():

            if QThread.currentThread().isInterruptionRequested():
                raise ThreadStoppedError()

            next: Node = open.get()

            next_path: str = next.getPath().as_posix()

            dir_list: List[str] = backend.listDirectory(next_path)

            for dir in dir_list:

                new: Node = Node()
                new.setName(dir)

                if backend.isDirectory(os.path.join(next_path, dir)):
                    new.setDirectory()
                else:
                    new.setFile()

                if new.isFile():

                    # check file extensions
                    _, ext = os.path.splitext(new.getName())

                    if not ext.lower() in getSupportedFileExtensions():
                        del new
                        continue

                next.addChild(new)

                if new.isDirectory():
                    open.put(new)

        return tree
Пример #15
0
    def OnInit(self):

        import Inspectors, Layouts, Shapes  # pylint: disable=W0612

        neuroptikon.library = Library()
        self._loadDefaultLibraryItems()

        neuroptikon.config = wx.Config('Neuroptikon')

        if platform.system() == 'Darwin':
            wx.MenuBar.MacSetCommonMenuBar(self.menuBar())

        neuroptikon.scriptLocals = self.scriptLocals

        self.preferences = Preferences()
        self.inspector = InspectorFrame()

        self.SetExitOnFrameDelete(False)

        startupScript = neuroptikon.config.Read('Startup Script', '')
        try:
            exec startupScript in self.scriptLocals()
        except:
            (exceptionType, exceptionValue,
             exceptionTraceback) = sys.exc_info()
            frames = traceback.extract_tb(exceptionTraceback)[1:]
            message = gettext(
                'An error occurred while running the startup script:')
            subMessage = str(
                exceptionValue
            ) + ' (' + exceptionType.__name__ + ')' + '\n\nTraceback:\n' + ''.join(
                traceback.format_list(frames))
            if platform.system() == 'Darwin':
                wx.MessageBox(subMessage, message, style=wx.ICON_ERROR | wx.OK)
            else:
                wx.MessageBox(message + '\n\n' + subMessage,
                              'Neuroptikon',
                              parent=self,
                              style=wx.ICON_ERROR | wx.OK)

        # open an empty network by default
        # TODO: pref to re-open last doc?
        self.onNewNetwork()

        return True
Пример #16
0
    def indexBooks(self, lib: Library, tree: Node) -> List[Book]:

        book_map: Dict[Book, Node] = {}
        book: Book
        match: Optional[TagCollection]
        next: Node
        ns: NamingScheme = cast(NamingScheme, lib.getNamingScheme())

        # process all volumes

        for next in tree.iterChildren(depth=ns.getDepth(
                ns.volume.getPattern()),
                                      files=False):

            match = ns.volume.match(next.getPath().as_posix())

            if match:
                book = Book(next.getPath(), match)

                book_map[book] = next

        # process all standalones

        for next in tree.iterChildren(depth=ns.getDepth(
                ns.standalone.getPattern()),
                                      files=False):

            match = ns.standalone.match(next.getPath().as_posix())

            if match:
                book = Book(next.getPath(), match)

                book_map[book] = next

        # iterate over all books in the dict
        # if the book is already part of the tree of another book, remove it
        # this might happen whenever a path is detected as a book
        # although e.g. their subpaths were also recognized as books already

        books: List[Book] = list(book_map.keys())
        book_nodes: List[Node] = list(book_map.values())
        i: int = 0
        j: int = 0

        while i < len(book_map):

            for j in range(len(book_map)):

                if QThread.currentThread().isInterruptionRequested():
                    raise ThreadStoppedError()

                if i == j:
                    continue

                if book_nodes[i].isParentOf(book_nodes[j]):
                    del book_map[books[i]]
                    del books[i]
                    del book_nodes[i]
                    break

            else:
                i += 1

        return books
Пример #17
0
    def updateLibrary(self, lib: Library) -> None:

        index: int = self._libraries.index(lib)

        item: QStandardItem = self.item(index, 0)
        item.setText(lib.getName())
Пример #18
0
class TestLibrary(unittest.TestCase):
    @patch('library.ext_api_interface.Books_API')
    @patch('library.library_db_interface.Library_DB')
    def setUp(self, mockBooks_API, mockLibrary_DB):
        self.library = Library()
        self.patron = Patron("bob", "bobson", 41, 1)
        self.library.api = mockBooks_API
        self.library.db = mockLibrary_DB
        mockBooks_API.get_ebooks.return_value = [{
            'title': 'The Count of Monte Cristo',
            "ebook_count": 1
        }, {
            'title': 'A Tale of Two Cities',
            "ebook_count": 1
        }, {
            'title': '1984',
            "ebook_count": 1
        }, {
            'title': 'Slaughterhouse 5',
            "ebook_count": 1
        }, {
            'title': 'Breakfast of Champions',
            "ebook_count": 1
        }]
        mockBooks_API.books_by_author.return_value = [
            'Slaughterhouse 5', 'Breakfast of Champions'
        ]
        mockBooks_API.get_book_info.return_value = [{
            'title': 'The Count of Monte Cristo',
            "ebook_count": 1,
            'publisher': 'Penguin',
            'publish_year': '1844',
            'language': "french"
        }]
        mockLibrary_DB.patrons = [self.patron]
        mockLibrary_DB.update_patron = self.mock_update_patron
        mockLibrary_DB.insert_patron.return_value = 1
        mockLibrary_DB.retrieve_patron = self.mock_retrieve_patron

    def mock_update_patron(self, patron):
        self.library.db.patrons[0] = patron

    def mock_retrieve_patron(self, patron):
        if patron == 1:
            return self.library.db.patrons[0]
        else:
            return None

    def test_is_ebook(self):
        library = self.library
        self.assertFalse(library.is_ebook('title'))
        self.assertTrue(library.is_ebook("1984"))

    def test_get_ebooks_count(self):
        library = self.library
        self.assertEqual(library.get_ebooks_count('title'), 5)

    def test_is_book_by_author(self):
        library = self.library
        self.assertTrue(
            library.is_book_by_author("Kurt Vonnegut", 'Slaughterhouse 5'))
        self.assertFalse(library.is_book_by_author("Kurt Vonnegut", "1984"))

    def test_get_languages_for_book(self):
        library = self.library
        result = set('french')
        self.assertEqual(
            library.get_languages_for_book('The Count of Monte Cristo'),
            result)

    def test_register_patron(self):
        library = self.library
        self.assertEqual(library.register_patron("bob", "bobson", 41, 1), 1)

    def test_is_patron_registered(self):
        library = self.library
        patron = self.patron
        p2 = Patron("bob", "bobson", 41, 2)
        self.assertTrue(library.is_patron_registered(patron))
        self.assertFalse(library.is_patron_registered(p2))

    def test_borrow_book(self):
        library = self.library
        patron = self.patron
        library.borrow_book("1984", patron)
        self.assertEqual(
            self.library.db.retrieve_patron(1).get_borrowed_books(), ["1984"])

    def test_return_borrowed_book(self):
        library = self.library
        patron = self.patron
        library.borrow_book("1984", patron)
        library.return_borrowed_book("1984", patron)
        self.assertEqual(
            self.library.db.retrieve_patron(1).get_borrowed_books(), [])

    def test_is_book_borrowed(self):
        library = self.library
        patron = self.patron
        library.borrow_book("1984", patron)
        self.assertTrue(self.library.is_book_borrowed("1984", patron))
Пример #19
0
class TestLibrary(TestCase):
    def setUp(self) -> None:
        self.CuT = Library()
        self.CuT.db.close_db()
        self.patron = Mock()
        self.book_title_there = 'Adventures of Elvis'
        self.book_title_not_there = 'Adventures of Dino'
        self.book_title_language = 'Harry Potter'
        self.book_author = 'Dummy Name'
        self.first_name = 'Sam'
        self.last_name = 'Wheeler'
        self.age = 27
        self.member_id = 100001

    def test_library_db_created(self):
        # Assert
        self.assertIsInstance(self.CuT.db, Library_DB)

    def test_book_api_created(self):
        # Assert
        self.assertIsInstance(self.CuT.api, Books_API)

    def test_book_is_ebook(self):
        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_ebooks.return_value = dummy_book_list_json

        # Assert
        self.assertTrue(self.CuT.is_ebook(self.book_title_there))

    def test_book_is_not_ebook(self):
        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_ebooks.return_value = dummy_book_list_json

        # Assert
        self.assertFalse(self.CuT.is_ebook(self.book_title_not_there))

    def test_gets_book_count_for_more_than_zero(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_ebooks.return_value = dummy_similar_book_list_json

        # Assert
        self.assertEqual(self.CuT.get_ebooks_count(self.book_title_there), 10)

    def test_gets_book_count_for_zero_books(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_ebooks.return_value = []

        # Assert
        self.assertEqual(self.CuT.get_ebooks_count(self.book_title_not_there),
                         0)

    def test_gets_book_count_if_no_book_is_there(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_ebooks.return_value = [
            {
                'title': 'Adventures of Dino',
                'ebook_count': 0
            },
        ]

        # Assert
        self.assertEqual(self.CuT.get_ebooks_count(self.book_title_not_there),
                         0)

    def test_author_entered_for_book_is_true(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.books_by_author.return_value = dummy_author_book_list_json

        # Assert
        self.assertTrue(
            self.CuT.is_book_by_author(self.book_author,
                                       self.book_title_there))

    def test_author_entered_for_book_is_false(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.books_by_author.return_value = dummy_author_book_list_json

        # Assert
        self.assertFalse(
            self.CuT.is_book_by_author(self.book_author,
                                       self.book_title_not_there))

    def test_author_entered_for_book_has_no_book_in_library(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.books_by_author.return_value = []

        # Assert
        self.assertFalse(
            self.CuT.is_book_by_author(self.book_author,
                                       self.book_title_not_there))

    def test_gets_languages_for_the_book(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_book_info.return_value = book_language_list
        languages = self.CuT.get_languages_for_book(self.book_title_language)

        # Assert
        self.assertEqual(len(languages), len(book_language_list))

    def test_gets_one_language_for_the_book(self):

        language_list = [{'language': ['eng']}]

        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_book_info.return_value = language_list
        languages = self.CuT.get_languages_for_book(self.book_title_language)

        # Assert
        self.assertEqual(len(languages), 1)

    def test_gets_zero_language_for_no_book(self):

        # Assume
        language_list = []

        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_book_info.return_value = language_list
        languages = self.CuT.get_languages_for_book(self.book_title_language)

        # Assert
        self.assertEqual(len(languages), 0)

    def test_gets_the_correct_languages_for_the_book(self):

        # Action
        self.CuT.api = Mock()
        self.CuT.api.get_book_info.return_value = book_language_list
        languages = self.CuT.get_languages_for_book(self.book_title_language)
        all_languages = list()
        for ebook in book_language_list:
            all_languages.append(ebook['language'][0])
        is_same = True
        for lang in languages:
            if lang not in all_languages:
                is_same = False
                break

        # Assert
        self.assertTrue(is_same)

    def test_patron_is_registered_in_db(self):

        # Assume
        self.CuT.db = Mock()
        self.CuT.db.insert_patron.return_value = 1
        self.CuT.db.retrieve_patron.return_value = True
        patron = Patron(self.first_name, self.last_name, self.age,
                        self.member_id)
        patron.get_memberID = Mock(return_value=1)

        # Action
        self.CuT.register_patron(self.first_name, self.last_name, self.age,
                                 self.member_id)
        is_patron_registered = self.CuT.is_patron_registered(patron)
        # Removes the instance of the db.json created
        if path.exists('db.json'):
            os.remove('db.json')

        # Assert
        self.assertTrue(is_patron_registered)

    def test_patron_is_not_registered_in_db(self):

        # Assume
        self.CuT.db = Mock()
        self.CuT.db.insert_patron.return_value = 1
        self.CuT.db.retrieve_patron.return_value = False
        patron = Patron(self.first_name, self.last_name, self.age,
                        self.member_id)
        patron.get_memberID = Mock(return_value=1)

        # Action
        self.CuT.register_patron(self.first_name, self.last_name, self.age,
                                 self.member_id)
        is_patron_registered = self.CuT.is_patron_registered(patron)
        # Removes the instance of the db.json created
        if path.exists('db.json'):
            os.remove('db.json')

        # Assert
        self.assertFalse(is_patron_registered)

    def test_has_patron_borrowed_book_true(self):

        # Assume
        self.CuT.db = Mock()

        self.patron.fname.return_value = self.first_name
        self.patron.lname.return_value = self.last_name
        self.patron.age.return_value = self.age
        self.patron.memberID.return_value = self.member_id
        self.patron.borrowed_books.return_value = []
        self.CuT.db.update_patron.return_value = True
        self.patron.add_borrowed_book.return_value = True
        self.patron.get_borrowed_books.return_value = [
            self.book_title_there.lower()
        ]

        # Action
        self.CuT.borrow_book(self.book_title_there, self.patron)
        is_book_borrowed = self.CuT.is_book_borrowed(self.book_title_there,
                                                     self.patron)

        # Removes the instance of the db.json created
        if path.exists('db.json'):
            os.remove('db.json')

        # Assert
        self.assertTrue(is_book_borrowed)

    def test_has_patron_borrowed_book_false(self):

        # Assume
        self.CuT.db = Mock()

        self.patron.fname.return_value = self.first_name
        self.patron.lname.return_value = self.last_name
        self.patron.age.return_value = self.age
        self.patron.memberID.return_value = self.member_id
        self.patron.borrowed_books.return_value = []
        self.CuT.db.update_patron.return_value = True
        self.patron.add_borrowed_book.return_value = True
        self.patron.get_borrowed_books.return_value = ['Some other book title']

        # Action
        self.CuT.borrow_book(self.book_title_there, self.patron)
        is_book_borrowed = self.CuT.is_book_borrowed(self.book_title_there,
                                                     self.patron)

        # Removes the instance of the db.json created
        if path.exists('db.json'):
            os.remove('db.json')

        # Assert
        self.assertFalse(is_book_borrowed)

    def test_patron_has_returned_book(self):

        # Assume
        self.CuT.db = Mock()

        self.patron.fname.return_value = self.first_name
        self.patron.lname.return_value = self.last_name
        self.patron.age.return_value = self.age
        self.patron.memberID.return_value = self.member_id
        self.patron.borrowed_books.return_value = [
            self.book_title_there.lower()
        ]
        self.CuT.db.update_patron.return_value = True
        self.patron.return_borrowed_book.return_value = True
        self.patron.get_borrowed_books.return_value = []

        # Action
        self.CuT.borrow_book(self.book_title_there, self.patron)
        self.CuT.return_borrowed_book(self.book_title_there, self.patron)
        is_book_borrowed = self.CuT.is_book_borrowed(self.book_title_there,
                                                     self.patron)

        # Removes the instance of the db.json created
        if path.exists('db.json'):
            os.remove('db.json')

        # Assert
        self.assertFalse(is_book_borrowed)
Пример #20
0
 def add(self, lib: Library):
     self.libs[lib.get_name()] = lib
     if lib.is_default():
         self.default_lib = lib
Пример #21
0
from library.library import Library
from library.user import User

user = User(12, 'Peter')
library = Library()
library.add_user(user)
print(library.add_user(user))
library.remove_user(user)
print(library.remove_user(user))
library.add_user(user)
print(library.change_username(2, 'Igor'))
print(library.change_username(12, 'Peter'))
print(library.change_username(12, 'George'))

[
    print(
        f'{user_record.user_id}, {user_record.username}, {user_record.books}')
    for user_record in library.user_records
]
library.books_available.update({
    'J.K.Rowling': [
        'The Chamber of Secrets', 'The Prisoner of Azkaban',
        'The Goblet of Fire', 'The Order of the Phoenix',
        'The Half-Blood Prince', 'The Deathly Hallows'
    ]
})

user.get_book('J.K.Rowling', 'The Deathly Hallows', 17, library)
print(library.books_available)
print(library.rented_books)
print(user.books)
Пример #22
0
def quality(part):
    return Library.parse_quality(part.path)
Пример #23
0
class Ui:

    def __init__(self):
        super().__init__()
        self.library = Library('music').create(folder_name, Listener())
        views = ['COMPOSER', 'GENRE', 'ALBUM', 'ARTIST']
        library_view = self.library.view()
        for view in views:
            self.filters = library_view.by(view)
        self.filters = self.filters.filter()
        self.track_selection = False

    def prompt(self, items):
        from prompt_toolkit.key_binding.manager import KeyBindingManager
        from prompt_toolkit.keys import Keys
        key_binding_manager = KeyBindingManager()

        @key_binding_manager.registry.add_binding(Keys.F4)
        def _(event):
            self.filters.remove_current_filter()
            self.run()

        @key_binding_manager.registry.add_binding(Keys.F1)
        def _(event):
            if self.filters.current_view() != 'TITLE':
                first_item = self.filters.ids[0]
                event.cli.current_buffer.insert_text(first_item)

        return get_input('> ', completer=WordCompleter(items, ignore_case=True),
                         key_bindings_registry=key_binding_manager.registry,
                         display_completions_in_columns=True)

    def handle_track_selection(self):
        songs = [format_song(song) for (song) in self.filters.ids]
        for song in songs:
            print(song)
        title = self.prompt(songs)
        index = songs.index(title)
        song = self.filters.ids[index]
        track_details = self.library.track_details(song['_id'])
        from bson.json_util import dumps
        print(dumps(track_details))
        self.track_selection = True

    def get_selection(self):
        if self.track_selection:
            for action in actions:
                print(action)
            self.prompt(actions)
        else:
            if self.filters.current_view() == 'TITLE':
                self.handle_track_selection()
            else:
                for item in self.filters.ids:
                    print(item)
                selection = self.prompt(self.filters.ids)
                self.filters.using(selection)
                self.track_selection = False

    def run(self):
        while True:
            self.get_selection()
Пример #24
0
class MusicLibrary:
    def __init__(self):
        super().__init__()
        self.selected_library = None
        self.library = None
        self.__make_widgets()
        self.__make_bindings()
        self.__make_menu()
        self.tree.tree.pack(expand=Y, side=LEFT, fill=BOTH)
        self.editor.pack(expand=Y, side=RIGHT, fill=BOTH)
        self.status_bar.label.pack(side=BOTTOM, fill=X)
        self.library_listeners = [self.tree, self.editor, WindowTitle(self.root)]
        self.__change_library(next(lib for lib in config['libraries'] if lib['selected'].get()))
        self.root.protocol("WM_DELETE_WINDOW", self.__on_exit)
        self.root.mainloop()

    def __make_widgets(self):
        root = Tk()
        root.state('zoomed')
        self.status_bar = StatusBar(root)
        self.editor = Editor(config['editor'], self.status_bar, root)
        self.tree = Tree(config['tree'], root)
        self.root = root

    def __save_command(self):
        return self.make_task(self.editor.save, task_name=lambda event=None: "Saving tags in {} files"
                              .format(len(self.editor.tracks)))

    def __reload_command(self):
        return self.make_task(self.__on_reload, task_name=lambda event=None, selection=None: "Reloading {}".format(
            selection or self.tree.selected_node))

    def __make_bindings(self):
        self.tree.tree.bind("<F5>", self.__reload_command())

        self.tree.tree.bind("<<TreeviewSelect>>", self.make_task(self.__on_node_selected))
        self.root.bind("<Control-s>", self.__save_command())

    def rename_command(self):
        # from os import rename
        self.library.rename(self.editor.tracks, self.selected_library['path'])
            # path = track['PATH']
            # composer = track['COMPOSER']
            # genre = track['GEN']

    def __make_menu(self):
        self.menu = Menu(self.root)
        self.root.config(menu=self.menu)
        file_menu = Menu(self.menu)
        self.menu.add_cascade(label="File", menu=file_menu)
        file_menu.add_command(label="Save tags", command=self.__save_command())
        file_menu.add_command(label="Reload", command=self.__reload_command())
        file_menu.add_command(label="Rename", command=self.rename_command)
        library_menu = Menu(self.menu)

        self.menu.add_cascade(label="Library", menu=library_menu)
        library_menu.add_command(label="Rescan",
                                 command=self.make_task(self.__rescan_library))
        open_library_menu = Menu(library_menu)
        library_menu.add_cascade(label="Open", menu=open_library_menu)
        for lib in config['libraries']:
            lib['selected'] = BooleanVar(value=lib.get('selected', False))
            open_library_menu.add_checkbutton(label=lib['name'], variable=lib['selected'],
                                              command=self.make_task(self.__change_library,
                                              lambda new_library: "Opening library {}".format(
                                                  new_library['name']), lib))
        library_menu.add_command(label="New...", command=self.__new_library)

    def make_task(self, function, task_name=None, *args):
        task = Task(function, self.status_bar, task_name)
        return partial(task.run, *args)

    def __on_exit(self):
        print("About to close window: saving application configuration")
        from json import dump
        with open(config_path, 'w') as config_file:
            dump(config, config_file, cls=ConfigEncoder, sort_keys=True, indent=4)
        self.root.destroy()

    def __on_reload(self, event=None, selection=None):
        selected_node = selection or self.tree.selected_node
        if selected_node:
            self.tree.delete_children(selected_node)
            self.tree.fetch_children(selected_node)
            self.__on_node_selected(event, selected_node)

    def __change_library(self, new_library):
        if self.selected_library:
            self.selected_library['selected'].set(False)
        self.selected_library = new_library
        self.selected_library['selected'].set(True)
        self.library = Library(self.selected_library['name']).restore()
        for listener in self.library_listeners:
            listener.on_library_change(self.library)

    def __new_library(self):
        dialog = Toplevel(self.root)
        Label(dialog, anchor=W, width=20, pady=5, justify=LEFT, text="Library name: ").grid(row=0, column=0)
        library_name = Entry(dialog, width=50)
        Label(dialog, anchor=W, width=20, pady=5, justify=LEFT, text="Library path: ").grid(row=1, column=0)
        library_path = Entry(dialog, width=50)
        library_name.grid(row=0, column=1)
        library_path.grid(row=1, column=1)

        def create_library():
            name = library_name.get()
            path = library_path.get()
            print("Creating Library {} at {}".format(name, path))
            new_library = {
                "name": name,
                "path": path,
                "selected": BooleanVar(False)
            }
            dialog.destroy()
            config['libraries'].append(new_library)
            self.library = Library(new_library['name']).create(new_library['path'], self.status_bar)
            self.__change_library(new_library)

        Button(dialog, text="OK", command=self.make_task(create_library), width=10, pady=5).grid(row=2, column=0,
                                                                                                 columnspan=3)
        dialog.grab_set()
        self.root.wait_window(dialog)

    def __rescan_library(self):
        self.library = self.library.create(self.selected_library['path'], self.status_bar)
        for listener in self.library_listeners:
            listener.on_library_change(self.library)

    def __on_node_selected(self, event=None, selection=None):
        selection = selection or self.tree.selected_node
        children = self.tree.children(selection)
        for child in children:
            self.tree.fetch_children(child)
        self.editor.select(selection)
Пример #25
0
from library.book import Book
from library.library import Library
from library.reader import Reader

if __name__ == '__main__':
    books = [Book("Harry potter", "J.K.Rowling"), Book("Lotr", "Tolkien")]
    reader1 = Reader("Piotr")
    library = Library()

    library.add_book(books[0])
    library.add_book(books[1])