Skip to content

Commit

Permalink
Clean up files and remove small useless ones (#965)
Browse files Browse the repository at this point in the history
* Cleanup logs in main.py

* Move power manager out of its own file

* Move enums to a common file

* I could never get my head around these filenames

* Missed a file again, thanks, Ruff

* Seems like I chose a bad way to clean up the imports

* Start using pathlib in more places

* Fix issues ruff warned about

* Update cozy/db/model_base.py
  • Loading branch information
rdbende authored Nov 29, 2024
1 parent 77ce7b9 commit 6cda5f3
Show file tree
Hide file tree
Showing 38 changed files with 273 additions and 285 deletions.
9 changes: 2 additions & 7 deletions cozy/app_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,26 @@
from gi.repository import Gio
from peewee import SqliteDatabase

from cozy.application_settings import ApplicationSettings
from cozy.architecture.singleton import Singleton
from cozy.control.db import get_db
from cozy.control.filesystem_monitor import FilesystemMonitor
from cozy.control.offline_cache import OfflineCache
from cozy.enums import OpenView, View
from cozy.media.files import Files
from cozy.media.player import GstPlayer, Player
from cozy.model.book import Book
from cozy.model.database_importer import DatabaseImporter
from cozy.model.library import Library
from cozy.model.settings import Settings
from cozy.open_view import OpenView
from cozy.power_manager import PowerManager
from cozy.report import reporter
from cozy.settings import ApplicationSettings
from cozy.ui.app_view import AppView
from cozy.ui.headerbar import Headerbar
from cozy.ui.library_view import LibraryView
from cozy.ui.main_view import CozyUI
from cozy.ui.media_controller import MediaController
from cozy.ui.search_view import SearchView
from cozy.ui.toaster import ToastNotifier
from cozy.view import View
from cozy.view_model.app_view_model import AppViewModel
from cozy.view_model.book_detail_view_model import BookDetailViewModel
from cozy.view_model.headerbar_view_model import HeaderbarViewModel
Expand Down Expand Up @@ -74,8 +72,6 @@ def __init__(self, gtk_app, main_window_builder, main_window):

self.main_window.add_listener(self._on_main_window_event)

self.power_manager = inject.instance(PowerManager)

def configure_inject(self, binder):
binder.bind_to_provider(SqliteDatabase, get_db)
binder.bind("MainWindow", self.main_window)
Expand All @@ -98,7 +94,6 @@ def configure_inject(self, binder):
binder.bind_to_constructor(PlaybackSpeedViewModel, lambda: PlaybackSpeedViewModel())
binder.bind_to_constructor(SleepTimerViewModel, lambda: SleepTimerViewModel())
binder.bind_to_constructor(GstPlayer, lambda: GstPlayer())
binder.bind_to_constructor(PowerManager, lambda: PowerManager())
binder.bind_to_constructor(ToastNotifier, lambda: ToastNotifier())
binder.bind_to_constructor(AppViewModel, lambda: AppViewModel())
binder.bind_to_constructor(SettingsViewModel, lambda: SettingsViewModel())
Expand Down
28 changes: 18 additions & 10 deletions cozy/control/application_directories.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,28 @@
import os
from pathlib import Path

from gi.repository import GLib


def get_artwork_cache_dir():
return os.path.join(get_cache_dir(), "artwork")
def get_path_relative_to_chache_folder(*args) -> Path:
dir = Path(GLib.get_user_cache_dir(), "cozy", *args)
dir.mkdir(parents=True, exist_ok=True)
return dir


def get_cache_dir():
cache_dir = os.path.join(GLib.get_user_cache_dir(), "cozy")
def get_artwork_cache_dir() -> Path:
return get_path_relative_to_chache_folder("artwork")

if not os.path.exists(cache_dir):
os.makedirs(cache_dir)

return cache_dir
def get_offline_cache_dir() -> Path:
return get_path_relative_to_chache_folder("offline")


def get_data_dir():
return os.path.join(GLib.get_user_data_dir(), "cozy")
def get_cache_dir() -> Path:
return get_path_relative_to_chache_folder()


def get_data_dir() -> Path:
dir = Path(GLib.get_user_data_dir(), "cozy")
dir.mkdir(parents=True, exist_ok=True)

return dir
14 changes: 5 additions & 9 deletions cozy/control/artwork_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
import inject
from gi.repository import Gdk, GdkPixbuf

from cozy.application_settings import ApplicationSettings
from cozy.control.application_directories import get_cache_dir
from cozy.control.application_directories import get_artwork_cache_dir
from cozy.db.artwork_cache import ArtworkCache as ArtworkCacheModel
from cozy.media.importer import Importer, ScanStatus
from cozy.report import reporter
from cozy.settings import ApplicationSettings

log = logging.getLogger("artwork_cache")

Expand All @@ -23,10 +23,6 @@ def __init__(self):
_app_settings = inject.instance(ApplicationSettings)
_app_settings.add_listener(self._on_app_setting_changed)

@property
def artwork_cache_dir(self):
return Path(get_cache_dir()) / "artwork"

def get_cover_paintable(self, book, scale, size=0) -> Gdk.Texture | None:
pixbuf = None
size *= scale
Expand All @@ -51,7 +47,7 @@ def delete_artwork_cache(self):
"""
Deletes the artwork cache completely.
"""
shutil.rmtree(self.artwork_cache_dir, ignore_errors=True)
shutil.rmtree(get_artwork_cache_dir(), ignore_errors=True)
ArtworkCacheModel.delete().execute()

def _on_importer_event(self, event, data):
Expand All @@ -75,7 +71,7 @@ def _create_artwork_cache(self, book, pixbuf, size):
uuid = str(uuid4())
ArtworkCacheModel.create(book=book.id, uuid=uuid)

cache_dir = self.artwork_cache_dir / uuid
cache_dir = get_artwork_cache_dir() / uuid
cache_dir.mkdir(exist_ok=True, parents=True)
file_path = (cache_dir / str(size)).with_suffix(".jpg")

Expand Down Expand Up @@ -104,7 +100,7 @@ def get_album_art_path(self, book, size) -> str:
)
return None

cache_dir = self.artwork_cache_dir / uuid
cache_dir = get_artwork_cache_dir() / uuid

if cache_dir.is_dir():
file_path = (cache_dir / str(size)).with_suffix(".jpg")
Expand Down
5 changes: 4 additions & 1 deletion cozy/control/db_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
from playhouse.reflection import generate_models

from cozy.control.application_directories import get_cache_dir
from cozy.control.application_directories import get_data_dir as get_data_dir_path
from cozy.db.file import File
from cozy.db.model_base import get_data_dir, get_sqlite_database
from cozy.db.model_base import get_sqlite_database
from cozy.db.offline_cache import OfflineCache
from cozy.db.settings import Settings
from cozy.db.storage import Storage
Expand All @@ -20,6 +21,8 @@

log = logging.getLogger("db_updater")

get_data_dir = lambda: str(get_data_dir_path()) # i don't want to rewrite this file for pathlib


def __update_db_1(db):
migrator = SqliteMigrator(db)
Expand Down
2 changes: 1 addition & 1 deletion cozy/control/mpris.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
import inject
from gi.repository import Gio, GLib

from cozy.application_settings import ApplicationSettings
from cozy.control.artwork_cache import ArtworkCache
from cozy.media.player import Player
from cozy.model.book import Book
from cozy.report import reporter
from cozy.settings import ApplicationSettings

log = logging.getLogger("mpris")

Expand Down
25 changes: 13 additions & 12 deletions cozy/control/offline_cache.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import logging
import os
import uuid
from pathlib import Path

import inject
from gi.repository import Gio

import cozy.tools as tools
from cozy.architecture.event_sender import EventSender
from cozy.control.application_directories import get_cache_dir
from cozy.control.application_directories import get_offline_cache_dir
from cozy.db.file import File
from cozy.db.offline_cache import OfflineCache as OfflineCacheModel
from cozy.db.track_to_file import TrackToFile
Expand All @@ -25,6 +26,7 @@ class OfflineCache(EventSender):
This includes operations like copying to the cache and adding or removing files from
the cache.
"""

queue = []
total_batch_count = 0
current_batch_count = 0
Expand All @@ -38,16 +40,16 @@ def __init__(self):
super().__init__()

from cozy.media.importer import Importer

self._importer = inject.instance(Importer)

from cozy.model.library import Library

self._library = inject.instance(Library)

self._importer.add_listener(self._on_importer_event)

self.cache_dir = os.path.join(get_cache_dir(), "offline")
if not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
self.cache_dir = get_offline_cache_dir()

self._start_processing()

Expand Down Expand Up @@ -104,21 +106,21 @@ def remove(self, book: Book):
def remove_all_for_storage(self, storage):
for element in OfflineCacheModel.select().join(File).where(
storage.path in OfflineCacheModel.original_file.path):
file_path = os.path.join(self.cache_dir, element.cached_file)
file_path = self.cache_dir / element.cached_file
if file_path == self.cache_dir:
continue

file = Gio.File.new_for_path(file_path)
file = Gio.File.new_for_path(str(file_path))
if file.query_exists():
file.delete()

OfflineCacheModel.delete().where(storage.path in OfflineCacheModel.original_file.path).execute()

def get_cached_path(self, chapter: Chapter):
def get_cached_path(self, chapter: Chapter) -> Path:
query = OfflineCacheModel.select().where(OfflineCacheModel.original_file == chapter.file_id,
OfflineCacheModel.copied)
if query.count() > 0:
return os.path.join(self.cache_dir, query.get().cached_file)
return self.cache_dir / query.get().cached_file
else:
return None

Expand All @@ -136,14 +138,13 @@ def delete_cache(self):
Deletes the entire offline cache files.
Doesn't delete anything from the cozy.db.
"""
cache_dir = os.path.join(get_cache_dir(), "offline")

import shutil
shutil.rmtree(cache_dir)

shutil.rmtree(self.cache_dir)

def _stop_processing(self):
"""
"""
""" """
if not self._is_processing() or not self.thread:
return

Expand Down
8 changes: 3 additions & 5 deletions cozy/db/model_base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import logging
import os

from peewee import Model
from playhouse.sqliteq import SqliteQueueDatabase
Expand All @@ -17,14 +16,13 @@ def get_sqlite_database():


def database_file_exists():
return os.path.exists(os.path.join(get_data_dir(), "cozy.db"))
return (get_data_dir() / "cozy.db").is_file()


def __open_database():
global _db
if not os.path.exists(get_data_dir()):
os.makedirs(get_data_dir())
_db = SqliteQueueDatabase(os.path.join(get_data_dir(), "cozy.db"), queue_max_size=128, results_timeout=15.0,

_db = SqliteQueueDatabase(str(get_data_dir() / "cozy.db"), queue_max_size=128, results_timeout=15.0,
timeout=15.0, pragmas=[('cache_size', -1024 * 32), ('journal_mode', 'wal')])


Expand Down
19 changes: 19 additions & 0 deletions cozy/enums.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from enum import Enum, auto


class OpenView(Enum):
AUTHOR = auto()
READER = auto()
BOOK = auto()
LIBRARY = auto()
BACK = auto()


class View(Enum):
EMPTY_STATE = auto()
PREPARING_LIBRARY = auto()
LIBRARY = auto()
LIBRARY_FILTER = auto()
LIBRARY_BOOKS = auto()
BOOK_DETAIL = auto()
NO_MEDIA = auto()
32 changes: 28 additions & 4 deletions cozy/media/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
from typing import Optional

import inject
from gi.repository import GLib, Gst, GstController
from gi.repository import GLib, Gst, GstController, Gtk

from cozy.application_settings import ApplicationSettings
from cozy.architecture.event_sender import EventSender
from cozy.control.offline_cache import OfflineCache
from cozy.media.importer import Importer, ScanStatus
from cozy.model.book import Book
from cozy.model.chapter import Chapter
from cozy.model.library import Library
from cozy.report import reporter
from cozy.settings import ApplicationSettings
from cozy.tools import IntervalTimer
from cozy.ui.file_not_found_dialog import FileNotFoundDialog
from cozy.ui.toaster import ToastNotifier
Expand Down Expand Up @@ -315,6 +315,29 @@ def _on_gst_message(self, _, message: Gst.Message):
self.emit_event("error", error)


class PowerManager:
_gtk_app = inject.attr("GtkApp")

def __init__(self):
self._inhibit_cookie = None

def _on_player_changed(self, event: str, data):
if event in ["pause", "stop"]:
if self._inhibit_cookie:
log.info("Uninhibited standby.")
self._gtk_app.uninhibit(self._inhibit_cookie)
self._inhibit_cookie = None

elif event == "play":
if self._inhibit_cookie:
return

self._inhibit_cookie = self._gtk_app.inhibit(
None, Gtk.ApplicationInhibitFlags.SUSPEND, "Playback of audiobook"
)
log.info("Inhibited standby.")


class Player(EventSender):
_library: Library = inject.attr(Library)
_app_settings: ApplicationSettings = inject.attr(ApplicationSettings)
Expand All @@ -329,6 +352,7 @@ def __init__(self):
self._book: Optional[Book] = None
self._play_next_chapter: bool = True

self.add_listener(PowerManager()._on_player_changed)
self._importer.add_listener(self._on_importer_event)
self._gst_player.add_listener(self._on_gst_player_event)

Expand Down Expand Up @@ -514,8 +538,8 @@ def _get_playback_path(self, chapter: Chapter):
if self._book.offline and self._book.downloaded:
path = self._offline_cache.get_cached_path(chapter)

if path and os.path.exists(path):
return path
if path and path.exists():
return str(path)

return chapter.file

Expand Down
2 changes: 1 addition & 1 deletion cozy/model/book.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import inject
from peewee import DoesNotExist, SqliteDatabase

from cozy.application_settings import ApplicationSettings
from cozy.architecture.event_sender import EventSender
from cozy.architecture.observable import Observable
from cozy.db.book import Book as BookModel
Expand All @@ -14,6 +13,7 @@
from cozy.model.chapter import Chapter
from cozy.model.settings import Settings
from cozy.model.track import Track, TrackInconsistentData
from cozy.settings import ApplicationSettings

log = logging.getLogger("BookModel")

Expand Down
9 changes: 0 additions & 9 deletions cozy/open_view.py

This file was deleted.

Loading

0 comments on commit 6cda5f3

Please sign in to comment.