Skip to content

Commit

Permalink
Fix things pointed out by Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
rdbende committed Mar 26, 2024
1 parent 0e3752b commit b1efd63
Show file tree
Hide file tree
Showing 19 changed files with 28 additions and 71 deletions.
8 changes: 2 additions & 6 deletions cozy/control/artwork_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 1 addition & 4 deletions cozy/control/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
1 change: 0 additions & 1 deletion cozy/control/filesystem_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 3 additions & 7 deletions cozy/control/offline_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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):
"""
Expand All @@ -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
Expand Down
3 changes: 1 addition & 2 deletions cozy/control/string_representation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions cozy/media/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion cozy/media/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cozy/media/media_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
11 changes: 2 additions & 9 deletions cozy/media/tag_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand Down
5 changes: 2 additions & 3 deletions cozy/model/book.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from contextlib import suppress

from peewee import SqliteDatabase, DoesNotExist

Expand Down Expand Up @@ -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:
Expand Down
5 changes: 1 addition & 4 deletions cozy/model/database_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cozy/model/track.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
7 changes: 4 additions & 3 deletions cozy/report/report_to_loki.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import os

from contextlib import suppress

import requests
import datetime
import pytz
Expand Down Expand Up @@ -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):
Expand Down
5 changes: 1 addition & 4 deletions cozy/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions cozy/ui/book_detail_view.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from contextlib import suppress
import time
from threading import Event, Thread
from typing import Optional, Callable
Expand Down Expand Up @@ -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
Expand Down
2 changes: 0 additions & 2 deletions cozy/ui/headerbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 1 addition & 4 deletions cozy/ui/search_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
7 changes: 1 addition & 6 deletions cozy/ui/widgets/sleep_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

10 changes: 2 additions & 8 deletions cozy/view_model/library_view_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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"}:
Expand Down

0 comments on commit b1efd63

Please sign in to comment.