smfetch 1.3.3__tar.gz → 1.4.0__tar.gz
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-1.3.3 → smfetch-1.4.0}/PKG-INFO +14 -7
- {smfetch-1.3.3 → smfetch-1.4.0}/README.md +12 -6
- {smfetch-1.3.3 → smfetch-1.4.0}/pyproject.toml +2 -1
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/app.py +4 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/smonline.py +119 -15
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/static/app.js +7 -1
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/updates.py +54 -0
- smfetch-1.4.0/tests/test_smonline.py +236 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/test_updates.py +100 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/uv.lock +3 -1
- {smfetch-1.3.3 → smfetch-1.4.0}/.gitignore +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/Makefile +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/__init__.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/config.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/jobs.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/library.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/static/index.html +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/static/style.css +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/smfetch/zenius.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/__init__.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/conftest.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/fixtures/category_1870.html +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/fixtures/latest_official.html +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/fixtures/latest_user.html +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/fixtures/simfile_63939.html +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/fixtures/simfile_70013.html +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/test_library.py +0 -0
- {smfetch-1.3.3 → smfetch-1.4.0}/tests/test_parsing.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: smfetch
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
4
|
Summary: Web interface for downloading simfiles from Zenius and StepManiaOnline
|
|
5
5
|
Author-email: Raeed Ahmed <code@raeed.me>
|
|
6
6
|
Requires-Python: <4,>=3.10
|
|
@@ -8,6 +8,7 @@ Requires-Dist: beautifulsoup4<5,>=4.12.3
|
|
|
8
8
|
Requires-Dist: fastapi>=0.115.0
|
|
9
9
|
Requires-Dist: loguru<0.8,>=0.7.2
|
|
10
10
|
Requires-Dist: requests<3,>=2.31.0
|
|
11
|
+
Requires-Dist: urllib3<3,>=2.0
|
|
11
12
|
Requires-Dist: uvicorn[standard]>=0.30.0
|
|
12
13
|
Description-Content-Type: text/markdown
|
|
13
14
|
|
|
@@ -47,10 +48,15 @@ whole pack for one chart.
|
|
|
47
48
|
fetches the latest revision once. If a chart changes again *while* its
|
|
48
49
|
download is running it stays pending for the next pass, rather than being
|
|
49
50
|
silently marked current.
|
|
50
|
-
- **
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
51
|
+
- **Packs you added yourself.** A pack folder copied into the songs directory is
|
|
52
|
+
picked up on its own — at startup, when you open Installed Packs, and on every
|
|
53
|
+
check — and listed as `local`. Nothing is guessed about where it came from, so
|
|
54
|
+
it stays out of update checking until you link it. A folder with no song
|
|
55
|
+
folders in it yet is left alone, so a copy still in progress is not adopted
|
|
56
|
+
half-finished.
|
|
57
|
+
- **Linking to Zenius.** Any pack without a category can be matched to one by
|
|
58
|
+
name, from the Installed Packs view or a scan. Charts already on disk are
|
|
59
|
+
treated as current, so only changes published after linking are reported.
|
|
54
60
|
- **StepManiaOnline packs too.** The two sites carry many of the same packs, so
|
|
55
61
|
a pack downloaded from StepManiaOnline can be linked to its Zenius
|
|
56
62
|
counterpart and updated from there. Linking records the origin separately, so
|
|
@@ -99,8 +105,9 @@ system light/dark preference and has a manual toggle.
|
|
|
99
105
|
| **Windows** | `%APPDATA%/smfetch/` | `~/Music/StepMania Songs/` | `%LOCALAPPDATA%/smfetch/logs/` |
|
|
100
106
|
|
|
101
107
|
Installed packs and pending updates live in `library.json` inside the config
|
|
102
|
-
directory. Deleting it only loses update history
|
|
103
|
-
|
|
108
|
+
directory. Deleting it only loses update history and your Zenius links — nothing
|
|
109
|
+
on disk is touched, and your packs are picked up again from the songs directory
|
|
110
|
+
on the next start.
|
|
104
111
|
|
|
105
112
|
## Development
|
|
106
113
|
|
|
@@ -34,10 +34,15 @@ whole pack for one chart.
|
|
|
34
34
|
fetches the latest revision once. If a chart changes again *while* its
|
|
35
35
|
download is running it stays pending for the next pass, rather than being
|
|
36
36
|
silently marked current.
|
|
37
|
-
- **
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
- **Packs you added yourself.** A pack folder copied into the songs directory is
|
|
38
|
+
picked up on its own — at startup, when you open Installed Packs, and on every
|
|
39
|
+
check — and listed as `local`. Nothing is guessed about where it came from, so
|
|
40
|
+
it stays out of update checking until you link it. A folder with no song
|
|
41
|
+
folders in it yet is left alone, so a copy still in progress is not adopted
|
|
42
|
+
half-finished.
|
|
43
|
+
- **Linking to Zenius.** Any pack without a category can be matched to one by
|
|
44
|
+
name, from the Installed Packs view or a scan. Charts already on disk are
|
|
45
|
+
treated as current, so only changes published after linking are reported.
|
|
41
46
|
- **StepManiaOnline packs too.** The two sites carry many of the same packs, so
|
|
42
47
|
a pack downloaded from StepManiaOnline can be linked to its Zenius
|
|
43
48
|
counterpart and updated from there. Linking records the origin separately, so
|
|
@@ -86,8 +91,9 @@ system light/dark preference and has a manual toggle.
|
|
|
86
91
|
| **Windows** | `%APPDATA%/smfetch/` | `~/Music/StepMania Songs/` | `%LOCALAPPDATA%/smfetch/logs/` |
|
|
87
92
|
|
|
88
93
|
Installed packs and pending updates live in `library.json` inside the config
|
|
89
|
-
directory. Deleting it only loses update history
|
|
90
|
-
|
|
94
|
+
directory. Deleting it only loses update history and your Zenius links — nothing
|
|
95
|
+
on disk is touched, and your packs are picked up again from the songs directory
|
|
96
|
+
on the next start.
|
|
91
97
|
|
|
92
98
|
## Development
|
|
93
99
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "smfetch"
|
|
3
|
-
version = "1.
|
|
3
|
+
version = "1.4.0"
|
|
4
4
|
description = "Web interface for downloading simfiles from Zenius and StepManiaOnline"
|
|
5
5
|
authors = [{ name = "Raeed Ahmed", email = "code@raeed.me" }]
|
|
6
6
|
requires-python = ">=3.10,<4"
|
|
@@ -8,6 +8,7 @@ readme = "README.md"
|
|
|
8
8
|
dependencies = [
|
|
9
9
|
"beautifulsoup4>=4.12.3,<5",
|
|
10
10
|
"requests>=2.31.0,<3",
|
|
11
|
+
"urllib3>=2.0,<3",
|
|
11
12
|
"loguru>=0.7.2,<0.8",
|
|
12
13
|
"fastapi>=0.115.0",
|
|
13
14
|
"uvicorn[standard]>=0.30.0",
|
|
@@ -103,6 +103,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
|
|
103
103
|
logger.add(str(config.log_file), retention="7 days", rotation="10 MB")
|
|
104
104
|
logger.info(f"smfetch {VERSION} starting up")
|
|
105
105
|
smo.pack_cache.build_async()
|
|
106
|
+
upd.track_local_packs()
|
|
106
107
|
upd.scheduler.start()
|
|
107
108
|
yield
|
|
108
109
|
upd.scheduler.stop()
|
|
@@ -310,6 +311,9 @@ async def smonline_download_packs(body: SmoBatch) -> dict[str, list[str]]:
|
|
|
310
311
|
|
|
311
312
|
@app.get("/api/library")
|
|
312
313
|
async def get_library() -> dict[str, Any]:
|
|
314
|
+
# Opening the view reflects what is on disk now, so a pack copied in a
|
|
315
|
+
# moment ago is listed without waiting for the scheduler's next pass.
|
|
316
|
+
upd.track_local_packs()
|
|
313
317
|
packs = sorted(library.packs, key=lambda p: p.name.lower())
|
|
314
318
|
return {
|
|
315
319
|
"packs": [p.to_dict() for p in packs],
|
|
@@ -7,19 +7,38 @@ import threading
|
|
|
7
7
|
import zipfile as zf
|
|
8
8
|
from dataclasses import dataclass, field
|
|
9
9
|
from datetime import date, datetime
|
|
10
|
+
from pathlib import Path
|
|
10
11
|
from typing import Any, NamedTuple
|
|
11
12
|
|
|
12
13
|
import requests
|
|
14
|
+
import urllib3
|
|
13
15
|
from bs4 import BeautifulSoup as bs
|
|
14
16
|
from bs4 import Tag
|
|
15
17
|
from loguru import logger
|
|
16
18
|
|
|
17
19
|
from smfetch.config import config
|
|
18
20
|
from smfetch.library import library
|
|
21
|
+
from smfetch.zenius import _zip_root
|
|
19
22
|
|
|
20
23
|
BASE = "https://stepmaniaonline.net"
|
|
21
24
|
SEARCH = f"{BASE}/search"
|
|
22
25
|
|
|
26
|
+
TIMEOUT = (10, 120) # (connect, read) seconds
|
|
27
|
+
|
|
28
|
+
#: Resumed attempts are cumulative, so a pack whose connection keeps dropping
|
|
29
|
+
#: still converges. What ends it is attempts that stop gaining ground, not a
|
|
30
|
+
#: budget of tries — a multi-gigabyte pack on a poor line can legitimately need
|
|
31
|
+
#: many. `MAX_ATTEMPTS` is only a backstop against spinning forever.
|
|
32
|
+
MAX_ATTEMPTS = 12
|
|
33
|
+
STALLED_ATTEMPTS = 3
|
|
34
|
+
|
|
35
|
+
#: A dropped transfer that already got this far is resumed with a ranged
|
|
36
|
+
#: request; below it, starting over is cheaper than negotiating a resume.
|
|
37
|
+
RESUME_FLOOR = 50 * 1024 * 1024
|
|
38
|
+
|
|
39
|
+
session = requests.Session()
|
|
40
|
+
session.headers.update({"User-Agent": "smfetch (+https://pypi.org/project/smfetch/)"})
|
|
41
|
+
|
|
23
42
|
|
|
24
43
|
class PackEntry(NamedTuple):
|
|
25
44
|
pack_title: str
|
|
@@ -174,6 +193,102 @@ def _pack_exists(title: str) -> bool:
|
|
|
174
193
|
return (config.songs_path / title).is_dir()
|
|
175
194
|
|
|
176
195
|
|
|
196
|
+
def _stream_to(url: str, archive: Path, resume_from: int = 0) -> tuple[int, int | None]:
|
|
197
|
+
"""Run one transfer attempt into `archive`.
|
|
198
|
+
|
|
199
|
+
Returns the bytes now on disk and the full size the server says the
|
|
200
|
+
archive should be, or `None` when it does not say.
|
|
201
|
+
"""
|
|
202
|
+
headers = {"Range": f"bytes={resume_from}-"} if resume_from else {}
|
|
203
|
+
with session.get(url, stream=True, timeout=TIMEOUT, headers=headers) as r:
|
|
204
|
+
r.raise_for_status()
|
|
205
|
+
# A server free to ignore Range answers 200 with the whole file again;
|
|
206
|
+
# only a 206 means what is already on disk is a prefix worth keeping.
|
|
207
|
+
resuming = bool(resume_from) and r.status_code == 206
|
|
208
|
+
length = r.headers.get("Content-Length")
|
|
209
|
+
expected = int(length) + (resume_from if resuming else 0) if length else None
|
|
210
|
+
with open(archive, "ab" if resuming else "wb") as f:
|
|
211
|
+
shutil.copyfileobj(r.raw, f)
|
|
212
|
+
return archive.stat().st_size, expected
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _download_archive(url: str, archive: Path, label: str) -> bool:
|
|
216
|
+
"""Fetch `url` into `archive`, retrying a transfer that gives out partway.
|
|
217
|
+
|
|
218
|
+
`shutil.copyfileobj` over a raw stream stops silently where the connection
|
|
219
|
+
broke, so a multi-gigabyte pack cut off near the end used to land as a
|
|
220
|
+
truncated file that merely failed `is_zipfile` — indistinguishable from a
|
|
221
|
+
pack that was never downloadable. Each attempt is measured against the
|
|
222
|
+
length the server promised, and one that got a real way in resumes from
|
|
223
|
+
where it stopped rather than paying for the whole pack again.
|
|
224
|
+
|
|
225
|
+
Retrying is driven by progress: an attempt that reached further than any
|
|
226
|
+
before it earns another, so a pack whose connection drops every few hundred
|
|
227
|
+
megabytes still finishes. Attempts that gain nothing are what stop it.
|
|
228
|
+
"""
|
|
229
|
+
on_disk = 0
|
|
230
|
+
furthest = 0
|
|
231
|
+
stalled = 0
|
|
232
|
+
problem = ""
|
|
233
|
+
for attempt in range(1, MAX_ATTEMPTS + 1):
|
|
234
|
+
try:
|
|
235
|
+
on_disk, expected = _stream_to(url, archive, resume_from=on_disk)
|
|
236
|
+
if expected is None or on_disk >= expected:
|
|
237
|
+
return True
|
|
238
|
+
problem = f"got {on_disk:,} of {expected:,} bytes"
|
|
239
|
+
except requests.HTTPError as e:
|
|
240
|
+
# The pack is not being served at all; further attempts would only
|
|
241
|
+
# collect the same error page.
|
|
242
|
+
logger.error(f"Download rejected for {label}: {e}")
|
|
243
|
+
archive.unlink(missing_ok=True)
|
|
244
|
+
return False
|
|
245
|
+
except (requests.RequestException, urllib3.exceptions.HTTPError, OSError) as e:
|
|
246
|
+
# Reading `r.raw` bypasses the wrapping requests does on its own
|
|
247
|
+
# stream helpers, so a broken connection surfaces as urllib3's
|
|
248
|
+
# ProtocolError rather than a requests error.
|
|
249
|
+
on_disk = archive.stat().st_size if archive.exists() else 0
|
|
250
|
+
problem = f"{type(e).__name__}: {e}"
|
|
251
|
+
|
|
252
|
+
if on_disk > furthest:
|
|
253
|
+
furthest, stalled = on_disk, 0
|
|
254
|
+
else:
|
|
255
|
+
stalled += 1
|
|
256
|
+
if stalled >= STALLED_ATTEMPTS or attempt == MAX_ATTEMPTS:
|
|
257
|
+
break
|
|
258
|
+
|
|
259
|
+
if on_disk < RESUME_FLOOR:
|
|
260
|
+
on_disk = 0 # too little to be worth resuming — start over
|
|
261
|
+
logger.warning(
|
|
262
|
+
f"Download for {label} interrupted ({problem}); "
|
|
263
|
+
f"{'resuming from ' + format(on_disk, ',') + ' bytes' if on_disk else 'restarting'} "
|
|
264
|
+
f"[attempt {attempt + 1}]"
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
logger.error(f"Download failed for {label} after {attempt} attempts ({problem})")
|
|
268
|
+
archive.unlink(missing_ok=True)
|
|
269
|
+
return False
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _extract_pack(archive: Path, prefix: Path, pack_title: str) -> None:
|
|
273
|
+
"""Unpack a pack archive into `prefix/pack_title`."""
|
|
274
|
+
destination = prefix / pack_title
|
|
275
|
+
with zf.ZipFile(archive, "r") as z:
|
|
276
|
+
root = _zip_root(z.namelist())
|
|
277
|
+
if root is None:
|
|
278
|
+
# Nothing wraps the songs, so the archive *is* the pack and has to
|
|
279
|
+
# land inside the pack folder rather than strewn across the songs
|
|
280
|
+
# directory beside it.
|
|
281
|
+
z.extractall(path=destination)
|
|
282
|
+
return
|
|
283
|
+
z.extractall(path=prefix)
|
|
284
|
+
|
|
285
|
+
extracted_path = prefix / root
|
|
286
|
+
if extracted_path != destination:
|
|
287
|
+
if destination.exists():
|
|
288
|
+
shutil.rmtree(destination)
|
|
289
|
+
shutil.move(str(extracted_path), str(destination))
|
|
290
|
+
|
|
291
|
+
|
|
177
292
|
def download_pack(pack_title: str, url: str) -> None:
|
|
178
293
|
"""Download and extract a pack zip."""
|
|
179
294
|
if _pack_exists(pack_title):
|
|
@@ -185,25 +300,14 @@ def download_pack(pack_title: str, url: str) -> None:
|
|
|
185
300
|
prefix.mkdir(parents=True, exist_ok=True)
|
|
186
301
|
archive = prefix / f"{pack_title}.zip"
|
|
187
302
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
shutil.copyfileobj(r.raw, f)
|
|
303
|
+
if not _download_archive(url, archive, pack_title):
|
|
304
|
+
raise RuntimeError(f"Could not download '{pack_title}' from {url}")
|
|
191
305
|
|
|
192
306
|
if not zf.is_zipfile(archive):
|
|
193
|
-
logger.error(f"Download is not a valid zip: {pack_title} from {url}")
|
|
194
307
|
archive.unlink(missing_ok=True)
|
|
195
|
-
|
|
308
|
+
raise RuntimeError(f"Download is not a valid zip: '{pack_title}' from {url}")
|
|
196
309
|
|
|
197
|
-
|
|
198
|
-
extracted_name = z.getinfo(z.namelist()[0]).filename.split("/")[0]
|
|
199
|
-
z.extractall(path=prefix)
|
|
200
|
-
|
|
201
|
-
extracted_path = prefix / extracted_name
|
|
202
|
-
destination = prefix / pack_title
|
|
203
|
-
if extracted_path != destination:
|
|
204
|
-
if destination.exists():
|
|
205
|
-
shutil.rmtree(destination)
|
|
206
|
-
shutil.move(str(extracted_path), str(destination))
|
|
310
|
+
_extract_pack(archive, prefix, pack_title)
|
|
207
311
|
|
|
208
312
|
archive.unlink()
|
|
209
313
|
library.record_pack(pack_title, pack_title, source="smonline")
|
|
@@ -483,7 +483,8 @@ views.library = function renderLibrary() {
|
|
|
483
483
|
}));
|
|
484
484
|
} else {
|
|
485
485
|
parts.push(el('p', { class: 'msg' },
|
|
486
|
-
'No packs tracked yet. Download a pack, or
|
|
486
|
+
'No packs tracked yet. Download a pack, or copy one into your songs directory — '
|
|
487
|
+
+ 'smfetch picks those up on its own.'));
|
|
487
488
|
}
|
|
488
489
|
|
|
489
490
|
if (state.scan) {
|
|
@@ -789,6 +790,11 @@ async function downloadZenPacks() {
|
|
|
789
790
|
} catch (e) { toast(e.message, 'bad'); }
|
|
790
791
|
}
|
|
791
792
|
|
|
793
|
+
// --- Zenius bundles ---
|
|
794
|
+
|
|
795
|
+
// Static markup wired once in wire() — registered so navigate() recognises it.
|
|
796
|
+
views['zen-bundles'] = () => {};
|
|
797
|
+
|
|
792
798
|
async function downloadBundle(group) {
|
|
793
799
|
if (!confirm(`Queue every pack in the ${group.toLowerCase()} group?\n\nThis can be a very large download.`)) return;
|
|
794
800
|
try {
|
|
@@ -237,6 +237,12 @@ class UpdateScheduler:
|
|
|
237
237
|
if self._stop.wait(STARTUP_DELAY):
|
|
238
238
|
return
|
|
239
239
|
while not self._stop.is_set():
|
|
240
|
+
# Independent of update checking: a pack added on disk should be
|
|
241
|
+
# picked up even when checks are switched off entirely.
|
|
242
|
+
try:
|
|
243
|
+
track_local_packs()
|
|
244
|
+
except Exception as e: # a scheduler thread must never die
|
|
245
|
+
logger.exception(f"Picking up local packs raised: {e}")
|
|
240
246
|
if config.update_check_enabled:
|
|
241
247
|
try:
|
|
242
248
|
self.run_once()
|
|
@@ -283,6 +289,54 @@ class Suggestion:
|
|
|
283
289
|
return asdict(self)
|
|
284
290
|
|
|
285
291
|
|
|
292
|
+
def _pack_folders(root: Path) -> list[Path]:
|
|
293
|
+
"""Directories under the songs root that could be packs."""
|
|
294
|
+
try:
|
|
295
|
+
entries = sorted(root.iterdir(), key=lambda d: d.name)
|
|
296
|
+
except OSError as e:
|
|
297
|
+
logger.warning(f"Could not read {root}: {e}")
|
|
298
|
+
return []
|
|
299
|
+
return [d for d in entries if d.is_dir() and not d.name.startswith(".") and d.name != "dump"]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def track_local_packs() -> list[str]:
|
|
303
|
+
"""Adopt pack folders that arrived in the songs directory on their own.
|
|
304
|
+
|
|
305
|
+
A pack copied in by hand is as installed as one smfetch downloaded, so it
|
|
306
|
+
is tracked on sight rather than waiting for someone to press Scan. Nothing
|
|
307
|
+
is guessed about where it came from: it is recorded as ``local`` with no
|
|
308
|
+
Zenius category, which keeps it out of update checking until it is linked
|
|
309
|
+
explicitly. Nothing on disk is read beyond the folder listing, and nothing
|
|
310
|
+
is written there at all.
|
|
311
|
+
"""
|
|
312
|
+
root = config.songs_path
|
|
313
|
+
if not root.is_dir():
|
|
314
|
+
return []
|
|
315
|
+
|
|
316
|
+
known = {pack.dir for pack in library.packs}
|
|
317
|
+
adopted: list[str] = []
|
|
318
|
+
for folder in _pack_folders(root):
|
|
319
|
+
if folder.name in known:
|
|
320
|
+
continue
|
|
321
|
+
try:
|
|
322
|
+
has_songs = any(child.is_dir() for child in folder.iterdir())
|
|
323
|
+
except OSError as e:
|
|
324
|
+
logger.warning(f"Could not read {folder}: {e}")
|
|
325
|
+
continue
|
|
326
|
+
if not has_songs:
|
|
327
|
+
# No song folders inside yet — an empty shell, or a copy still in
|
|
328
|
+
# progress. Leave it for a later pass rather than tracking it now.
|
|
329
|
+
continue
|
|
330
|
+
library.record_pack(folder.name, folder.name, source="local")
|
|
331
|
+
adopted.append(folder.name)
|
|
332
|
+
|
|
333
|
+
if adopted:
|
|
334
|
+
logger.info(
|
|
335
|
+
f"Library: picked up {len(adopted)} pack(s) added on disk: {', '.join(adopted)}"
|
|
336
|
+
)
|
|
337
|
+
return adopted
|
|
338
|
+
|
|
339
|
+
|
|
286
340
|
@dataclass
|
|
287
341
|
class LinkablePack:
|
|
288
342
|
"""A pack that could be linked to a Zenius category but is not yet."""
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""StepManiaOnline pack downloads.
|
|
2
|
+
|
|
3
|
+
Pack archives run to gigabytes, and a connection that gives out partway used
|
|
4
|
+
to leave a truncated file that merely failed the zip check — reported as a
|
|
5
|
+
completed job with nothing installed. These cover the retry that replaced it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import zipfile as zf
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import pytest
|
|
15
|
+
import requests
|
|
16
|
+
import urllib3
|
|
17
|
+
|
|
18
|
+
from smfetch import smonline as smo
|
|
19
|
+
from smfetch.config import config
|
|
20
|
+
from smfetch.library import library
|
|
21
|
+
|
|
22
|
+
SONGS = [f"Song {i}" for i in range(12)]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def build_zip(path, root: str | None = "My Pack") -> bytes:
|
|
26
|
+
"""A pack archive, optionally without a folder wrapping the songs."""
|
|
27
|
+
with zf.ZipFile(path, "w") as z:
|
|
28
|
+
for song in SONGS:
|
|
29
|
+
inner = f"{song}/{song}.ssc"
|
|
30
|
+
z.writestr(f"{root}/{inner}" if root else inner, "#TITLE:test;")
|
|
31
|
+
return path.read_bytes()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Raw:
|
|
35
|
+
"""A urllib3 raw stream that can stop short of what it promised."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, body: bytes, cut: int | None = None, silent: bool = False) -> None:
|
|
38
|
+
self.body = body
|
|
39
|
+
self.cut = cut
|
|
40
|
+
self.silent = silent
|
|
41
|
+
self.pos = 0
|
|
42
|
+
|
|
43
|
+
def read(self, size: int = -1) -> bytes:
|
|
44
|
+
if size is None or size < 0:
|
|
45
|
+
size = len(self.body) - self.pos
|
|
46
|
+
if self.cut is not None and self.pos >= self.cut:
|
|
47
|
+
# A server that hangs up cleanly reads as end-of-stream, which is
|
|
48
|
+
# the case `copyfileobj` cannot tell from a finished download.
|
|
49
|
+
if self.silent:
|
|
50
|
+
return b""
|
|
51
|
+
raise urllib3.exceptions.ProtocolError("Connection broken")
|
|
52
|
+
end = min(self.pos + size, len(self.body))
|
|
53
|
+
if self.cut is not None:
|
|
54
|
+
end = min(end, self.cut)
|
|
55
|
+
chunk = self.body[self.pos : end]
|
|
56
|
+
self.pos = end
|
|
57
|
+
return chunk
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Response:
|
|
61
|
+
def __init__(self, status: int, headers: dict[str, str], raw: Raw | None) -> None:
|
|
62
|
+
self.status_code = status
|
|
63
|
+
self.headers = headers
|
|
64
|
+
self.raw = raw
|
|
65
|
+
|
|
66
|
+
def raise_for_status(self) -> None:
|
|
67
|
+
if self.status_code >= 400:
|
|
68
|
+
raise requests.HTTPError(f"{self.status_code} Server Error", response=None)
|
|
69
|
+
|
|
70
|
+
def __enter__(self) -> Response:
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
def __exit__(self, *exc: object) -> bool:
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class FakeSMOnline:
|
|
79
|
+
"""Serves `body`, dropping each attempt after the matching entry in `cuts`."""
|
|
80
|
+
|
|
81
|
+
body: bytes = b""
|
|
82
|
+
cuts: list[int | None] = field(default_factory=list)
|
|
83
|
+
silent: bool = False
|
|
84
|
+
status: int = 200
|
|
85
|
+
offsets: list[int] = field(default_factory=list)
|
|
86
|
+
|
|
87
|
+
def get(self, url: str, **kwargs: Any) -> Response:
|
|
88
|
+
headers: dict[str, str] = kwargs.get("headers") or {}
|
|
89
|
+
rng = headers.get("Range")
|
|
90
|
+
start = int(rng.split("=")[1].split("-")[0]) if rng else 0
|
|
91
|
+
self.offsets.append(start)
|
|
92
|
+
|
|
93
|
+
if self.status >= 400:
|
|
94
|
+
return Response(self.status, {}, None)
|
|
95
|
+
|
|
96
|
+
cut = self.cuts.pop(0) if self.cuts else None
|
|
97
|
+
chunk = self.body[start:]
|
|
98
|
+
return Response(
|
|
99
|
+
206 if rng else 200,
|
|
100
|
+
{"Content-Length": str(len(chunk))},
|
|
101
|
+
Raw(chunk, cut, self.silent),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@pytest.fixture
|
|
106
|
+
def smonline(monkeypatch, tmp_path) -> FakeSMOnline:
|
|
107
|
+
fake = FakeSMOnline(body=build_zip(tmp_path / "pack.zip"))
|
|
108
|
+
monkeypatch.setattr(smo.session, "get", fake.get)
|
|
109
|
+
return fake
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def installed_songs() -> list[str]:
|
|
113
|
+
pack = config.songs_path / "My Pack"
|
|
114
|
+
return sorted(p.name for p in pack.iterdir()) if pack.is_dir() else []
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def strays() -> list[str]:
|
|
118
|
+
return sorted(p.name for p in config.songs_path.iterdir() if p.name != "My Pack")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def test_downloads_and_extracts_a_pack(smonline):
|
|
122
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
123
|
+
|
|
124
|
+
assert installed_songs() == sorted(SONGS)
|
|
125
|
+
assert strays() == []
|
|
126
|
+
assert library.packs[0].name == "My Pack"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_interrupted_download_resumes_where_it_stopped(smonline, monkeypatch):
|
|
130
|
+
monkeypatch.setattr(smo, "RESUME_FLOOR", 1)
|
|
131
|
+
cut = len(smonline.body) // 2
|
|
132
|
+
smonline.cuts = [cut]
|
|
133
|
+
|
|
134
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
135
|
+
|
|
136
|
+
assert smonline.offsets == [0, cut], "second attempt should range from the cut"
|
|
137
|
+
assert installed_songs() == sorted(SONGS)
|
|
138
|
+
assert strays() == []
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_silently_truncated_download_is_caught_and_retried(smonline, monkeypatch):
|
|
142
|
+
"""The original failure: the stream just ends, with no error to catch."""
|
|
143
|
+
monkeypatch.setattr(smo, "RESUME_FLOOR", 1)
|
|
144
|
+
cut = len(smonline.body) // 2
|
|
145
|
+
smonline.cuts = [cut]
|
|
146
|
+
smonline.silent = True
|
|
147
|
+
|
|
148
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
149
|
+
|
|
150
|
+
assert smonline.offsets == [0, cut]
|
|
151
|
+
assert installed_songs() == sorted(SONGS)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_barely_started_download_restarts_instead_of_resuming(smonline, monkeypatch):
|
|
155
|
+
monkeypatch.setattr(smo, "RESUME_FLOOR", 10**9)
|
|
156
|
+
smonline.cuts = [len(smonline.body) // 2]
|
|
157
|
+
|
|
158
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
159
|
+
|
|
160
|
+
assert smonline.offsets == [0, 0], "too little to resume, so start over"
|
|
161
|
+
assert installed_songs() == sorted(SONGS)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def test_a_connection_that_keeps_dropping_still_finishes(smonline, monkeypatch):
|
|
165
|
+
"""Each resumed attempt is cumulative, so slow progress is still progress."""
|
|
166
|
+
monkeypatch.setattr(smo, "RESUME_FLOOR", 1)
|
|
167
|
+
step = len(smonline.body) // 6
|
|
168
|
+
smonline.cuts = [step, step, step, step, step]
|
|
169
|
+
|
|
170
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
171
|
+
|
|
172
|
+
assert len(smonline.offsets) > smo.STALLED_ATTEMPTS, "more tries than a fixed budget"
|
|
173
|
+
assert smonline.offsets == sorted(smonline.offsets), "each attempt starts further in"
|
|
174
|
+
assert installed_songs() == sorted(SONGS)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def test_a_download_that_stops_gaining_ground_gives_up(smonline, monkeypatch):
|
|
178
|
+
monkeypatch.setattr(smo, "RESUME_FLOOR", 1)
|
|
179
|
+
smonline.cuts = [0] * smo.MAX_ATTEMPTS # every attempt dies without a byte
|
|
180
|
+
|
|
181
|
+
with pytest.raises(RuntimeError, match="Could not download"):
|
|
182
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
183
|
+
|
|
184
|
+
assert len(smonline.offsets) == smo.STALLED_ATTEMPTS, "ends before the backstop"
|
|
185
|
+
assert strays() == [], "the partial archive should not be left behind"
|
|
186
|
+
assert library.packs == []
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def test_the_attempt_backstop_is_honoured(smonline, monkeypatch):
|
|
190
|
+
"""Progress every time, but never enough — the cap still stops it."""
|
|
191
|
+
monkeypatch.setattr(smo, "RESUME_FLOOR", 1)
|
|
192
|
+
smonline.cuts = [1] * (smo.MAX_ATTEMPTS + 5)
|
|
193
|
+
|
|
194
|
+
with pytest.raises(RuntimeError, match="Could not download"):
|
|
195
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
196
|
+
|
|
197
|
+
assert len(smonline.offsets) == smo.MAX_ATTEMPTS
|
|
198
|
+
assert strays() == []
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def test_rejected_download_is_not_retried(smonline):
|
|
202
|
+
smonline.status = 503
|
|
203
|
+
|
|
204
|
+
with pytest.raises(RuntimeError, match="Could not download"):
|
|
205
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
206
|
+
|
|
207
|
+
assert smonline.offsets == [0], "an error page will not improve on a retry"
|
|
208
|
+
assert strays() == []
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def test_pack_without_a_wrapping_folder_lands_in_its_own_directory(smonline, tmp_path):
|
|
212
|
+
"""Songs sitting at the top of the archive must not spill into songs/."""
|
|
213
|
+
smonline.body = build_zip(tmp_path / "flat.zip", root=None)
|
|
214
|
+
|
|
215
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
216
|
+
|
|
217
|
+
assert installed_songs() == sorted(SONGS)
|
|
218
|
+
assert strays() == []
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def test_archive_folder_is_renamed_to_the_pack_title(smonline, tmp_path):
|
|
222
|
+
smonline.body = build_zip(tmp_path / "other.zip", root="pack_v2_final")
|
|
223
|
+
|
|
224
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
225
|
+
|
|
226
|
+
assert installed_songs() == sorted(SONGS)
|
|
227
|
+
assert strays() == []
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def test_a_pack_already_on_disk_is_left_alone(smonline):
|
|
231
|
+
(config.songs_path / "My Pack").mkdir(parents=True)
|
|
232
|
+
|
|
233
|
+
smo.download_pack("My Pack", "https://smo.test/pack/1/")
|
|
234
|
+
|
|
235
|
+
assert smonline.offsets == [], "nothing should be fetched"
|
|
236
|
+
assert library.packs[0].name == "My Pack"
|
|
@@ -483,3 +483,103 @@ class TestScheduler:
|
|
|
483
483
|
assert scheduler.is_running
|
|
484
484
|
scheduler.stop()
|
|
485
485
|
assert not scheduler.is_running
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class TestPacksAddedByHand:
|
|
489
|
+
"""Pack folders that arrive in the songs directory without smfetch."""
|
|
490
|
+
|
|
491
|
+
def make_pack(self, songs_dir, name: str, songs: list[str]) -> None:
|
|
492
|
+
for song in songs:
|
|
493
|
+
(songs_dir / name / song).mkdir(parents=True, exist_ok=True)
|
|
494
|
+
|
|
495
|
+
def test_a_folder_copied_in_is_tracked(self, songs_dir):
|
|
496
|
+
self.make_pack(songs_dir, "Handmade Pack", ["Song A", "Song B"])
|
|
497
|
+
|
|
498
|
+
assert upd.track_local_packs() == ["Handmade Pack"]
|
|
499
|
+
|
|
500
|
+
pack = tracked_pack("Handmade Pack")
|
|
501
|
+
assert pack.source == "local"
|
|
502
|
+
assert pack.category_id == "", "nothing is guessed about where it came from"
|
|
503
|
+
assert pack.name == "Handmade Pack"
|
|
504
|
+
|
|
505
|
+
def test_every_folder_already_on_disk_is_picked_up(self, songs_dir):
|
|
506
|
+
for name in ("Alpha", "Beta", "Gamma"):
|
|
507
|
+
self.make_pack(songs_dir, name, ["Song"])
|
|
508
|
+
|
|
509
|
+
assert upd.track_local_packs() == ["Alpha", "Beta", "Gamma"]
|
|
510
|
+
assert sorted(p.dir for p in library.packs) == ["Alpha", "Beta", "Gamma"]
|
|
511
|
+
|
|
512
|
+
def test_it_is_not_checked_for_updates_until_linked(self, songs_dir):
|
|
513
|
+
self.make_pack(songs_dir, "Handmade Pack", ["Song A"])
|
|
514
|
+
upd.track_local_packs()
|
|
515
|
+
|
|
516
|
+
summary = upd.check_updates()
|
|
517
|
+
|
|
518
|
+
assert summary.packs_tracked == 0, "an unlinked pack joins nothing"
|
|
519
|
+
assert library.pending == []
|
|
520
|
+
|
|
521
|
+
def test_the_scan_offers_it_for_linking(self, zenius, songs_dir):
|
|
522
|
+
self.make_pack(songs_dir, "Butterfly Pack", ["Butterfly!"])
|
|
523
|
+
upd.track_local_packs()
|
|
524
|
+
zenius.groups = {"User": [(CAT, "Butterfly Pack")]}
|
|
525
|
+
|
|
526
|
+
result = upd.scan_songs_dir()
|
|
527
|
+
|
|
528
|
+
assert result["untracked"] == [], "it is tracked, just not linked"
|
|
529
|
+
entry = result["unlinked"][0]
|
|
530
|
+
assert entry["dir"] == "Butterfly Pack"
|
|
531
|
+
assert entry["source"] == "local"
|
|
532
|
+
assert entry["suggestions"][0]["category_id"] == CAT
|
|
533
|
+
|
|
534
|
+
def test_linking_it_keeps_the_local_origin(self, zenius, songs_dir):
|
|
535
|
+
self.make_pack(songs_dir, "Butterfly Pack", ["Butterfly!"])
|
|
536
|
+
upd.track_local_packs()
|
|
537
|
+
zenius.category_rows[CAT] = [Row("300", "BUTTERFLY", "SMILE.dk", CAT, "Butterfly Pack")]
|
|
538
|
+
|
|
539
|
+
upd.adopt("Butterfly Pack", CAT)
|
|
540
|
+
|
|
541
|
+
pack = tracked_pack("Butterfly Pack")
|
|
542
|
+
assert pack.source == "local", "it did not suddenly come from Zenius"
|
|
543
|
+
assert pack.category_id == CAT
|
|
544
|
+
|
|
545
|
+
def test_a_downloaded_pack_is_not_relabelled_local(self, zenius, songs_dir):
|
|
546
|
+
install_pack(zenius, CAT, "Test Pack", [Row("1", "Song A")])
|
|
547
|
+
|
|
548
|
+
assert upd.track_local_packs() == [], "already tracked"
|
|
549
|
+
assert tracked_pack("Test Pack").source == "zenius"
|
|
550
|
+
|
|
551
|
+
def test_an_empty_folder_is_left_alone(self, songs_dir):
|
|
552
|
+
(songs_dir / "Not A Pack").mkdir(parents=True)
|
|
553
|
+
|
|
554
|
+
assert upd.track_local_packs() == [], "a copy may still be in progress"
|
|
555
|
+
assert library.packs == []
|
|
556
|
+
|
|
557
|
+
def test_the_dump_folder_and_dotfiles_are_skipped(self, songs_dir):
|
|
558
|
+
self.make_pack(songs_dir, "dump", ["Loose Song"])
|
|
559
|
+
self.make_pack(songs_dir, ".hidden", ["Song"])
|
|
560
|
+
self.make_pack(songs_dir, "Real Pack", ["Song"])
|
|
561
|
+
|
|
562
|
+
assert upd.track_local_packs() == ["Real Pack"]
|
|
563
|
+
|
|
564
|
+
def test_picking_up_twice_does_not_duplicate_or_reset(self, songs_dir):
|
|
565
|
+
self.make_pack(songs_dir, "Handmade Pack", ["Song A"])
|
|
566
|
+
upd.track_local_packs()
|
|
567
|
+
installed_at = tracked_pack("Handmade Pack").installed_at
|
|
568
|
+
|
|
569
|
+
assert upd.track_local_packs() == []
|
|
570
|
+
assert len(library.packs) == 1
|
|
571
|
+
assert tracked_pack("Handmade Pack").installed_at == installed_at
|
|
572
|
+
|
|
573
|
+
def test_untracking_survives_until_the_folder_is_removed(self, songs_dir):
|
|
574
|
+
"""Untrack is a request about the library, but the folder is still there."""
|
|
575
|
+
self.make_pack(songs_dir, "Handmade Pack", ["Song A"])
|
|
576
|
+
upd.track_local_packs()
|
|
577
|
+
|
|
578
|
+
library.untrack_pack("Handmade Pack")
|
|
579
|
+
|
|
580
|
+
assert upd.track_local_packs() == ["Handmade Pack"], "still on disk, so still picked up"
|
|
581
|
+
|
|
582
|
+
def test_a_missing_songs_directory_is_not_an_error(self, songs_dir, monkeypatch):
|
|
583
|
+
monkeypatch.setattr(config, "songs_dir", str(songs_dir / "nope"))
|
|
584
|
+
|
|
585
|
+
assert upd.track_local_packs() == []
|
|
@@ -570,13 +570,14 @@ wheels = [
|
|
|
570
570
|
|
|
571
571
|
[[package]]
|
|
572
572
|
name = "smfetch"
|
|
573
|
-
version = "1.
|
|
573
|
+
version = "1.4.0"
|
|
574
574
|
source = { editable = "." }
|
|
575
575
|
dependencies = [
|
|
576
576
|
{ name = "beautifulsoup4" },
|
|
577
577
|
{ name = "fastapi" },
|
|
578
578
|
{ name = "loguru" },
|
|
579
579
|
{ name = "requests" },
|
|
580
|
+
{ name = "urllib3" },
|
|
580
581
|
{ name = "uvicorn", extra = ["standard"] },
|
|
581
582
|
]
|
|
582
583
|
|
|
@@ -595,6 +596,7 @@ requires-dist = [
|
|
|
595
596
|
{ name = "fastapi", specifier = ">=0.115.0" },
|
|
596
597
|
{ name = "loguru", specifier = ">=0.7.2,<0.8" },
|
|
597
598
|
{ name = "requests", specifier = ">=2.31.0,<3" },
|
|
599
|
+
{ name = "urllib3", specifier = ">=2.0,<3" },
|
|
598
600
|
{ name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" },
|
|
599
601
|
]
|
|
600
602
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|