smfetch 1.3.4__tar.gz → 1.4.1__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.4 → smfetch-1.4.1}/PKG-INFO +14 -7
- {smfetch-1.3.4 → smfetch-1.4.1}/README.md +12 -6
- {smfetch-1.3.4 → smfetch-1.4.1}/pyproject.toml +2 -1
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/app.py +4 -0
- smfetch-1.4.1/smfetch/smonline.py +425 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/static/app.js +2 -1
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/updates.py +54 -0
- smfetch-1.4.1/tests/test_smonline.py +412 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/test_updates.py +100 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/uv.lock +3 -1
- smfetch-1.3.4/smfetch/smonline.py +0 -210
- {smfetch-1.3.4 → smfetch-1.4.1}/.gitignore +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/Makefile +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/__init__.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/config.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/jobs.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/library.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/static/index.html +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/static/style.css +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/smfetch/zenius.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/__init__.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/conftest.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/fixtures/category_1870.html +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/fixtures/latest_official.html +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/fixtures/latest_user.html +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/fixtures/simfile_63939.html +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/fixtures/simfile_70013.html +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/tests/test_library.py +0 -0
- {smfetch-1.3.4 → smfetch-1.4.1}/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.1
|
|
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.1"
|
|
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],
|
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
"""StepManiaOnline scraping and download logic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import zipfile as zf
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import date, datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, NamedTuple
|
|
13
|
+
|
|
14
|
+
import requests
|
|
15
|
+
import urllib3
|
|
16
|
+
from bs4 import BeautifulSoup as bs
|
|
17
|
+
from bs4 import Tag
|
|
18
|
+
from loguru import logger
|
|
19
|
+
|
|
20
|
+
from smfetch.config import config
|
|
21
|
+
from smfetch.library import library
|
|
22
|
+
from smfetch.zenius import _zip_root
|
|
23
|
+
|
|
24
|
+
BASE = "https://stepmaniaonline.net"
|
|
25
|
+
SEARCH = f"{BASE}/search"
|
|
26
|
+
|
|
27
|
+
TIMEOUT = (10, 120) # (connect, read) seconds
|
|
28
|
+
|
|
29
|
+
#: Resumed attempts are cumulative, so a pack whose connection keeps dropping
|
|
30
|
+
#: still converges. What ends it is attempts that stop gaining ground, not a
|
|
31
|
+
#: budget of tries, and the backstop against spinning forever is scaled to the
|
|
32
|
+
#: pack rather than fixed: `Content-Length` gives the exact size on the first
|
|
33
|
+
#: response, so a 15 GB pack is allowed the tries it needs while a 15 MB one is
|
|
34
|
+
#: not allowed to churn. `MIN_PROGRESS` is the least headway worth reconnecting
|
|
35
|
+
#: for — a property of the line, not of the catalogue, so it does not go stale
|
|
36
|
+
#: as packs get bigger. Only transfers are counted against it; a refused
|
|
37
|
+
#: request moves no bytes and is bounded separately.
|
|
38
|
+
MIN_ATTEMPTS = 12
|
|
39
|
+
MIN_PROGRESS = 256 * 1024 * 1024
|
|
40
|
+
STALLED_ATTEMPTS = 3
|
|
41
|
+
|
|
42
|
+
#: A dropped transfer that already got this far is resumed with a ranged
|
|
43
|
+
#: request; below it, starting over is cheaper than negotiating a resume.
|
|
44
|
+
RESUME_FLOOR = 50 * 1024 * 1024
|
|
45
|
+
|
|
46
|
+
#: Statuses that mean "not now" rather than "not ever". Packs are served from
|
|
47
|
+
#: behind a CDN, so a 504 is it failing to reach the origin rather than a
|
|
48
|
+
#: verdict on the pack. The rest are the usual transient refusals.
|
|
49
|
+
RETRY_STATUSES = frozenset({408, 425, 429, 500, 502, 503, 504})
|
|
50
|
+
|
|
51
|
+
#: An origin that is unreachable or overloaded can stay that way for several
|
|
52
|
+
#: minutes, and a refusal costs no bandwidth to repeat, so refusals are given a
|
|
53
|
+
#: budget of their own — spending the transfer budget on them would leave a
|
|
54
|
+
#: large pack with too few tries left to actually arrive.
|
|
55
|
+
MAX_REFUSALS = 6
|
|
56
|
+
|
|
57
|
+
#: How long to wait out a refusal, doubled for each one. A server that just
|
|
58
|
+
#: said it is busy will say it again if asked straight away, and a dropped
|
|
59
|
+
#: connection is not made more likely by the pause.
|
|
60
|
+
RETRY_WAIT = 15
|
|
61
|
+
MAX_RETRY_WAIT = 300
|
|
62
|
+
|
|
63
|
+
session = requests.Session()
|
|
64
|
+
session.headers.update({"User-Agent": "smfetch (+https://pypi.org/project/smfetch/)"})
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class PackEntry(NamedTuple):
|
|
68
|
+
pack_title: str
|
|
69
|
+
size: str
|
|
70
|
+
songs: int
|
|
71
|
+
created: date
|
|
72
|
+
download: str
|
|
73
|
+
idx: int
|
|
74
|
+
|
|
75
|
+
def to_dict(self) -> dict[str, Any]:
|
|
76
|
+
return {
|
|
77
|
+
"pack_title": self.pack_title,
|
|
78
|
+
"size": self.size,
|
|
79
|
+
"songs": self.songs,
|
|
80
|
+
"created": self.created.isoformat(),
|
|
81
|
+
"download": self.download,
|
|
82
|
+
"idx": self.idx,
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class SongEntry(NamedTuple):
|
|
87
|
+
song_title: str
|
|
88
|
+
artist: str
|
|
89
|
+
pack_title: str
|
|
90
|
+
download: str
|
|
91
|
+
idx: int
|
|
92
|
+
|
|
93
|
+
def to_dict(self) -> dict[str, Any]:
|
|
94
|
+
return {
|
|
95
|
+
"song_title": self.song_title,
|
|
96
|
+
"artist": self.artist,
|
|
97
|
+
"pack_title": self.pack_title,
|
|
98
|
+
"download": self.download,
|
|
99
|
+
"idx": self.idx,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _parse_pack_row(cells: list[str]) -> PackEntry:
|
|
104
|
+
title = bs(cells[1], "html.parser").find("a").text # type: ignore[union-attr]
|
|
105
|
+
size = bs(cells[2], "html.parser").get_text(strip=True).replace("\xa0", " ")
|
|
106
|
+
songs = int(bs(cells[3], "html.parser").get_text(strip=True))
|
|
107
|
+
created = datetime.strptime(bs(cells[5], "html.parser").get_text(strip=True), "%Y-%m-%d").date()
|
|
108
|
+
href = bs(cells[6], "html.parser").find("a").get("href") # type: ignore[union-attr]
|
|
109
|
+
download = f"{BASE}{href}"
|
|
110
|
+
idx = int(download.split("/")[-2])
|
|
111
|
+
return PackEntry(title, size, songs, created, download, idx)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _parse_search_row(row: Tag) -> SongEntry:
|
|
115
|
+
tags = row.select("td")
|
|
116
|
+
title = tags[1].text
|
|
117
|
+
artist = tags[2].text
|
|
118
|
+
pack = tags[3].text
|
|
119
|
+
download = f"{BASE}/download{tags[3].find('a').get('href')}/" # type: ignore[union-attr]
|
|
120
|
+
idx = int(download.split("/")[-2])
|
|
121
|
+
return SongEntry(title, artist, pack, download, idx)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# --- Pack cache ---
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class PackCache:
|
|
129
|
+
_entries: list[PackEntry] = field(default_factory=list)
|
|
130
|
+
_lock: threading.Lock = field(default_factory=threading.Lock)
|
|
131
|
+
_building: bool = False
|
|
132
|
+
_built: bool = False
|
|
133
|
+
|
|
134
|
+
def build(self) -> None:
|
|
135
|
+
"""Fetch all packs from the site."""
|
|
136
|
+
with self._lock:
|
|
137
|
+
if self._building:
|
|
138
|
+
return
|
|
139
|
+
self._building = True
|
|
140
|
+
|
|
141
|
+
try:
|
|
142
|
+
logger.info("Building SMOnline pack cache...")
|
|
143
|
+
entries: list[PackEntry] = []
|
|
144
|
+
page_size = 500
|
|
145
|
+
start = 0
|
|
146
|
+
while True:
|
|
147
|
+
params = {
|
|
148
|
+
"draw": 1,
|
|
149
|
+
"start": start,
|
|
150
|
+
"length": page_size,
|
|
151
|
+
"order[0][column]": 1,
|
|
152
|
+
"order[0][dir]": "asc",
|
|
153
|
+
}
|
|
154
|
+
data = requests.get(f"{BASE}/api/packs/datatables", params=params).json()
|
|
155
|
+
rows = data.get("data") or []
|
|
156
|
+
if not rows:
|
|
157
|
+
break
|
|
158
|
+
entries.extend(_parse_pack_row(row) for row in rows)
|
|
159
|
+
start += page_size
|
|
160
|
+
if start >= data.get("recordsTotal", 0):
|
|
161
|
+
break
|
|
162
|
+
with self._lock:
|
|
163
|
+
self._entries = entries
|
|
164
|
+
self._built = True
|
|
165
|
+
logger.info(f"Pack cache built: {len(entries)} packs")
|
|
166
|
+
finally:
|
|
167
|
+
with self._lock:
|
|
168
|
+
self._building = False
|
|
169
|
+
|
|
170
|
+
def build_async(self) -> None:
|
|
171
|
+
"""Start cache build in background thread."""
|
|
172
|
+
thread = threading.Thread(target=self.build, daemon=True)
|
|
173
|
+
thread.start()
|
|
174
|
+
|
|
175
|
+
@property
|
|
176
|
+
def is_ready(self) -> bool:
|
|
177
|
+
with self._lock:
|
|
178
|
+
return self._built
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def is_building(self) -> bool:
|
|
182
|
+
with self._lock:
|
|
183
|
+
return self._building
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def entries(self) -> list[PackEntry]:
|
|
187
|
+
with self._lock:
|
|
188
|
+
return list(self._entries)
|
|
189
|
+
|
|
190
|
+
def refresh(self) -> None:
|
|
191
|
+
"""Force rebuild the cache."""
|
|
192
|
+
with self._lock:
|
|
193
|
+
self._built = False
|
|
194
|
+
self._entries = []
|
|
195
|
+
self.build()
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
pack_cache = PackCache()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# --- Search ---
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def search_songs(category: str, query: str) -> list[SongEntry]:
|
|
205
|
+
"""Search for songs by title or artist on SMOnline."""
|
|
206
|
+
url = f"{SEARCH}/{category}/{query}"
|
|
207
|
+
response = requests.get(url).text
|
|
208
|
+
soup = bs(response, "html.parser")
|
|
209
|
+
rows = soup.select("tbody tr")
|
|
210
|
+
return [_parse_search_row(row) for row in rows]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# --- Download ---
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _pack_exists(title: str) -> bool:
|
|
217
|
+
return (config.songs_path / title).is_dir()
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class Transfer(NamedTuple):
|
|
221
|
+
"""What one attempt left on disk, and what stopped it if anything did."""
|
|
222
|
+
|
|
223
|
+
on_disk: int
|
|
224
|
+
#: The full size the server says the archive should be, or `None` when it
|
|
225
|
+
#: does not say.
|
|
226
|
+
expected: int | None
|
|
227
|
+
broke: Exception | None
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _stream_to(url: str, archive: Path, resume_from: int = 0) -> Transfer:
|
|
231
|
+
"""Run one transfer attempt into `archive`.
|
|
232
|
+
|
|
233
|
+
A connection that gives out partway is reported rather than raised. The
|
|
234
|
+
length comes from the response headers, so it is known as soon as the
|
|
235
|
+
server answers and stays known however badly the body then goes — which is
|
|
236
|
+
what lets a half-transferred pack still say how much patience it deserves.
|
|
237
|
+
"""
|
|
238
|
+
headers = {"Range": f"bytes={resume_from}-"} if resume_from else {}
|
|
239
|
+
broke: Exception | None = None
|
|
240
|
+
with session.get(url, stream=True, timeout=TIMEOUT, headers=headers) as r:
|
|
241
|
+
r.raise_for_status()
|
|
242
|
+
# A server free to ignore Range answers 200 with the whole file again;
|
|
243
|
+
# only a 206 means what is already on disk is a prefix worth keeping.
|
|
244
|
+
resuming = bool(resume_from) and r.status_code == 206
|
|
245
|
+
length = r.headers.get("Content-Length")
|
|
246
|
+
expected = int(length) + (resume_from if resuming else 0) if length else None
|
|
247
|
+
try:
|
|
248
|
+
with open(archive, "ab" if resuming else "wb") as f:
|
|
249
|
+
shutil.copyfileobj(r.raw, f)
|
|
250
|
+
except (requests.RequestException, urllib3.exceptions.HTTPError, OSError) as e:
|
|
251
|
+
# Reading `r.raw` bypasses the wrapping requests does on its own
|
|
252
|
+
# stream helpers, so a broken connection surfaces as urllib3's
|
|
253
|
+
# ProtocolError rather than a requests error.
|
|
254
|
+
broke = e
|
|
255
|
+
return Transfer(archive.stat().st_size if archive.exists() else 0, expected, broke)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _status_of(error: requests.HTTPError) -> int | None:
|
|
259
|
+
"""The status the server answered with, if the error carries a response."""
|
|
260
|
+
return error.response.status_code if error.response is not None else None
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _rejected_range_length(error: requests.HTTPError) -> int | None:
|
|
264
|
+
"""The archive's real length, from a 416's `Content-Range: bytes */<total>`.
|
|
265
|
+
|
|
266
|
+
A server turning down a range is expected to say what it does hold, which
|
|
267
|
+
is the only way to tell an archive that is already complete from one that
|
|
268
|
+
no longer matches the pack being served. `None` when it did not say.
|
|
269
|
+
"""
|
|
270
|
+
if error.response is None:
|
|
271
|
+
return None
|
|
272
|
+
_, _, total = (error.response.headers.get("Content-Range") or "").rpartition("/")
|
|
273
|
+
return int(total) if total.isdigit() else None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _download_archive(url: str, archive: Path, label: str) -> bool:
|
|
277
|
+
"""Fetch `url` into `archive`, retrying a transfer that gives out partway.
|
|
278
|
+
|
|
279
|
+
`shutil.copyfileobj` over a raw stream stops silently where the connection
|
|
280
|
+
broke, so a multi-gigabyte pack cut off near the end used to land as a
|
|
281
|
+
truncated file that merely failed `is_zipfile` — indistinguishable from a
|
|
282
|
+
pack that was never downloadable. Each attempt is measured against the
|
|
283
|
+
length the server promised, and one that got a real way in resumes from
|
|
284
|
+
where it stopped rather than paying for the whole pack again.
|
|
285
|
+
|
|
286
|
+
Retrying is driven by progress: an attempt that reached further than any
|
|
287
|
+
before it earns another, so a pack whose connection drops every few hundred
|
|
288
|
+
megabytes still finishes. Attempts that gain nothing are what stop it.
|
|
289
|
+
|
|
290
|
+
A server that refuses the request outright is only worth asking again when
|
|
291
|
+
the refusal reads as temporary, and then only after waiting it out. Those
|
|
292
|
+
refusals are counted apart from the transfers, since they move no bytes.
|
|
293
|
+
"""
|
|
294
|
+
on_disk = 0
|
|
295
|
+
furthest = 0
|
|
296
|
+
stalled = 0
|
|
297
|
+
transfers = 0
|
|
298
|
+
refusals = 0
|
|
299
|
+
allowance = MIN_ATTEMPTS
|
|
300
|
+
problem = ""
|
|
301
|
+
while True:
|
|
302
|
+
refused = False
|
|
303
|
+
try:
|
|
304
|
+
attempt = _stream_to(url, archive, resume_from=on_disk)
|
|
305
|
+
except requests.HTTPError as e:
|
|
306
|
+
status = _status_of(e)
|
|
307
|
+
# Nothing is ever written on a refusal — `raise_for_status` fires
|
|
308
|
+
# before the file is opened — so an earlier attempt's bytes survive.
|
|
309
|
+
on_disk = archive.stat().st_size if archive.exists() else 0
|
|
310
|
+
if status == 416:
|
|
311
|
+
# The resume point sits at or past the end of the archive the
|
|
312
|
+
# server holds. Either the last attempt did transfer the lot and
|
|
313
|
+
# only its trailing read failed, or the pack has changed and
|
|
314
|
+
# what is on disk belongs to a file that is no longer served.
|
|
315
|
+
if _rejected_range_length(e) == on_disk:
|
|
316
|
+
logger.info(f"Download for {label} was already complete ({on_disk:,} bytes)")
|
|
317
|
+
return True
|
|
318
|
+
# Nothing on disk is worth resuming, so the next attempt is a
|
|
319
|
+
# fresh download and earlier progress is no longer comparable.
|
|
320
|
+
on_disk = furthest = 0
|
|
321
|
+
problem = str(e)
|
|
322
|
+
elif status in RETRY_STATUSES:
|
|
323
|
+
refused = True
|
|
324
|
+
problem = str(e)
|
|
325
|
+
else:
|
|
326
|
+
# The pack is not being served at all; further attempts would
|
|
327
|
+
# only collect the same error page.
|
|
328
|
+
logger.error(f"Download rejected for {label}: {e}")
|
|
329
|
+
archive.unlink(missing_ok=True)
|
|
330
|
+
return False
|
|
331
|
+
except (requests.RequestException, urllib3.exceptions.HTTPError, OSError) as e:
|
|
332
|
+
# The request never got far enough to answer at all.
|
|
333
|
+
on_disk = archive.stat().st_size if archive.exists() else 0
|
|
334
|
+
problem = f"{type(e).__name__}: {e}"
|
|
335
|
+
else:
|
|
336
|
+
on_disk = attempt.on_disk
|
|
337
|
+
if attempt.expected is not None:
|
|
338
|
+
# The pack's own length is what says how many tries it is
|
|
339
|
+
# worth, so it is read even from an attempt that then broke.
|
|
340
|
+
allowance = max(MIN_ATTEMPTS, -(-attempt.expected // MIN_PROGRESS))
|
|
341
|
+
if on_disk >= attempt.expected:
|
|
342
|
+
# Every byte arrived; a read that failed after the last of
|
|
343
|
+
# them says nothing about the archive.
|
|
344
|
+
return True
|
|
345
|
+
problem = f"got {on_disk:,} of {attempt.expected:,} bytes"
|
|
346
|
+
if attempt.broke is not None:
|
|
347
|
+
problem = f"{type(attempt.broke).__name__}: {attempt.broke}"
|
|
348
|
+
elif attempt.expected is None:
|
|
349
|
+
if zf.is_zipfile(archive):
|
|
350
|
+
# Nothing promised a length, so the archive's own trailer
|
|
351
|
+
# is the only thing that says the stream ran to the end
|
|
352
|
+
# rather than stopping somewhere convincing.
|
|
353
|
+
return True
|
|
354
|
+
problem = f"got {on_disk:,} bytes, ending mid-archive"
|
|
355
|
+
|
|
356
|
+
if refused:
|
|
357
|
+
refusals += 1
|
|
358
|
+
else:
|
|
359
|
+
transfers += 1
|
|
360
|
+
if on_disk > furthest:
|
|
361
|
+
furthest, stalled = on_disk, 0
|
|
362
|
+
else:
|
|
363
|
+
stalled += 1
|
|
364
|
+
if stalled >= STALLED_ATTEMPTS or transfers >= allowance or refusals >= MAX_REFUSALS:
|
|
365
|
+
break
|
|
366
|
+
|
|
367
|
+
pause = min(RETRY_WAIT * 2 ** (refusals - 1), MAX_RETRY_WAIT) if refused else 0
|
|
368
|
+
if on_disk < RESUME_FLOOR:
|
|
369
|
+
on_disk = 0 # too little to be worth resuming — start over
|
|
370
|
+
picking_up = f"resuming from {on_disk:,} bytes" if on_disk else "restarting"
|
|
371
|
+
logger.warning(
|
|
372
|
+
f"Download for {label} interrupted ({problem}); {picking_up}"
|
|
373
|
+
f"{f' in {pause}s' if pause else ''} [attempt {transfers + refusals + 1}]"
|
|
374
|
+
)
|
|
375
|
+
if pause:
|
|
376
|
+
time.sleep(pause)
|
|
377
|
+
|
|
378
|
+
logger.error(f"Download failed for {label} after {transfers + refusals} attempts ({problem})")
|
|
379
|
+
archive.unlink(missing_ok=True)
|
|
380
|
+
return False
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _extract_pack(archive: Path, prefix: Path, pack_title: str) -> None:
|
|
384
|
+
"""Unpack a pack archive into `prefix/pack_title`."""
|
|
385
|
+
destination = prefix / pack_title
|
|
386
|
+
with zf.ZipFile(archive, "r") as z:
|
|
387
|
+
root = _zip_root(z.namelist())
|
|
388
|
+
if root is None:
|
|
389
|
+
# Nothing wraps the songs, so the archive *is* the pack and has to
|
|
390
|
+
# land inside the pack folder rather than strewn across the songs
|
|
391
|
+
# directory beside it.
|
|
392
|
+
z.extractall(path=destination)
|
|
393
|
+
return
|
|
394
|
+
z.extractall(path=prefix)
|
|
395
|
+
|
|
396
|
+
extracted_path = prefix / root
|
|
397
|
+
if extracted_path != destination:
|
|
398
|
+
if destination.exists():
|
|
399
|
+
shutil.rmtree(destination)
|
|
400
|
+
shutil.move(str(extracted_path), str(destination))
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def download_pack(pack_title: str, url: str) -> None:
|
|
404
|
+
"""Download and extract a pack zip."""
|
|
405
|
+
if _pack_exists(pack_title):
|
|
406
|
+
logger.warning(f"Pack '{pack_title}' already exists, skipping")
|
|
407
|
+
library.record_pack(pack_title, pack_title, source="smonline")
|
|
408
|
+
return
|
|
409
|
+
|
|
410
|
+
prefix = config.songs_path
|
|
411
|
+
prefix.mkdir(parents=True, exist_ok=True)
|
|
412
|
+
archive = prefix / f"{pack_title}.zip"
|
|
413
|
+
|
|
414
|
+
if not _download_archive(url, archive, pack_title):
|
|
415
|
+
raise RuntimeError(f"Could not download '{pack_title}' from {url}")
|
|
416
|
+
|
|
417
|
+
if not zf.is_zipfile(archive):
|
|
418
|
+
archive.unlink(missing_ok=True)
|
|
419
|
+
raise RuntimeError(f"Download is not a valid zip: '{pack_title}' from {url}")
|
|
420
|
+
|
|
421
|
+
_extract_pack(archive, prefix, pack_title)
|
|
422
|
+
|
|
423
|
+
archive.unlink()
|
|
424
|
+
library.record_pack(pack_title, pack_title, source="smonline")
|
|
425
|
+
logger.info(f"Downloaded {pack_title}")
|
|
@@ -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) {
|
|
@@ -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."""
|