Skip to content

Commit a6ece6a

Browse files
committed
typing
1 parent ec83fa5 commit a6ece6a

File tree

6 files changed

+239
-143
lines changed

6 files changed

+239
-143
lines changed

nowplaying/db.py

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,20 @@
88
import sys
99
import sqlite3
1010
import time
11-
import typing as t
11+
from typing import TYPE_CHECKING, Any
1212

1313
import aiosqlite
1414

15+
import watchdog.observers.api # pylint: disable=import-error, no-name-in-module
1516
from watchdog.observers import Observer # pylint: disable=import-error
1617
from watchdog.events import PatternMatchingEventHandler # pylint: disable=import-error
1718

1819
from PySide6.QtCore import QStandardPaths # pylint: disable=import-error, no-name-in-module
1920

21+
if TYPE_CHECKING:
22+
from nowplaying.types import TrackMetadata
23+
import nowplaying.config
24+
2025
SPLITSTR = '@@SPLITHERE@@'
2126

2227
METADATALIST = [
@@ -84,12 +89,12 @@
8489
class DBWatcher:
8590
''' utility to watch for database changes '''
8691

87-
def __init__(self, databasefile):
88-
self.observer = None
89-
self.event_handler = None
90-
self.updatetime = time.time()
91-
self.databasefile = databasefile
92-
self.callback = None
92+
def __init__(self, databasefile: str | pathlib.Path):
93+
self.observer: watchdog.observers.api.BaseObserver | None = None
94+
self.event_handler: PatternMatchingEventHandler | None = None
95+
self.updatetime: float = time.time()
96+
self.databasefile: str = str(databasefile) # Convert to string for os.path functions
97+
self.callback: Any = None
9398

9499
def start(self, customhandler=None):
95100
''' fire up the watcher '''
@@ -137,17 +142,17 @@ def __del__(self):
137142
class MetadataDB:
138143
""" Metadata DB module"""
139144

140-
def __init__(self, databasefile: t.Optional[str] = None, initialize=False):
141-
self.watchers = set()
145+
def __init__(self, databasefile: str | pathlib.Path | None = None, initialize: bool = False):
146+
self.watchers: set[DBWatcher] = set()
142147

143-
self.databasefile = self.init_db_var(databasefile=databasefile)
148+
self.databasefile: pathlib.Path = self.init_db_var(databasefile=databasefile)
144149
logging.debug("Metadata DB at %s", self.databasefile)
145150
if not self.databasefile.exists() or initialize:
146151
logging.debug('Setting up a new DB')
147152
self.setupsql()
148153

149154
@staticmethod
150-
def init_db_var(databasefile) -> pathlib.Path:
155+
def init_db_var(databasefile: str | pathlib.Path | None) -> pathlib.Path:
151156
""" split this out to make testing easier """
152157
if os.environ.get("WNP_METADB_TEST_FILE"):
153158
return pathlib.Path(os.environ["WNP_METADB_TEST_FILE"])
@@ -168,10 +173,10 @@ def __del__(self):
168173
logging.exception("Clearing leftover watcher")
169174
watcher.stop()
170175

171-
async def write_to_metadb(self, metadata=None):
176+
async def write_to_metadb(self, metadata: "TrackMetadata | None" = None) -> None:
172177
''' update metadb '''
173178

174-
def filterkeys(mydict):
179+
def filterkeys(mydict: dict[str, Any]) -> dict[str, Any]:
175180
return {key: mydict[key] for key in METADATALIST + METADATABLOBLIST if key in mydict}
176181

177182
logging.debug('Called (async) write_to_metadb')
@@ -186,7 +191,7 @@ def filterkeys(mydict):
186191
async with aiosqlite.connect(self.databasefile, timeout=10) as connection:
187192
# do not want to modify the original dictionary
188193
# otherwise Bad Things(tm) will happen
189-
mdcopy = copy.deepcopy(metadata)
194+
mdcopy: dict[str, Any] = copy.deepcopy(dict(metadata))
190195
mdcopy['artistfanartraw'] = None
191196

192197
# toss any keys we do not care about
@@ -214,7 +219,7 @@ def filterkeys(mydict):
214219
await cursor.execute(sql, datatuple)
215220
await connection.commit()
216221

217-
def make_previoustracklist(self):
222+
def make_previoustracklist(self) -> list[dict[str, str]] | None:
218223
''' create a reversed list of the tracks played '''
219224

220225
if not self.databasefile.exists():
@@ -237,7 +242,7 @@ def make_previoustracklist(self):
237242

238243
return previouslist
239244

240-
async def make_previoustracklist_async(self):
245+
async def make_previoustracklist_async(self) -> list[dict[str, str]] | None:
241246
''' create a reversed list of the tracks played '''
242247

243248
if not self.databasefile.exists():
@@ -262,9 +267,9 @@ async def make_previoustracklist_async(self):
262267
return previouslist
263268

264269
@staticmethod
265-
def _postprocess_read_last_meta(row):
270+
def _postprocess_read_last_meta(row: sqlite3.Row) -> "TrackMetadata":
266271
''' common post-process of read_last_meta '''
267-
metadata = {data: row[data] for data in METADATALIST}
272+
metadata: dict[str, Any] = {data: row[data] for data in METADATALIST}
268273
for key in METADATABLOBLIST:
269274
metadata[key] = row[key]
270275
if not metadata[key]:
@@ -276,9 +281,9 @@ def _postprocess_read_last_meta(row):
276281
metadata[key] = metadata[key].split(SPLITSTR)
277282

278283
metadata['dbid'] = row['id']
279-
return metadata
284+
return metadata # type: ignore[return-value]
280285

281-
async def read_last_meta_async(self):
286+
async def read_last_meta_async(self) -> "TrackMetadata | None":
282287
''' update metadb '''
283288

284289
if not self.databasefile.exists():
@@ -302,10 +307,10 @@ async def read_last_meta_async(self):
302307
return None
303308

304309
metadata = self._postprocess_read_last_meta(row)
305-
metadata['previoustrack'] = await self.make_previoustracklist_async()
310+
metadata['previoustrack'] = await self.make_previoustracklist_async() # type: ignore[misc]
306311
return metadata
307312

308-
def read_last_meta(self):
313+
def read_last_meta(self) -> "TrackMetadata | None":
309314
''' update metadb '''
310315

311316
if not self.databasefile.exists():
@@ -326,7 +331,7 @@ def read_last_meta(self):
326331
return None
327332

328333
metadata = self._postprocess_read_last_meta(row)
329-
metadata['previoustrack'] = self.make_previoustracklist()
334+
metadata['previoustrack'] = self.make_previoustracklist() # type: ignore[misc]
330335
return metadata
331336

332337
def setupsql(self):
@@ -369,7 +374,8 @@ def vacuum_database(self):
369374
logging.error("Database error during vacuum: %s", error)
370375

371376

372-
def create_setlist(config=None, databasefile=None):
377+
def create_setlist(config: "nowplaying.config.ConfigFile | None" = None,
378+
databasefile: str | None = None) -> None:
373379
''' create the setlist '''
374380

375381
if not config:
@@ -385,7 +391,7 @@ def create_setlist(config=None, databasefile=None):
385391
logging.info('No tracks were played; not saving setlist')
386392
return
387393

388-
previoustrack = metadata['previoustrack']
394+
previoustrack = metadata['previoustrack'] # type: ignore[misc]
389395
if not previoustrack:
390396
logging.info('No previoustracks were played; not saving setlist')
391397
return

0 commit comments

Comments
 (0)