smfetch 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- smfetch/__init__.py +0 -0
- smfetch/app.py +260 -0
- smfetch/config.py +115 -0
- smfetch/jobs.py +105 -0
- smfetch/smonline.py +191 -0
- smfetch/static/index.html +1185 -0
- smfetch/zenius.py +296 -0
- smfetch-1.0.1.dist-info/METADATA +50 -0
- smfetch-1.0.1.dist-info/RECORD +11 -0
- smfetch-1.0.1.dist-info/WHEEL +4 -0
- smfetch-1.0.1.dist-info/entry_points.txt +2 -0
smfetch/__init__.py
ADDED
|
File without changes
|
smfetch/app.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""FastAPI web application for smfetch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from collections.abc import AsyncIterator
|
|
7
|
+
from contextlib import asynccontextmanager
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import uvicorn
|
|
12
|
+
from fastapi import FastAPI, Query
|
|
13
|
+
from fastapi.responses import FileResponse, HTMLResponse
|
|
14
|
+
from fastapi.staticfiles import StaticFiles
|
|
15
|
+
from loguru import logger
|
|
16
|
+
from pydantic import BaseModel
|
|
17
|
+
|
|
18
|
+
from smfetch import smonline as smo
|
|
19
|
+
from smfetch import zenius as zen
|
|
20
|
+
from smfetch.config import config
|
|
21
|
+
from smfetch.jobs import jobs
|
|
22
|
+
|
|
23
|
+
STATIC_DIR = Path(__file__).parent / "static"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# --- Pydantic request models ---
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ConfigUpdate(BaseModel):
|
|
30
|
+
songs_dir: str | None = None
|
|
31
|
+
log_dir: str | None = None
|
|
32
|
+
config_dir: str | None = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ZenSongDownload(BaseModel):
|
|
36
|
+
song_name: str
|
|
37
|
+
song_page: str
|
|
38
|
+
pack_name: str
|
|
39
|
+
pack_page: str
|
|
40
|
+
group: str = ""
|
|
41
|
+
sp: str = ""
|
|
42
|
+
dp: str = ""
|
|
43
|
+
artist: str = ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ZenCategoryDownload(BaseModel):
|
|
47
|
+
id: str
|
|
48
|
+
title: str = ""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ZenGroupDownload(BaseModel):
|
|
52
|
+
group: str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class SmoDownload(BaseModel):
|
|
56
|
+
pack_title: str
|
|
57
|
+
download: str
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# --- App lifespan ---
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@asynccontextmanager
|
|
64
|
+
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
65
|
+
logger.remove()
|
|
66
|
+
logger.add(str(config.log_file), retention="7 days", rotation="10 MB")
|
|
67
|
+
logger.info("smfetch starting up")
|
|
68
|
+
smo.pack_cache.build_async()
|
|
69
|
+
yield
|
|
70
|
+
logger.info("smfetch shutting down")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
app = FastAPI(title="smfetch", version="1.0.0", lifespan=lifespan)
|
|
74
|
+
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# --- UI ---
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@app.get("/", response_class=HTMLResponse)
|
|
81
|
+
async def index() -> FileResponse:
|
|
82
|
+
return FileResponse(STATIC_DIR / "index.html")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# --- Config ---
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@app.get("/api/config")
|
|
89
|
+
async def get_config() -> dict[str, str]:
|
|
90
|
+
return {
|
|
91
|
+
"songs_dir": config.songs_dir,
|
|
92
|
+
"log_dir": config.log_dir,
|
|
93
|
+
"config_dir": config.config_dir,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@app.put("/api/config")
|
|
98
|
+
async def update_config(body: ConfigUpdate) -> dict[str, str]:
|
|
99
|
+
if body.songs_dir is not None:
|
|
100
|
+
config.songs_dir = body.songs_dir
|
|
101
|
+
if body.log_dir is not None:
|
|
102
|
+
config.log_dir = body.log_dir
|
|
103
|
+
if body.config_dir is not None:
|
|
104
|
+
config.config_dir = body.config_dir
|
|
105
|
+
config.ensure_dirs()
|
|
106
|
+
config.save()
|
|
107
|
+
return await get_config()
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# --- Jobs ---
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@app.get("/api/jobs")
|
|
114
|
+
async def list_jobs() -> dict[str, Any]:
|
|
115
|
+
return {
|
|
116
|
+
"jobs": jobs.list_jobs(),
|
|
117
|
+
"active_count": jobs.active_count(),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@app.post("/api/jobs/clear")
|
|
122
|
+
async def clear_jobs() -> dict[str, int]:
|
|
123
|
+
return {"cleared": jobs.clear_completed()}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# --- Zenius endpoints ---
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@app.get("/api/zenius/search")
|
|
130
|
+
async def zenius_search(
|
|
131
|
+
title: str = Query(default=""),
|
|
132
|
+
artist: str = Query(default=""),
|
|
133
|
+
) -> list[dict[str, Any]]:
|
|
134
|
+
results = zen.search_songs(title, artist)
|
|
135
|
+
return [r.to_dict() for r in results]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@app.get("/api/zenius/categories")
|
|
139
|
+
async def zenius_categories(
|
|
140
|
+
group: str = Query(..., description="ARCADE, SPINOFF, OFFICIAL, or USER"),
|
|
141
|
+
) -> list[dict[str, str]]:
|
|
142
|
+
try:
|
|
143
|
+
g = zen.Group[group.upper()]
|
|
144
|
+
except KeyError:
|
|
145
|
+
return []
|
|
146
|
+
return zen.fetch_categories(g)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@app.post("/api/zenius/download/song")
|
|
150
|
+
async def zenius_download_song(body: ZenSongDownload) -> dict[str, str]:
|
|
151
|
+
result = zen.SearchResult(
|
|
152
|
+
song_name=body.song_name,
|
|
153
|
+
song_page=body.song_page,
|
|
154
|
+
pack_name=body.pack_name,
|
|
155
|
+
pack_page=body.pack_page,
|
|
156
|
+
group=body.group,
|
|
157
|
+
difficulties=zen.Levels(body.sp, body.dp),
|
|
158
|
+
artist=body.artist,
|
|
159
|
+
)
|
|
160
|
+
job_id = jobs.submit(
|
|
161
|
+
f"Zenius: {result.song_name} by {result.artist}",
|
|
162
|
+
zen.download_song,
|
|
163
|
+
result,
|
|
164
|
+
)
|
|
165
|
+
return {"job_id": job_id}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@app.post("/api/zenius/download/category")
|
|
169
|
+
async def zenius_download_category(body: ZenCategoryDownload) -> dict[str, str]:
|
|
170
|
+
title = body.title or f"Category {body.id}"
|
|
171
|
+
job_id = jobs.submit(
|
|
172
|
+
f"Zenius pack: {title}",
|
|
173
|
+
zen.download_category,
|
|
174
|
+
body.id,
|
|
175
|
+
)
|
|
176
|
+
return {"job_id": job_id}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
@app.post("/api/zenius/download/group")
|
|
180
|
+
async def zenius_download_group(body: ZenGroupDownload) -> dict[str, str]:
|
|
181
|
+
try:
|
|
182
|
+
group = zen.Group[body.group.upper()]
|
|
183
|
+
except KeyError:
|
|
184
|
+
return {"error": f"Invalid group: {body.group}"}
|
|
185
|
+
job_id = jobs.submit(
|
|
186
|
+
f"Zenius bundle: {group.name}",
|
|
187
|
+
zen.download_group,
|
|
188
|
+
group,
|
|
189
|
+
)
|
|
190
|
+
return {"job_id": job_id}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
# --- SMOnline endpoints ---
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@app.get("/api/smonline/search")
|
|
197
|
+
async def smonline_search(
|
|
198
|
+
category: str = Query(..., description="title or artist"),
|
|
199
|
+
query: str = Query(...),
|
|
200
|
+
) -> list[dict[str, Any]]:
|
|
201
|
+
if category not in ("title", "artist"):
|
|
202
|
+
return []
|
|
203
|
+
entries = smo.search_songs(category, query)
|
|
204
|
+
return [e.to_dict() for e in entries]
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@app.get("/api/smonline/packs")
|
|
208
|
+
async def smonline_packs() -> dict[str, Any]:
|
|
209
|
+
return {
|
|
210
|
+
"ready": smo.pack_cache.is_ready,
|
|
211
|
+
"building": smo.pack_cache.is_building,
|
|
212
|
+
"packs": [e.to_dict() for e in smo.pack_cache.entries],
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@app.post("/api/smonline/packs/refresh")
|
|
217
|
+
async def smonline_refresh_cache() -> dict[str, str]:
|
|
218
|
+
smo.pack_cache.build_async()
|
|
219
|
+
return {"status": "rebuilding"}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@app.post("/api/smonline/download")
|
|
223
|
+
async def smonline_download(body: SmoDownload) -> dict[str, str]:
|
|
224
|
+
job_id = jobs.submit(
|
|
225
|
+
f"SMOnline: {body.pack_title}",
|
|
226
|
+
smo.download_pack,
|
|
227
|
+
body.pack_title,
|
|
228
|
+
body.download,
|
|
229
|
+
)
|
|
230
|
+
return {"job_id": job_id}
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# --- Entrypoint ---
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
DEFAULT_PORT = 8095
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def main() -> None:
|
|
240
|
+
parser = argparse.ArgumentParser(description="smfetch web interface")
|
|
241
|
+
parser.add_argument(
|
|
242
|
+
"-p",
|
|
243
|
+
"--port",
|
|
244
|
+
type=int,
|
|
245
|
+
default=DEFAULT_PORT,
|
|
246
|
+
help=f"port for the web interface (default: {DEFAULT_PORT})",
|
|
247
|
+
)
|
|
248
|
+
args = parser.parse_args()
|
|
249
|
+
|
|
250
|
+
print(f"Starting smfetch on http://localhost:{args.port}")
|
|
251
|
+
uvicorn.run(
|
|
252
|
+
"smfetch.app:app",
|
|
253
|
+
host="127.0.0.1",
|
|
254
|
+
port=args.port,
|
|
255
|
+
log_level="warning",
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
if __name__ == "__main__":
|
|
260
|
+
main()
|
smfetch/config.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Cross-platform configuration with sensible defaults per OS.
|
|
2
|
+
|
|
3
|
+
Config file location:
|
|
4
|
+
- Windows: %APPDATA%/smfetch/config.json
|
|
5
|
+
- macOS: ~/Library/Application Support/smfetch/config.json
|
|
6
|
+
- Linux: $XDG_CONFIG_HOME/smfetch/config.json (default ~/.config/smfetch/)
|
|
7
|
+
|
|
8
|
+
Songs directory:
|
|
9
|
+
- Windows: %USERPROFILE%/Music/StepMania Songs
|
|
10
|
+
- macOS: ~/Music/StepMania Songs
|
|
11
|
+
- Linux: ~/.local/share/smfetch
|
|
12
|
+
|
|
13
|
+
Log directory:
|
|
14
|
+
- Windows: %LOCALAPPDATA%/smfetch/logs
|
|
15
|
+
- macOS: ~/Library/Logs/smfetch
|
|
16
|
+
- Linux: $XDG_STATE_HOME/smfetch/logs (default ~/.local/state/smfetch/logs)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import platform
|
|
24
|
+
from dataclasses import asdict, dataclass, field
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
from loguru import logger
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _default_config_dir() -> Path:
|
|
31
|
+
system = platform.system()
|
|
32
|
+
if system == "Windows":
|
|
33
|
+
return Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming")) / "smfetch"
|
|
34
|
+
elif system == "Darwin":
|
|
35
|
+
return Path.home() / "Library" / "Application Support" / "smfetch"
|
|
36
|
+
else:
|
|
37
|
+
return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "smfetch"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _default_songs_dir() -> Path:
|
|
41
|
+
system = platform.system()
|
|
42
|
+
if system in ("Windows", "Darwin"):
|
|
43
|
+
return Path.home() / "Music" / "StepMania Songs"
|
|
44
|
+
else:
|
|
45
|
+
return Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share")) / "smfetch"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _default_log_dir() -> Path:
|
|
49
|
+
system = platform.system()
|
|
50
|
+
if system == "Windows":
|
|
51
|
+
return (
|
|
52
|
+
Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
|
|
53
|
+
/ "smfetch"
|
|
54
|
+
/ "logs"
|
|
55
|
+
)
|
|
56
|
+
elif system == "Darwin":
|
|
57
|
+
return Path.home() / "Library" / "Logs" / "smfetch"
|
|
58
|
+
else:
|
|
59
|
+
return (
|
|
60
|
+
Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local" / "state"))
|
|
61
|
+
/ "smfetch"
|
|
62
|
+
/ "logs"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
CONFIG_PATH = _default_config_dir() / "config.json"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class AppConfig:
|
|
71
|
+
songs_dir: str = field(default_factory=lambda: str(_default_songs_dir()))
|
|
72
|
+
log_dir: str = field(default_factory=lambda: str(_default_log_dir()))
|
|
73
|
+
config_dir: str = field(default_factory=lambda: str(_default_config_dir()))
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def songs_path(self) -> Path:
|
|
77
|
+
return Path(self.songs_dir)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def log_path(self) -> Path:
|
|
81
|
+
return Path(self.log_dir)
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def log_file(self) -> Path:
|
|
85
|
+
return self.log_path / "smfetch.log"
|
|
86
|
+
|
|
87
|
+
def ensure_dirs(self) -> None:
|
|
88
|
+
self.songs_path.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
self.log_path.mkdir(parents=True, exist_ok=True)
|
|
90
|
+
Path(self.config_dir).mkdir(parents=True, exist_ok=True)
|
|
91
|
+
|
|
92
|
+
def save(self) -> None:
|
|
93
|
+
path = Path(self.config_dir) / "config.json"
|
|
94
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
path.write_text(json.dumps(asdict(self), indent=2))
|
|
96
|
+
logger.info(f"Config saved to {path}")
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def load(cls) -> AppConfig:
|
|
100
|
+
path = CONFIG_PATH
|
|
101
|
+
if path.exists():
|
|
102
|
+
try:
|
|
103
|
+
data = json.loads(path.read_text())
|
|
104
|
+
return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
|
|
105
|
+
except (json.JSONDecodeError, TypeError) as e:
|
|
106
|
+
logger.warning(f"Failed to load config from {path}: {e}")
|
|
107
|
+
config = cls()
|
|
108
|
+
config.ensure_dirs()
|
|
109
|
+
config.save()
|
|
110
|
+
return config
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# Singleton config loaded at import
|
|
114
|
+
config = AppConfig.load()
|
|
115
|
+
config.ensure_dirs()
|
smfetch/jobs.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Background job management for download tasks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
import uuid
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from loguru import logger
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class JobStatus(str, Enum):
|
|
17
|
+
PENDING = "pending"
|
|
18
|
+
RUNNING = "running"
|
|
19
|
+
COMPLETED = "completed"
|
|
20
|
+
FAILED = "failed"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Job:
|
|
25
|
+
id: str
|
|
26
|
+
name: str
|
|
27
|
+
status: JobStatus
|
|
28
|
+
created_at: datetime
|
|
29
|
+
error: str | None = None
|
|
30
|
+
_thread: threading.Thread | None = field(default=None, repr=False)
|
|
31
|
+
|
|
32
|
+
def to_dict(self) -> dict[str, Any]:
|
|
33
|
+
return {
|
|
34
|
+
"id": self.id,
|
|
35
|
+
"name": self.name,
|
|
36
|
+
"status": self.status.value,
|
|
37
|
+
"created_at": self.created_at.isoformat(),
|
|
38
|
+
"error": self.error,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class JobManager:
|
|
43
|
+
"""Thread-safe job manager with automatic status tracking."""
|
|
44
|
+
|
|
45
|
+
def __init__(self) -> None:
|
|
46
|
+
self._jobs: dict[str, Job] = {}
|
|
47
|
+
self._lock = threading.Lock()
|
|
48
|
+
|
|
49
|
+
def submit(self, name: str, fn: Callable[..., Any], *args: Any, **kwargs: Any) -> str:
|
|
50
|
+
job_id = uuid.uuid4().hex[:8]
|
|
51
|
+
|
|
52
|
+
def _wrapper() -> None:
|
|
53
|
+
try:
|
|
54
|
+
with self._lock:
|
|
55
|
+
self._jobs[job_id].status = JobStatus.RUNNING
|
|
56
|
+
fn(*args, **kwargs)
|
|
57
|
+
with self._lock:
|
|
58
|
+
self._jobs[job_id].status = JobStatus.COMPLETED
|
|
59
|
+
logger.info(f"Job completed: {name}")
|
|
60
|
+
except Exception as e:
|
|
61
|
+
with self._lock:
|
|
62
|
+
self._jobs[job_id].status = JobStatus.FAILED
|
|
63
|
+
self._jobs[job_id].error = str(e)
|
|
64
|
+
logger.error(f"Job failed: {name} - {e}")
|
|
65
|
+
|
|
66
|
+
thread = threading.Thread(target=_wrapper, daemon=True)
|
|
67
|
+
|
|
68
|
+
job = Job(
|
|
69
|
+
id=job_id,
|
|
70
|
+
name=name,
|
|
71
|
+
status=JobStatus.PENDING,
|
|
72
|
+
created_at=datetime.now(),
|
|
73
|
+
_thread=thread,
|
|
74
|
+
)
|
|
75
|
+
with self._lock:
|
|
76
|
+
self._jobs[job_id] = job
|
|
77
|
+
thread.start()
|
|
78
|
+
logger.info(f"Job started: {name} ({job_id})")
|
|
79
|
+
return job_id
|
|
80
|
+
|
|
81
|
+
def list_jobs(self) -> list[dict[str, Any]]:
|
|
82
|
+
with self._lock:
|
|
83
|
+
return [job.to_dict() for job in self._jobs.values()]
|
|
84
|
+
|
|
85
|
+
def active_count(self) -> int:
|
|
86
|
+
with self._lock:
|
|
87
|
+
return sum(
|
|
88
|
+
1
|
|
89
|
+
for job in self._jobs.values()
|
|
90
|
+
if job.status in (JobStatus.PENDING, JobStatus.RUNNING)
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def clear_completed(self) -> int:
|
|
94
|
+
with self._lock:
|
|
95
|
+
done = [
|
|
96
|
+
jid
|
|
97
|
+
for jid, job in self._jobs.items()
|
|
98
|
+
if job.status in (JobStatus.COMPLETED, JobStatus.FAILED)
|
|
99
|
+
]
|
|
100
|
+
for jid in done:
|
|
101
|
+
del self._jobs[jid]
|
|
102
|
+
return len(done)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
jobs = JobManager()
|
smfetch/smonline.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""StepManiaOnline scraping and download logic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import threading
|
|
7
|
+
import zipfile as zf
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from datetime import date, datetime
|
|
10
|
+
from typing import Any, NamedTuple
|
|
11
|
+
|
|
12
|
+
import requests
|
|
13
|
+
from bs4 import BeautifulSoup as bs
|
|
14
|
+
from bs4 import Tag
|
|
15
|
+
from loguru import logger
|
|
16
|
+
|
|
17
|
+
from smfetch.config import config
|
|
18
|
+
|
|
19
|
+
BASE = "https://stepmaniaonline.net"
|
|
20
|
+
SEARCH = f"{BASE}/search"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PackEntry(NamedTuple):
|
|
24
|
+
pack_title: str
|
|
25
|
+
size: str
|
|
26
|
+
songs: int
|
|
27
|
+
created: date
|
|
28
|
+
download: str
|
|
29
|
+
idx: int
|
|
30
|
+
|
|
31
|
+
def to_dict(self) -> dict[str, Any]:
|
|
32
|
+
return {
|
|
33
|
+
"pack_title": self.pack_title,
|
|
34
|
+
"size": self.size,
|
|
35
|
+
"songs": self.songs,
|
|
36
|
+
"created": self.created.isoformat(),
|
|
37
|
+
"download": self.download,
|
|
38
|
+
"idx": self.idx,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SongEntry(NamedTuple):
|
|
43
|
+
song_title: str
|
|
44
|
+
artist: str
|
|
45
|
+
pack_title: str
|
|
46
|
+
download: str
|
|
47
|
+
idx: int
|
|
48
|
+
|
|
49
|
+
def to_dict(self) -> dict[str, Any]:
|
|
50
|
+
return {
|
|
51
|
+
"song_title": self.song_title,
|
|
52
|
+
"artist": self.artist,
|
|
53
|
+
"pack_title": self.pack_title,
|
|
54
|
+
"download": self.download,
|
|
55
|
+
"idx": self.idx,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _parse_pack_row(row: Tag) -> PackEntry:
|
|
60
|
+
tags = row.select("td")
|
|
61
|
+
title = tags[1].find("a").text # type: ignore[union-attr]
|
|
62
|
+
size = tags[2].text.replace("\xa0", " ")
|
|
63
|
+
songs = int(tags[3].text)
|
|
64
|
+
created = datetime.strptime(tags[5].text.strip(), "%Y-%m-%d").date()
|
|
65
|
+
download = f"{BASE}{tags[6].find('a').get('href')}" # type: ignore[union-attr]
|
|
66
|
+
idx = int(download.split("/")[-2])
|
|
67
|
+
return PackEntry(title, size, songs, created, download, idx)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _parse_search_row(row: Tag) -> SongEntry:
|
|
71
|
+
tags = row.select("td")
|
|
72
|
+
title = tags[1].text
|
|
73
|
+
artist = tags[2].text
|
|
74
|
+
pack = tags[3].text
|
|
75
|
+
download = f"{BASE}/download{tags[3].find('a').get('href')}/" # type: ignore[union-attr]
|
|
76
|
+
idx = int(download.split("/")[-2])
|
|
77
|
+
return SongEntry(title, artist, pack, download, idx)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# --- Pack cache ---
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class PackCache:
|
|
85
|
+
_entries: list[PackEntry] = field(default_factory=list)
|
|
86
|
+
_lock: threading.Lock = field(default_factory=threading.Lock)
|
|
87
|
+
_building: bool = False
|
|
88
|
+
_built: bool = False
|
|
89
|
+
|
|
90
|
+
def build(self) -> None:
|
|
91
|
+
"""Fetch all packs from the site."""
|
|
92
|
+
with self._lock:
|
|
93
|
+
if self._building:
|
|
94
|
+
return
|
|
95
|
+
self._building = True
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
logger.info("Building SMOnline pack cache...")
|
|
99
|
+
response = requests.get(f"{BASE}/packs").text
|
|
100
|
+
soup = bs(response, "html.parser")
|
|
101
|
+
entries = [_parse_pack_row(row) for row in soup.select("tbody tr")]
|
|
102
|
+
with self._lock:
|
|
103
|
+
self._entries = entries
|
|
104
|
+
self._built = True
|
|
105
|
+
logger.info(f"Pack cache built: {len(entries)} packs")
|
|
106
|
+
finally:
|
|
107
|
+
with self._lock:
|
|
108
|
+
self._building = False
|
|
109
|
+
|
|
110
|
+
def build_async(self) -> None:
|
|
111
|
+
"""Start cache build in background thread."""
|
|
112
|
+
thread = threading.Thread(target=self.build, daemon=True)
|
|
113
|
+
thread.start()
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def is_ready(self) -> bool:
|
|
117
|
+
with self._lock:
|
|
118
|
+
return self._built
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def is_building(self) -> bool:
|
|
122
|
+
with self._lock:
|
|
123
|
+
return self._building
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def entries(self) -> list[PackEntry]:
|
|
127
|
+
with self._lock:
|
|
128
|
+
return list(self._entries)
|
|
129
|
+
|
|
130
|
+
def refresh(self) -> None:
|
|
131
|
+
"""Force rebuild the cache."""
|
|
132
|
+
with self._lock:
|
|
133
|
+
self._built = False
|
|
134
|
+
self._entries = []
|
|
135
|
+
self.build()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
pack_cache = PackCache()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# --- Search ---
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def search_songs(category: str, query: str) -> list[SongEntry]:
|
|
145
|
+
"""Search for songs by title or artist on SMOnline."""
|
|
146
|
+
url = f"{SEARCH}/{category}/{query}"
|
|
147
|
+
response = requests.get(url).text
|
|
148
|
+
soup = bs(response, "html.parser")
|
|
149
|
+
rows = soup.select("tbody tr")
|
|
150
|
+
return [_parse_search_row(row) for row in rows]
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# --- Download ---
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _pack_exists(title: str) -> bool:
|
|
157
|
+
return (config.songs_path / title).is_dir()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def download_pack(pack_title: str, url: str) -> None:
|
|
161
|
+
"""Download and extract a pack zip."""
|
|
162
|
+
if _pack_exists(pack_title):
|
|
163
|
+
logger.warning(f"Pack '{pack_title}' already exists, skipping")
|
|
164
|
+
return
|
|
165
|
+
|
|
166
|
+
prefix = config.songs_path
|
|
167
|
+
prefix.mkdir(parents=True, exist_ok=True)
|
|
168
|
+
archive = prefix / f"{pack_title}.zip"
|
|
169
|
+
|
|
170
|
+
with requests.get(url, stream=True) as r:
|
|
171
|
+
with open(archive, "wb") as f:
|
|
172
|
+
shutil.copyfileobj(r.raw, f)
|
|
173
|
+
|
|
174
|
+
if not zf.is_zipfile(archive):
|
|
175
|
+
logger.error(f"Download is not a valid zip: {pack_title} from {url}")
|
|
176
|
+
archive.unlink(missing_ok=True)
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
with zf.ZipFile(archive, "r") as z:
|
|
180
|
+
extracted_name = z.getinfo(z.namelist()[0]).filename.split("/")[0]
|
|
181
|
+
z.extractall(path=prefix)
|
|
182
|
+
|
|
183
|
+
extracted_path = prefix / extracted_name
|
|
184
|
+
destination = prefix / pack_title
|
|
185
|
+
if extracted_path != destination:
|
|
186
|
+
if destination.exists():
|
|
187
|
+
shutil.rmtree(destination)
|
|
188
|
+
shutil.move(str(extracted_path), str(destination))
|
|
189
|
+
|
|
190
|
+
archive.unlink()
|
|
191
|
+
logger.info(f"Downloaded {pack_title}")
|