From b1efd633ba330ee819ca34fb828d50456bae6764 Mon Sep 17 00:00:00 2001 From: rdbende Date: Tue, 26 Mar 2024 13:13:35 +0100 Subject: [PATCH] Fix things pointed out by Ruff --- cozy/control/artwork_cache.py | 8 ++------ cozy/control/db.py | 5 +---- cozy/control/filesystem_monitor.py | 1 - cozy/control/offline_cache.py | 10 +++------- cozy/control/string_representation.py | 3 +-- cozy/media/files.py | 4 ++-- cozy/media/importer.py | 2 +- cozy/media/media_detector.py | 2 +- cozy/media/tag_reader.py | 11 ++--------- cozy/model/book.py | 5 ++--- cozy/model/database_importer.py | 5 +---- cozy/model/track.py | 2 +- cozy/report/report_to_loki.py | 7 ++++--- cozy/tools.py | 5 +---- cozy/ui/book_detail_view.py | 5 ++--- cozy/ui/headerbar.py | 2 -- cozy/ui/search_view.py | 5 +---- cozy/ui/widgets/sleep_timer.py | 7 +------ cozy/view_model/library_view_model.py | 10 ++-------- 19 files changed, 28 insertions(+), 71 deletions(-) diff --git a/cozy/control/artwork_cache.py b/cozy/control/artwork_cache.py index ba8eebf0..64446063 100644 --- a/cozy/control/artwork_cache.py +++ b/cozy/control/artwork_cache.py @@ -55,8 +55,7 @@ def delete_artwork_cache(self): q.execute() def _on_importer_event(self, event, data): - if event == "scan": - if data == ScanStatus.STARTED: + if event == "scan" and data == ScanStatus.STARTED: self.delete_artwork_cache() def _create_artwork_cache(self, book, pixbuf, size): @@ -123,10 +122,7 @@ def _load_pixbuf_from_cache(self, book, size): path = self.get_album_art_path(book, size) try: - if path: - pixbuf = GdkPixbuf.Pixbuf.new_from_file(path) - else: - pixbuf = None + pixbuf = GdkPixbuf.Pixbuf.new_from_file(path) if path else None except Exception as e: log.warning("Failed to load pixbuf from path: %s. Deleting file.", path) log.debug(e) diff --git a/cozy/control/db.py b/cozy/control/db.py index 5f79b909..0e84647e 100644 --- a/cozy/control/db.py +++ b/cozy/control/db.py @@ -91,10 +91,7 @@ def get_track_for_playback(book): query = Track.select().where(Track.id == book.position) if book.position < 1: track_items = get_tracks(book) - if len(track_items) > 0: - track = get_tracks(book)[0] - else: - track = None + track = get_tracks(book)[0] if len(track_items) > 0 else None elif query.exists(): track = query.get() else: diff --git a/cozy/control/filesystem_monitor.py b/cozy/control/filesystem_monitor.py index 68f15c2e..96d745fd 100644 --- a/cozy/control/filesystem_monitor.py +++ b/cozy/control/filesystem_monitor.py @@ -42,7 +42,6 @@ def __init__(self): self._settings_view_model.add_listener(self.__on_settings_changed) def init_offline_mode(self): - external_storage = [] mounts = self.volume_monitor.get_mounts() # go through all audiobook locations and test if they can be found in the mounts list diff --git a/cozy/control/offline_cache.py b/cozy/control/offline_cache.py index 145f1724..339aea95 100644 --- a/cozy/control/offline_cache.py +++ b/cozy/control/offline_cache.py @@ -118,7 +118,7 @@ def remove_all_for_storage(self, storage): def get_cached_path(self, chapter: Chapter): query = OfflineCacheModel.select().where(OfflineCacheModel.original_file == chapter.file_id, - OfflineCacheModel.copied == True) + OfflineCacheModel.copied) if query.count() > 0: return os.path.join(self.cache_dir, query.get().cached_file) else: @@ -244,11 +244,7 @@ def _is_book_downloaded(self, book: Book): offline_files = OfflineCacheModel.select().where(OfflineCacheModel.original_file << file_ids) offline_file_ids = [file.original_file.id for file in offline_files] - for chapter in book.chapters: - if chapter.file_id not in offline_file_ids: - return False - - return True + return all(chapter.file_id in offline_file_ids for chapter in book.chapters) def _is_processing(self): """ @@ -259,7 +255,7 @@ def _is_processing(self): return False def _fill_queue_from_db(self): - for item in OfflineCacheModel.select().where(OfflineCacheModel.copied == False): + for item in OfflineCacheModel.select().where(not OfflineCacheModel.copied): if not any(item.id == queued.id for queued in self.queue): self.queue.append(item) self.total_batch_count += 1 diff --git a/cozy/control/string_representation.py b/cozy/control/string_representation.py index 7ea188bb..125928d2 100644 --- a/cozy/control/string_representation.py +++ b/cozy/control/string_representation.py @@ -9,12 +9,11 @@ def seconds_to_str(seconds, max_length=None, include_seconds=True): h, m = divmod(m, 60) if max_length: - max_m, max_s = divmod(max_length, 60) + max_m, _ = divmod(max_length, 60) max_h, max_m = divmod(max_m, 60) else: max_h = h max_m = m - max_s = s if (max_h >= 10): result = "%02d:%02d" % (h, m) diff --git a/cozy/media/files.py b/cozy/media/files.py index 7ee3f39c..0bdb97ed 100644 --- a/cozy/media/files.py +++ b/cozy/media/files.py @@ -58,7 +58,7 @@ def _copy_file(self, source_path: str, dest_path: str): flags = Gio.FileCopyFlags.OVERWRITE self.filecopy_cancel = Gio.Cancellable() try: - copied = source.copy(destination, flags, self.filecopy_cancel, self._update_copy_status, None) + source.copy(destination, flags, self.filecopy_cancel, self._update_copy_status, None) except Exception as e: if e.code == Gio.IOErrorEnum.CANCELLED: pass @@ -76,7 +76,7 @@ def _copy_file(self, source_path: str, dest_path: str): def _copy_directory(self, path, destination): main_source_path = os.path.split(path)[0] - for dirpath, dirnames, filenames in os.walk(path): + for dirpath, _, filenames in os.walk(path): dirname = os.path.relpath(dirpath, main_source_path) destination_dir = os.path.join(destination, dirname) try: diff --git a/cozy/media/importer.py b/cozy/media/importer.py index 93e56ecc..dd36c92b 100644 --- a/cozy/media/importer.py +++ b/cozy/media/importer.py @@ -167,7 +167,7 @@ def _get_configured_storage_paths(self) -> list[str]: def _walk_paths_to_scan(self, paths: list[str]) -> list[str]: """Get all files recursive inside a directory. Returns absolute paths.""" for path in paths: - for directory, subdirectories, files in os.walk(path): + for directory, _, files in os.walk(path): for file in files: filepath = os.path.join(directory, file) yield filepath diff --git a/cozy/media/media_detector.py b/cozy/media/media_detector.py index 5ed0306b..fb21993a 100644 --- a/cozy/media/media_detector.py +++ b/cozy/media/media_detector.py @@ -35,7 +35,7 @@ def get_media_data(self) -> MediaFile: discoverer_info: GstPbutils.DiscovererInfo = self.discoverer.discover_uri(self.uri) except Exception: log.info("Skipping file because it couldn't be detected: %s", self.uri) - raise AudioFileCouldNotBeDiscovered(self.uri) + raise AudioFileCouldNotBeDiscovered(self.uri) from None is_valid_audio_file = self._is_valid_audio_file(discoverer_info) if is_valid_audio_file: diff --git a/cozy/media/tag_reader.py b/cozy/media/tag_reader.py index ebb13e86..1ef07dd4 100644 --- a/cozy/media/tag_reader.py +++ b/cozy/media/tag_reader.py @@ -144,18 +144,13 @@ def _get_m4b_chapters(self, mutagen_tags: MP4) -> list[Chapter]: if not mutagen_tags.chapters or len(mutagen_tags.chapters) == 0: return self._get_single_chapter() - index = 0 - - for chapter in mutagen_tags.chapters: + for index, chapter in enumerate(mutagen_tags.chapters): if index < len(mutagen_tags.chapters) - 1: length = mutagen_tags.chapters[index + 1].start - chapter.start else: length = self._get_length_in_seconds() - chapter.start - if chapter.title: - title = chapter.title - else: - title = "" + title = chapter.title or "" chapters.append(Chapter( name=title, @@ -164,8 +159,6 @@ def _get_m4b_chapters(self, mutagen_tags: MP4) -> list[Chapter]: number=index + 1 )) - index += 1 - return chapters def _parse_with_mutagen(self) -> MP4: diff --git a/cozy/model/book.py b/cozy/model/book.py index 15e499af..12684da0 100644 --- a/cozy/model/book.py +++ b/cozy/model/book.py @@ -1,4 +1,5 @@ import logging +from contextlib import suppress from peewee import SqliteDatabase, DoesNotExist @@ -221,10 +222,8 @@ def _fetch_chapters(self): def _on_chapter_event(self, event: str, chapter: Chapter): if event == "chapter-deleted": - try: + with suppress(ValueError): self.chapters.remove(chapter) - except ValueError: - pass if len(self._chapters) < 1: if self._settings.last_played_book and self._settings.last_played_book.id == self._db_object.id: diff --git a/cozy/model/database_importer.py b/cozy/model/database_importer.py index 1824e005..6af23d02 100644 --- a/cozy/model/database_importer.py +++ b/cozy/model/database_importer.py @@ -162,10 +162,7 @@ def _delete_tracks_from_db(self, media_file: MediaFile): def _is_chapter_count_in_db_different(self, media_file: MediaFile) -> bool: all_track_mappings = self._get_chapter_count_in_db(media_file) - if all_track_mappings != len(media_file.chapters): - return True - else: - return False + return all_track_mappings != len(media_file.chapters) def _get_chapter_count_in_db(self, media_file: MediaFile) -> int: all_track_mappings = TrackToFile.select().join(File).where(TrackToFile.file.path == media_file.path) diff --git a/cozy/model/track.py b/cozy/model/track.py index 983fccbe..7048142e 100644 --- a/cozy/model/track.py +++ b/cozy/model/track.py @@ -28,7 +28,7 @@ def __init__(self, db: SqliteDatabase, track: TrackModel): except DoesNotExist: log.error("Inconsistent DB, TrackToFile object is missing. Deleting this track.") self._db_object.delete_instance(recursive=True, delete_nullable=False) - raise TrackInconsistentData + raise TrackInconsistentData from None @property def name(self): diff --git a/cozy/report/report_to_loki.py b/cozy/report/report_to_loki.py index eed69f19..fc23e2aa 100644 --- a/cozy/report/report_to_loki.py +++ b/cozy/report/report_to_loki.py @@ -1,5 +1,7 @@ import os +from contextlib import suppress + import requests import datetime import pytz @@ -79,10 +81,9 @@ def report(component: str, type: LogLevel, message: str, exception: Exception): } ] } - try: + + with suppress(Exception): requests.post(URL, json=payload, headers=headers, timeout=10) - except: - pass def __append_label(labels, new_label_name, new_label_content): diff --git a/cozy/tools.py b/cozy/tools.py index ff7c8938..cb06d06a 100644 --- a/cozy/tools.py +++ b/cozy/tools.py @@ -37,10 +37,7 @@ def is_elementary(): """ dist = distro.linux_distribution(full_distribution_name=False) log.debug(dist) - if '"elementary"' in dist or 'elementary' in dist: - return True - else: - return False + return '"elementary"' in dist or 'elementary' in dist # https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python diff --git a/cozy/ui/book_detail_view.py b/cozy/ui/book_detail_view.py index a11c6baa..3d28f121 100644 --- a/cozy/ui/book_detail_view.py +++ b/cozy/ui/book_detail_view.py @@ -1,4 +1,5 @@ import logging +from contextlib import suppress import time from threading import Event, Thread from typing import Optional, Callable @@ -278,10 +279,8 @@ def _set_cover_image(self, book: Book): def _interrupt_chapters_jobs(self): self._chapters_job_locked = True - try: + with suppress(AttributeError): self._chapters_thread.join(timeout=0.2) - except AttributeError: - pass def _prepare_chapters_job(self): self._chapters_job_locked: bool = False diff --git a/cozy/ui/headerbar.py b/cozy/ui/headerbar.py index cdb772dd..0beceeb3 100644 --- a/cozy/ui/headerbar.py +++ b/cozy/ui/headerbar.py @@ -92,8 +92,6 @@ def _set_show_sidebar_button_visible(self, *_): self.search_button.set_active(False) def _on_mobile_view(self, widget, _): - page = self.sort_stack.props.visible_child_name - if widget.props.reveal: self.headerbar.set_title_widget(Adw.WindowTitle(title="Cozy")) else: diff --git a/cozy/ui/search_view.py b/cozy/ui/search_view.py index e846abdb..0343cba8 100644 --- a/cozy/ui/search_view.py +++ b/cozy/ui/search_view.py @@ -110,10 +110,7 @@ def _populate_listbox( if not results: return - if isinstance(results[0], Book): - row_type = BookRow - else: - row_type = ArtistResultRow + row_type = BookRow if isinstance(results[0], Book) else ArtistResultRow for result in results: listbox.append(row_type(result, callback)) diff --git a/cozy/ui/widgets/sleep_timer.py b/cozy/ui/widgets/sleep_timer.py index f41167db..c2ae3aea 100644 --- a/cozy/ui/widgets/sleep_timer.py +++ b/cozy/ui/widgets/sleep_timer.py @@ -93,10 +93,5 @@ def _on_stop_after_chapter_changed(self): self.chapter_switch.set_active(self._view_model.stop_after_chapter) def _on_timer_enabled_changed(self): - if self._view_model.timer_enabled: - icon = "bed-symbolic" - else: - icon = "no-bed-symbolic" - - self._timer_image.set_from_icon_name(icon) + self._timer_image.set_from_icon_name('bed-symbolic' if self._view_model.timer_enabled else 'no-bed-symbolic') diff --git a/cozy/view_model/library_view_model.py b/cozy/view_model/library_view_model.py index 43b5326f..87f4bfda 100644 --- a/cozy/view_model/library_view_model.py +++ b/cozy/view_model/library_view_model.py @@ -78,10 +78,7 @@ def selected_filter(self, value): @property def is_any_book_in_progress(self) -> bool: - for book in self.books: - if book.position > 0: - return True - return False + return any(book.position > 0 for book in self.books) @property def authors(self): @@ -152,10 +149,7 @@ def open_library(self): self._notify("library_view_mode") def book_files_exist(self, book: Book) -> bool: - for chapter in book.chapters: - if os.path.isfile(chapter.file): - return True - return False + return any(os.path.isfile(chapter.file) for chapter in book.chapters) def _on_fs_monitor_event(self, event, _): if event in {"storage-online", "storage-offline"}: