Skip to content

Commit a10442f

Browse files
authored
typing (#1207)
1 parent ec83fa5 commit a10442f

File tree

6 files changed

+244
-145
lines changed

6 files changed

+244
-145
lines changed

nowplaying/db.py

Lines changed: 34 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,13 +173,16 @@ 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')
183+
if metadata is None:
184+
logging.debug('metadata is None')
185+
return
178186
if (not metadata or not METADATALIST or 'title' not in metadata
179187
or 'artist' not in metadata):
180188
logging.debug('metadata is either empty or too incomplete')
@@ -186,7 +194,7 @@ def filterkeys(mydict):
186194
async with aiosqlite.connect(self.databasefile, timeout=10) as connection:
187195
# do not want to modify the original dictionary
188196
# otherwise Bad Things(tm) will happen
189-
mdcopy = copy.deepcopy(metadata)
197+
mdcopy: dict[str, Any] = copy.deepcopy(dict(metadata))
190198
mdcopy['artistfanartraw'] = None
191199

192200
# toss any keys we do not care about
@@ -214,7 +222,7 @@ def filterkeys(mydict):
214222
await cursor.execute(sql, datatuple)
215223
await connection.commit()
216224

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

220228
if not self.databasefile.exists():
@@ -237,7 +245,7 @@ def make_previoustracklist(self):
237245

238246
return previouslist
239247

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

243251
if not self.databasefile.exists():
@@ -262,9 +270,9 @@ async def make_previoustracklist_async(self):
262270
return previouslist
263271

264272
@staticmethod
265-
def _postprocess_read_last_meta(row):
273+
def _postprocess_read_last_meta(row: sqlite3.Row) -> "TrackMetadata":
266274
''' common post-process of read_last_meta '''
267-
metadata = {data: row[data] for data in METADATALIST}
275+
metadata: dict[str, Any] = {data: row[data] for data in METADATALIST}
268276
for key in METADATABLOBLIST:
269277
metadata[key] = row[key]
270278
if not metadata[key]:
@@ -276,9 +284,9 @@ def _postprocess_read_last_meta(row):
276284
metadata[key] = metadata[key].split(SPLITSTR)
277285

278286
metadata['dbid'] = row['id']
279-
return metadata
287+
return metadata # type: ignore[return-value]
280288

281-
async def read_last_meta_async(self):
289+
async def read_last_meta_async(self) -> "TrackMetadata | None":
282290
''' update metadb '''
283291

284292
if not self.databasefile.exists():
@@ -302,10 +310,10 @@ async def read_last_meta_async(self):
302310
return None
303311

304312
metadata = self._postprocess_read_last_meta(row)
305-
metadata['previoustrack'] = await self.make_previoustracklist_async()
313+
metadata['previoustrack'] = await self.make_previoustracklist_async() # type: ignore[misc]
306314
return metadata
307315

308-
def read_last_meta(self):
316+
def read_last_meta(self) -> "TrackMetadata | None":
309317
''' update metadb '''
310318

311319
if not self.databasefile.exists():
@@ -326,7 +334,7 @@ def read_last_meta(self):
326334
return None
327335

328336
metadata = self._postprocess_read_last_meta(row)
329-
metadata['previoustrack'] = self.make_previoustracklist()
337+
metadata['previoustrack'] = self.make_previoustracklist() # type: ignore[misc]
330338
return metadata
331339

332340
def setupsql(self):
@@ -369,7 +377,8 @@ def vacuum_database(self):
369377
logging.error("Database error during vacuum: %s", error)
370378

371379

372-
def create_setlist(config=None, databasefile=None):
380+
def create_setlist(config: "nowplaying.config.ConfigFile | None" = None,
381+
databasefile: str | None = None) -> None:
373382
''' create the setlist '''
374383

375384
if not config:
@@ -385,7 +394,7 @@ def create_setlist(config=None, databasefile=None):
385394
logging.info('No tracks were played; not saving setlist')
386395
return
387396

388-
previoustrack = metadata['previoustrack']
397+
previoustrack = metadata['previoustrack'] # type: ignore[misc]
389398
if not previoustrack:
390399
logging.info('No previoustracks were played; not saving setlist')
391400
return

0 commit comments

Comments
 (0)