Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Various improvements in code #825

Merged
merged 11 commits into from
Jan 19, 2024
12 changes: 7 additions & 5 deletions cozy/architecture/observable.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,21 +33,23 @@ def remove_bind(self, prop: str, callback: Callable):
if callback in self._observers[prop]:
self._observers[prop].remove(callback)
else:
log.info("Callback not found in prop's {} observers. Skipping remove bind...".format(prop))
log.info("Callback not found in prop's %s observers. Skipping remove bind...", prop)
else:
log.info("Prop not found in observers. Skipping remove bind...")

def _notify(self, prop: str):
if prop not in self._observers:
return

try:
if prop in self._observers:
for callback in self._observers[prop]:
callback()
for callback in self._observers[prop]:
callback()
except Exception as e:
log.error(e)
reporter.exception("observable", e)

def _notify_main_thread(self, prop: str):
GLib.MainContext.default().invoke_full(GLib.PRIORITY_DEFAULT_IDLE, self._notify, (prop))
GLib.MainContext.default().invoke_full(GLib.PRIORITY_DEFAULT_IDLE, self._notify, prop)

def _destroy_observers(self):
self._observers = {}
2 changes: 1 addition & 1 deletion cozy/control/artwork_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def _load_pixbuf_from_cache(self, book, size):
else:
pixbuf = None
except Exception as e:
log.warning("Failed to load pixbuf from path: {}. Deleting file.".format(path))
log.warning("Failed to load pixbuf from path: %s. Deleting file.", path)
log.debug(e)
os.remove(path)
return None
Expand Down
2 changes: 1 addition & 1 deletion cozy/control/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def init_db():
_connect_db(_db)

sqlite_version = ".".join([str(num) for num in _db.server_version])
log.info("SQLite version: {}".format(sqlite_version))
log.info("SQLite version: %s", sqlite_version)

if Settings.table_exists():
update_db()
Expand Down
4 changes: 2 additions & 2 deletions cozy/control/db_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,15 +136,15 @@ def _update_db_9(db):
file = next((f for f in files if f.path == path), None)

if File.select().where(File.path == path).count() > 0:
log.info("Path already existing in db: {}".format(path))
log.info("Path already existing in db: %s", path)
file = File.select().where(File.path == path).get()
elif not file:
file = File(path=path, modified=track.modified, id=file_id)
files.append(file)
file_id += 1

if TrackToFile.select().join(Track).where(TrackToFile.track.id == track.id).count() > 0:
log.info("TrackToFile already existing in db: {}".format(path))
log.info("TrackToFile already existing in db: %s", path)
continue

track_to_file = TrackToFile(track=track.id, file=file, start_at=0)
Expand Down
4 changes: 2 additions & 2 deletions cozy/control/filesystem_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,10 @@ def is_external(self, directory: str) -> bool:
return False

if path in directory and mount.can_unmount():
log.info("Storage location {} is external".format(directory))
log.info("Storage location %s is external", directory)
return True

log.info("Storage location {} is not external".format(directory))
log.info("Storage location %s is not external", directory)
return False

def __on_mount_added(self, monitor, mount):
Expand Down
6 changes: 3 additions & 3 deletions cozy/control/mpris.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,17 @@ def on_method_call(
result = getattr(self, snake_method)(*args)
except AttributeError:
invocation.return_dbus_error(
"{}.Error.NotSupported".format(interface_name), "Unsupported property"
f"{interface_name}.Error.NotSupported", "Unsupported property"
)
except Exception as e:
log.error(e)
reporter.exception("mpris", e)
reporter.error(
"mpris",
"MPRIS method call failed with method name: {}".format(method_name),
f"MPRIS method call failed with method name: {method_name}",
)
invocation.return_dbus_error(
"{}.Error.Failed".format(interface_name), "Internal exception occurred"
f"{interface_name}.Error.Failed", "Internal exception occurred"
)
else:
# out_args is at least (signature1).
Expand Down
4 changes: 2 additions & 2 deletions cozy/media/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def _copy_all(self, sources, destination: str):
self._copy_file(path, file_copy_destination)

def _copy_file(self, source_path: str, dest_path: str):
log.info("Copy file {} to {}".format(source_path, dest_path))
log.info("Copy file %s to %s", source_path, dest_path)

source = Gio.File.new_for_path(source_path)
destination = Gio.File.new_for_path(dest_path)
Expand All @@ -72,7 +72,7 @@ def _copy_file(self, source_path: str, dest_path: str):
else:
reporter.exception("files", e)

log.error("Failed to copy file: {}".format(e))
log.error("Failed to copy file: %s", e)
self._file_progess += 1

def _copy_directory(self, path, destination):
Expand Down
6 changes: 3 additions & 3 deletions cozy/media/gst_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def state(self) -> GstPlayerState:
elif state == Gst.State.PAUSED:
return GstPlayerState.PAUSED
else:
log.debug("GST player state was not playing or paused but {}.".format(state))
log.debug("GST player state was not playing or paused but %s", state)
return GstPlayerState.STOPPED

@property
Expand Down Expand Up @@ -268,7 +268,7 @@ def _on_gst_message(self, _, message: Gst.Message):
reporter.warning("gst_player", "gst: Resource not found. Stopping player.")
return

reporter.error("player", "{}: {}".format(error.code, error))
log.error("{}: {}".format(error.code, error))
reporter.error("player", f"{error.code}: {error}")
log.error("%s: %s", error.code, error)
log.debug(debug_msg)
self.emit_event("error", error)
2 changes: 1 addition & 1 deletion cozy/media/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def _filter_unchanged_files(self, files: List[str]) -> List[str]:
yield file
except Exception as e:
log.debug(e)
log.info("Could not get modified timestamp for file {}".format(file))
log.info("Could not get modified timestamp for file %s", file)
continue

continue
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 @@ -34,7 +34,7 @@ def get_media_data(self) -> MediaFile:
try:
discoverer_info: GstPbutils.DiscovererInfo = self.discoverer.discover_uri(self.uri)
except Exception as e:
log.info("Skipping file because it couldn't be detected: {}".format(self.uri))
log.info("Skipping file because it couldn't be detected: %s", self.uri)
raise AudioFileCouldNotBeDiscovered(self.uri)

is_valid_audio_file = self._is_valid_audio_file(discoverer_info)
Expand Down
2 changes: 1 addition & 1 deletion cozy/media/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ def _emit_tick(self):
position_for_ui = self.position - self.loaded_chapter.start_position
self.emit_event_main_thread("position", position_for_ui)
except Exception as e:
log.warning("Could not emit position event: {}".format(e))
log.warning("Could not emit position event: %s", e)

def _fadeout_playback(self):
duration = self._app_settings.sleep_timer_fadeout_duration * 20
Expand Down
2 changes: 1 addition & 1 deletion cozy/model/book.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def _fetch_chapters(self):
except TrackInconsistentData:
log.warning("Skipping inconsistent model")
except Exception as e:
log.error("Could not create chapter object: {}".format(e))
log.error("Could not create chapter object: %s", e)

for chapter in self._chapters:
chapter.add_listener(self._on_chapter_event)
Expand Down
2 changes: 1 addition & 1 deletion cozy/model/database_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def _prepare_track_db_objects(self, media_files: Set[MediaFile]) -> Set[TrackIns
book = next((book for book in book_db_objects if is_same_book(book.name, media_file.book_name)), None)
file_query = File.select().where(File.path == media_file.path)
if not file_query.exists():
log.error("No file object with path present: {}".format(media_file.path))
log.error("No file object with path present: %s", media_file.path)
continue

file = file_query.get()
Expand Down
4 changes: 1 addition & 3 deletions cozy/model/library.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,8 @@ def rebase_path(self, old_path: str, new_path: str):
self.emit_event_main_thread("rebase-started")

chapter_count = len(self.chapters)
progress = 0
for chapter in self.chapters:
for progress, chapter in enumerate(self.chapters, 1):
if chapter.file.startswith(old_path):
progress += 1
chapter.file = chapter.file.replace(old_path, new_path)
self.emit_event_main_thread("rebase-progress", progress / chapter_count)

Expand Down
29 changes: 13 additions & 16 deletions cozy/model/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import logging
from typing import List, Optional

import peewee

Expand All @@ -16,8 +15,8 @@


class Settings:
_storages: List[Storage] = []
_db = cache = inject.attr(SqliteDatabase)
_storages: list[Storage] = []
_db = inject.attr(SqliteDatabase)

def __init__(self):
self._db_object: SettingsModel = SettingsModel.get()
Expand All @@ -27,7 +26,7 @@ def first_start(self) -> bool:
return self._db_object.first_start

@property
def last_played_book(self) -> Optional[Book]:
def last_played_book(self) -> Book | None:
try:
return self._db_object.last_played_book
except peewee.DoesNotExist:
Expand All @@ -48,21 +47,21 @@ def last_played_book(self, new_value):
self._db_object.save(only=self._db_object.dirty_fields)

@property
def default_location(self):
return next(location
for location
in self.storage_locations
if location.default)
def default_location(self) -> bool:
for location in self.storage_locations:
if location.default:
return True
rdbende marked this conversation as resolved.
Show resolved Hide resolved
return False

@property
def storage_locations(self):
def storage_locations(self) -> list[Storage]:
if not self._storages:
self._load_all_storage_locations()

return self._storages

@property
def external_storage_locations(self):
def external_storage_locations(self) -> list[Storage]:
if not self._storages:
self._load_all_storage_locations()

Expand All @@ -78,14 +77,12 @@ def _load_all_storage_locations(self):
try:
self._storages.append(Storage(self._db, storage_db_obj.id))
except InvalidPath:
log.error("Invalid path found in database, skipping: {}".format(storage_db_obj.path))
log.error("Invalid path found in database, skipping: %s", storage_db_obj.path)

self._ensure_default_storage_present()

def _ensure_default_storage_present(self):
default_storage_present = any(storage.default
for storage
in self._storages)
default_storage_present = any(storage.default for storage in self._storages)

if not default_storage_present and len(self._storages) > 0:
if not default_storage_present and self._storages:
self._storages[0].default = True
31 changes: 0 additions & 31 deletions cozy/model/single_file_chapter.py

This file was deleted.

2 changes: 1 addition & 1 deletion cozy/model/track.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def name(self):
if self._db_object.name:
return self._db_object.name

return "{} {}".format(_("Chapter"), self.number)
return f"{_('Chapter')} {self.number}"
rdbende marked this conversation as resolved.
Show resolved Hide resolved

@name.setter
def name(self, new_name: str):
Expand Down
2 changes: 1 addition & 1 deletion cozy/report/report_to_loki.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def report(component: str, type: LogLevel, message: str, exception: Exception):
labels = __append_label(labels, "distro_version", distro.version())
labels = __append_label(labels, "desktop_environment", os.environ.get('DESKTOP_SESSION'))

line = "[{}] {}".format(LOG_LEVEL_MAP[type], message)
line = f"[{LOG_LEVEL_MAP[type]}] {message}"
rdbende marked this conversation as resolved.
Show resolved Hide resolved

headers = {
'Content-type': 'application/json'
Expand Down
7 changes: 3 additions & 4 deletions cozy/ui/library_view.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import functools
from typing import Optional

from gi.repository import Gtk, Adw
from gi.repository.Gtk import Builder
from gi.repository import Adw, Gtk

from cozy.ext import inject
from cozy.ui.widgets.book_element import BookElement
from cozy.ui.delete_book_view import DeleteBookView
from cozy.ui.widgets.filter_list_box import FilterListBox
from cozy.view_model.library_view_model import LibraryViewModel, LibraryViewMode, LibraryPage
from cozy.view_model.library_view_model import LibraryViewModel, LibraryViewMode

READER_PAGE = "reader"
AUTHOR_PAGE = "author"
Expand All @@ -23,7 +22,7 @@
class LibraryView:
_view_model: LibraryViewModel = inject.attr(LibraryViewModel)

def __init__(self, builder: Builder):
def __init__(self, builder: Gtk.Builder):
self._builder = builder
self._connected_book_element: Optional[BookElement] = None

Expand Down
Loading