Coverage for downtify/slskd_provider.py: 77%

1110 statements  

« prev     ^ index     » next       coverage.py v7.17.4, created at 2026-11-21 22:18 +0000

1"""slskd provider integration for track search and download handoff.""" 

2 

3from __future__ import annotations 

4 

5import hashlib 

6import os 

7import re 

8import threading 

9import time 

10import unicodedata 

11from collections import OrderedDict 

12from pathlib import Path 

13from typing import Any, Callable, Optional 

14from urllib.parse import quote 

15 

16import httpx 

17from loguru import logger 

18 

19from .library_metadata import read_audio_metadata 

20from .track_tag_match import ( 

21 MIX_VARIANT_REMOTE_SKIP_KEYWORDS, 

22 duration_tolerances_from_settings, 

23 media_duration_matches_mix_variant, 

24 media_duration_matches_song, 

25 remote_text_unacceptable, 

26 snapshot_spotify_metadata, 

27 spotify_file_tag_mismatch_label, 

28 strip_mix_suffix, 

29 verify_downloaded_file_matches_spotify, 

30) 

31from .track_tag_match import fold_accents as _fold_accents 

32from .track_tag_match import plain_name as _plain_name 

33 

34ProgressCallback = Callable[[float, str], None] 

35 

36_SLSKD_SEM: Optional[threading.Semaphore] = None 

37_SLSKD_SEM_LIMIT = 0 

38 

39 

40def _slskd_parallel_limit(settings: dict[str, Any]) -> int: 

41 return _int_setting( 

42 settings, 

43 'max_parallel_downloads', 

44 3, 

45 minimum=1, 

46 maximum=8, 

47 ) 

48 

49 

50def reset_slskd_parallelism(settings: dict[str, Any]) -> None: 

51 """Apply a new parallel limit after settings change (call on save).""" 

52 global _SLSKD_SEM, _SLSKD_SEM_LIMIT 

53 limit = _slskd_parallel_limit(settings) 

54 _SLSKD_SEM = threading.Semaphore(limit) 

55 _SLSKD_SEM_LIMIT = limit 

56 

57 

58def _slskd_semaphore(settings: dict[str, Any]) -> threading.Semaphore: 

59 """Match Downtify parallel download setting; do not serialize all slskd work.""" 

60 limit = _slskd_parallel_limit(settings) 

61 if _SLSKD_SEM is None or _SLSKD_SEM_LIMIT != limit: 

62 reset_slskd_parallelism(settings) 

63 return _SLSKD_SEM 

64 

65 

66_DEFAULT_DOWNLOAD_TIMEOUT_SECONDS = 600 

67_DEFAULT_QUEUED_TIMEOUT_SECONDS = 180 

68_TRANSFERS_LOCK = threading.Lock() 

69_TRANSFERS_CACHE: OrderedDict[ 

70 tuple[str, bytes], tuple[float, list[dict[str, Any]]] 

71] = OrderedDict() 

72_TRANSFERS_CACHE_LIMIT = 32 

73 

74 

75def _poll_env(name: str, default: int, minimum: int, maximum: int) -> int: 

76 return _int_setting( 

77 {name: os.getenv(name)}, 

78 name, 

79 default, 

80 minimum=minimum, 

81 maximum=maximum, 

82 ) 

83 

84 

85def _poll_sleep( 

86 seconds: float, cancel_check: Optional[Callable[[], None]] 

87) -> None: 

88 """Keep cancellation responsive without extra HTTP or filesystem polls.""" 

89 if cancel_check is None: 

90 time.sleep(seconds) 

91 return 

92 remaining = seconds 

93 while remaining > 0: 

94 cancel_check() 

95 step = min(1.0, remaining) 

96 time.sleep(step) 

97 remaining -= step 

98 

99 

100class _PollSchedule: 

101 """Bound expensive polls while retaining the original wait budget.""" 

102 

103 def __init__(self, settings: dict[str, Any]) -> None: 

104 self.interval = _poll_env( 

105 'DOWNTIFY_POLL_INTERVAL', 

106 _int_setting( 

107 settings, 'poll_interval_seconds', 5, minimum=1, maximum=30 

108 ), 

109 1, 

110 30, 

111 ) 

112 self.idle_interval = _poll_env( 

113 'DOWNTIFY_POLL_IDLE_INTERVAL', 60, 1, 60 

114 ) 

115 self.deep_scan_every = _poll_env( 

116 'DOWNTIFY_POLL_DEEP_SCAN_EVERY', 12, 1, 300 

117 ) 

118 self.attempts = _int_setting( 

119 settings, 'poll_max_attempts', 60, minimum=1, maximum=300 

120 ) 

121 self.started = time.monotonic() 

122 self.remaining_sleep = float(self.attempts * self.interval) 

123 self.last_deep_scan = self.started - 60 

124 

125 def should_scan( 

126 self, attempt: int, transfer: Optional[dict[str, Any]] 

127 ) -> bool: 

128 now = time.monotonic() 

129 scan = ( 

130 attempt % self.deep_scan_every == 0 

131 or bool(transfer) 

132 or now - self.last_deep_scan >= 60 

133 ) 

134 if scan: 

135 self.last_deep_scan = now 

136 return scan 

137 

138 def sleep( 

139 self, 

140 transfer: Optional[dict[str, Any]], 

141 last_progress: float, 

142 queued_timeout: int, 

143 deadline: Optional[float], 

144 cancel_check: Optional[Callable[[], None]], 

145 ) -> None: 

146 now = time.monotonic() 

147 timeout_at = ( 

148 last_progress if transfer else self.started 

149 ) + queued_timeout 

150 seconds = min( 

151 self.interval if transfer else self.idle_interval, 

152 max(1.0, timeout_at - now), 

153 self.remaining_sleep, 

154 ) 

155 if deadline is not None: 

156 seconds = min(seconds, max(0.0, deadline - now)) 

157 _poll_sleep(seconds, cancel_check) 

158 self.remaining_sleep -= seconds 

159 

160 

161def _int_setting( 

162 settings: dict[str, Any], 

163 key: str, 

164 default: int, 

165 *, 

166 minimum: int, 

167 maximum: int, 

168) -> int: 

169 try: 

170 value = int(settings.get(key) or default) 

171 except (TypeError, ValueError): 

172 value = default 

173 return min(maximum, max(minimum, value)) 

174 

175 

176SLSKD_UNKNOWN_BITRATE_MODES = ('auto', 'allow', 'reject') 

177 

178 

179def _bitrate_value(value: Any) -> int: 

180 """A kbps value clamped to 0-10000; anything unreadable is 0 (off).""" 

181 try: 

182 number = int(value) 

183 except (TypeError, ValueError): 

184 return 0 

185 return min(10000, max(0, number)) 

186 

187 

188def normalize_slskd_quality(raw: dict[str, Any]) -> dict[str, Any]: 

189 """The fine-tune quality fields of the slskd settings, normalized. 

190 

191 ``advanced`` switches them on; while it is off, candidate selection 

192 ignores them, so turning it off restores the basic behaviour without 

193 losing what was set. ``unknown_bitrate`` decides files that report no 

194 bitrate (``auto`` keeps the basic rule: rejected in strict mode with a 

195 minimum, allowed otherwise). ``format_min_bitrate`` overrides the 

196 minimum per extension, ``max_bitrate`` (0 = off) skips files above it, 

197 such as lossless audio in an ``.m4a``, and ``prefer_bitrate`` tries the 

198 highest bitrate first among files that match well enough. 

199 """ 

200 

201 floors_raw = raw.get('format_min_bitrate') 

202 floors: dict[str, int] = {} 

203 if isinstance(floors_raw, dict): 

204 for ext, value in floors_raw.items(): 

205 key = str(ext or '').strip().lower().lstrip('.') 

206 if key and value not in {None, ''}: 

207 floors[key] = _bitrate_value(value) 

208 unknown = str(raw.get('unknown_bitrate') or 'auto').strip().lower() 

209 if unknown not in SLSKD_UNKNOWN_BITRATE_MODES: 

210 unknown = 'auto' 

211 return { 

212 'advanced': bool(raw.get('advanced', False)), 

213 'unknown_bitrate': unknown, 

214 'format_min_bitrate': floors, 

215 'max_bitrate': _bitrate_value(raw.get('max_bitrate')), 

216 'prefer_bitrate': bool(raw.get('prefer_bitrate', False)), 

217 } 

218 

219 

220def _slskd_deadline(settings: dict[str, Any]) -> float: 

221 seconds = _int_setting( 

222 settings, 

223 'download_timeout_seconds', 

224 _DEFAULT_DOWNLOAD_TIMEOUT_SECONDS, 

225 minimum=30, 

226 maximum=3600, 

227 ) 

228 return time.monotonic() + seconds 

229 

230 

231def _past_deadline(deadline: float) -> bool: 

232 return time.monotonic() >= deadline 

233 

234 

235_AUDIO_EXTENSIONS = frozenset({'mp3', 'flac', 'm4a', 'ogg', 'opus'}) 

236_PATH_PENALTY_KEYWORDS = ( 

237 'unreleased', 

238 'bootleg', 

239 'mixtape', 

240 'discography', 

241) 

242_AMBIGUOUS_TITLE_ALNUM_LEN = 5 

243# Share of the minimum bitrate a variable-bitrate file's average must reach. 

244_VBR_FLOOR_SHARE = 0.85 

245_DEFAULT_MATCH_MIN_SCORE = 5 

246_STRICT_DURATION_SECONDS = 3 

247 

248 

249class SlskdClient: 

250 def __init__(self, settings: dict[str, Any]): 

251 self.base_url = str(settings.get('base_url') or '').strip().rstrip('/') 

252 self.api_key = str(settings.get('api_key') or '').strip() 

253 self.timeout = int(settings.get('timeout_seconds') or 20) 

254 self.search_retries = int(settings.get('search_retries') or 5) 

255 self.search_poll_seconds = int( 

256 settings.get('search_poll_seconds') or 15 

257 ) 

258 self.download_attempts = int(settings.get('download_attempts') or 5) 

259 self.session = httpx.Client(follow_redirects=True) 

260 if self.api_key: 

261 self.session.headers.update({'X-API-Key': self.api_key}) 

262 

263 def configured(self) -> bool: 

264 return bool(self.base_url and self.api_key) 

265 

266 def can_connect(self) -> bool: 

267 for ep in ( 

268 '/api/v0/application', 

269 '/api/v0/options', 

270 '/api/v0/transfers/downloads', 

271 ): 

272 try: 

273 self._request('GET', ep) 

274 return True 

275 except Exception: 

276 continue 

277 return False 

278 

279 def _request( 

280 self, 

281 method: str, 

282 path: str, 

283 *, 

284 json_body: Optional[Any] = None, 

285 ) -> Any: 

286 url = f'{self.base_url}{path}' 

287 kwargs: dict[str, Any] = {'timeout': self.timeout} 

288 if json_body is not None: 

289 kwargs['json'] = json_body 

290 resp = self.session.request(method, url, **kwargs) 

291 resp.raise_for_status() 

292 if not resp.content: 

293 return {} 

294 return resp.json() 

295 

296 def start_search(self, query: str) -> Optional[str]: 

297 body = { 

298 'searchText': query, 

299 'filterResponses': True, 

300 'minimumResponseFileCount': 1, 

301 'minimumPeerUploadSpeed': 1, 

302 } 

303 try: 

304 data = self._request('POST', '/api/v0/searches', json_body=body) 

305 except Exception as exc: 

306 logger.info( 

307 'slskd: search POST failed q={!r} err={}', query[:120], exc 

308 ) 

309 return None 

310 if isinstance(data, dict): 

311 for key in ('id', 'searchId'): 

312 raw = data.get(key) 

313 if isinstance(raw, (int, str)) and str(raw).strip(): 

314 return str(raw).strip() 

315 return None 

316 

317 def wait_search_complete( 

318 self, 

319 search_id: str, 

320 label: str, 

321 *, 

322 on_poll: Optional[Callable[[float], None]] = None, 

323 deadline: Optional[float] = None, 

324 cancel_check: Optional[Callable[[], None]] = None, 

325 ) -> bool: 

326 max_attempts = max(1, self.search_retries) 

327 for attempt in range(max_attempts): 

328 if cancel_check: 

329 cancel_check() 

330 if deadline is not None and _past_deadline(deadline): 

331 return False 

332 if on_poll is not None: 

333 try: 

334 on_poll(5.0 + (attempt / max_attempts) * 30.0) 

335 except Exception: 

336 logger.opt(exception=True).debug( 

337 'slskd search progress callback error' 

338 ) 

339 try: 

340 status = self._request('GET', f'/api/v0/searches/{search_id}') 

341 except Exception as exc: 

342 logger.info( 

343 'slskd: search status failed id={} err={}', search_id, exc 

344 ) 

345 return False 

346 if not isinstance(status, dict): 

347 return False 

348 file_count = int(status.get('fileCount') or 0) 

349 locked = int(status.get('lockedFileCount') or 0) 

350 if status.get('isComplete'): 

351 if file_count > 0 and file_count != locked: 

352 return True 

353 logger.info( 

354 'slskd: search complete but no free files label={!r} ' 

355 'fileCount={} locked={}', 

356 label[:120], 

357 file_count, 

358 locked, 

359 ) 

360 return False 

361 if attempt + 1 < self.search_retries: 

362 time.sleep(max(1, self.search_poll_seconds)) 

363 logger.info( 

364 'slskd: search timed out label={!r} retries={}', 

365 label[:120], 

366 self.search_retries, 

367 ) 

368 return False 

369 

370 def search_responses(self, search_id: str) -> list[dict[str, Any]]: 

371 try: 

372 data = self._request( 

373 'GET', f'/api/v0/searches/{search_id}/responses' 

374 ) 

375 except Exception: 

376 return [] 

377 if isinstance(data, list): 

378 return [r for r in data if isinstance(r, dict)] 

379 return [] 

380 

381 def delete_search(self, search_id: str) -> None: 

382 try: 

383 self._request('DELETE', f'/api/v0/searches/{search_id}') 

384 except Exception: 

385 pass 

386 

387 def enqueue_download(self, row: dict[str, Any]) -> bool: 

388 username = str( 

389 row.get('username') or row.get('userName') or row.get('user') or '' 

390 ).strip() 

391 filename = str( 

392 row.get('filename') 

393 or row.get('fileName') 

394 or row.get('path') 

395 or row.get('fullPath') 

396 or '' 

397 ).strip() 

398 if not username or not filename: 

399 return False 

400 try: 

401 size = int(row.get('size') or 0) 

402 except (TypeError, ValueError): 

403 size = 0 

404 endpoint = f'/api/v0/transfers/downloads/{quote(username)}' 

405 body = [{'filename': filename, 'size': max(0, size)}] 

406 try: 

407 self._request('POST', endpoint, json_body=body) 

408 with _TRANSFERS_LOCK: 

409 _TRANSFERS_CACHE.pop(self._transfers_cache_key(), None) 

410 return True 

411 except Exception as exc: 

412 logger.info( 

413 'slskd: enqueue failed user={!r} file={!r} err={}', 

414 username, 

415 filename[:120], 

416 exc, 

417 ) 

418 return False 

419 

420 def list_download_transfers(self) -> list[dict[str, Any]]: 

421 ttl = _poll_env('DOWNTIFY_TRANSFERS_TTL', 3, 0, 60) 

422 if ttl == 0: 

423 return self._fetch_download_transfers() or [] 

424 # Single-flight across workers using the same endpoint/credentials. 

425 # Never share another API key's snapshot or cache a failed request. 

426 with _TRANSFERS_LOCK: 

427 key = self._transfers_cache_key() 

428 cached = _TRANSFERS_CACHE.get(key) 

429 if cached and 0 <= time.monotonic() - cached[0] < ttl: 

430 _TRANSFERS_CACHE.move_to_end(key) 

431 return cached[1] 

432 data = self._fetch_download_transfers() 

433 if data is None: 

434 return [] 

435 _TRANSFERS_CACHE[key] = (time.monotonic(), data) 

436 _TRANSFERS_CACHE.move_to_end(key) 

437 while len(_TRANSFERS_CACHE) > _TRANSFERS_CACHE_LIMIT: 

438 _TRANSFERS_CACHE.popitem(last=False) 

439 return data 

440 

441 def _transfers_cache_key(self) -> tuple[str, bytes]: 

442 return self.base_url, hashlib.sha256(self.api_key.encode()).digest() 

443 

444 def _fetch_download_transfers(self) -> Optional[list[dict[str, Any]]]: 

445 try: 

446 data = self._request('GET', '/api/v0/transfers/downloads') 

447 except Exception: 

448 return None 

449 if isinstance(data, list): 

450 return [row for row in data if isinstance(row, dict)] 

451 return [] 

452 

453 def find_transfer( 

454 self, username: str, filename: str 

455 ) -> Optional[dict[str, Any]]: 

456 transfers = self.list_download_transfers() 

457 for peer_filter in (username, ''): 

458 for peer in transfers: 

459 if ( 

460 peer_filter 

461 and str(peer.get('username') or '') != peer_filter 

462 ): 

463 continue 

464 for directory in peer.get('directories') or []: 

465 if not isinstance(directory, dict): 

466 continue 

467 for file_row in directory.get('files') or []: 

468 if not isinstance(file_row, dict): 

469 continue 

470 name = str( 

471 file_row.get('filename') 

472 or file_row.get('fileName') 

473 or '' 

474 ) 

475 if _paths_match(name, filename): 

476 return file_row 

477 return None 

478 

479 def remote_download_directories(self) -> list[str]: 

480 """Best-effort read of slskd's configured download/incomplete dirs.""" 

481 for endpoint in ('/api/v0/options', '/api/v0/application'): 

482 try: 

483 data = self._request('GET', endpoint) 

484 except Exception: 

485 continue 

486 paths = _extract_directory_paths(data) 

487 if paths: 

488 return paths 

489 return [] 

490 

491 

492def _flatten_slskd_responses(data: Any) -> list[dict[str, Any]]: 

493 responses = data if isinstance(data, list) else [] 

494 rows: list[dict[str, Any]] = [] 

495 for resp in responses: 

496 if not isinstance(resp, dict): 

497 continue 

498 username = str( 

499 resp.get('username') 

500 or resp.get('userName') 

501 or resp.get('user') 

502 or '' 

503 ).strip() 

504 for file_row in resp.get('files') or []: 

505 if not isinstance(file_row, dict): 

506 continue 

507 filename = str( 

508 file_row.get('filename') 

509 or file_row.get('fileName') 

510 or file_row.get('path') 

511 or '' 

512 ).strip() 

513 if not filename: 

514 continue 

515 rows.append({**file_row, 'username': username}) 

516 return rows 

517 

518 

519def _normalize_search_text(text: str) -> str: 

520 folded = unicodedata.normalize('NFKC', text) 

521 folded = re.sub(r"[''`\u2019]", '', folded) 

522 return re.sub(r'\s+', ' ', folded).strip() 

523 

524 

525# "&", "+" and "and" join names the same way ("Earth, Wind & Fire" is 

526# often filed as "Earth Wind and Fire"), so a comparison leaves them out. 

527_JOINER = re.compile(r'(?<!\w)(?:and|&|\+)(?!\w)', re.IGNORECASE) 

528# "Pt. II" / "Part 2" / "pt 2" are one spelling to a comparison. 

529_PART_NUMBER = re.compile( 

530 r'\b(?:pt|part|vol|volume|chapter)\b\.?\s*([ivx]+|\d+)\b', re.IGNORECASE 

531) 

532_ROMAN = { 

533 'i': '1', 

534 'ii': '2', 

535 'iii': '3', 

536 'iv': '4', 

537 'v': '5', 

538 'vi': '6', 

539 'vii': '7', 

540 'viii': '8', 

541 'ix': '9', 

542 'x': '10', 

543} 

544 

545 

546def _part_number(match: re.Match) -> str: 

547 number = match.group(1).casefold() 

548 return f' pt {_ROMAN.get(number, number)} ' 

549 

550 

551def _alnum_only(text: str) -> str: 

552 """*text* as names are compared: letters and digits only (any script, 

553 so ``夜に駆ける`` is still a title), no accents, no case, without 

554 ``&``/``+``/``and``, and ``Part II`` spelled ``pt 2``.""" 

555 

556 folded = _fold_accents(_normalize_search_text(text)).casefold() 

557 folded = _PART_NUMBER.sub(_part_number, _JOINER.sub(' ', folded)) 

558 return re.sub(r'[\W_]+', '', folded) 

559 

560 

561def _primary_title(title: str) -> str: 

562 text = strip_mix_suffix(str(title or '').strip()) 

563 if ' - ' in text: 

564 head = text.split(' - ', 1)[0].strip() 

565 if head: 

566 return head 

567 return text 

568 

569 

570# "(feat. X)", "[with X]", "(from GTAVI: The Album)": credits and where a 

571# song comes from, which Spotify puts in the title and a shared file's name 

572# usually leaves out, words differently or moves in front of the title. 

573_CREDIT_PART = re.compile( 

574 r'\s*[\(\[]\s*(?:feat\.?|ft\.?|featuring|with|from)\s[^\)\]]*[\)\]]', 

575 re.IGNORECASE, 

576) 

577_CREDIT_TAIL = re.compile( 

578 r'\s+(?:feat\.?|ft\.?|featuring)\s.*$', re.IGNORECASE 

579) 

580 

581 

582def _core_title(title: str) -> str: 

583 """The song's own name, as a shared file names it: :func:`_primary_title` 

584 without featured artists or a "(from …)" note - ``That's It (feat. 

585 Future & Metro Boomin)`` -> ``That's It``.""" 

586 

587 primary = _primary_title(title) 

588 core = _CREDIT_TAIL.sub('', _CREDIT_PART.sub('', primary)).strip() 

589 return core or primary 

590 

591 

592# Words that make a recording a different version of the song. One that 

593# is in Spotify's title must be in the file's path too, so "Despacito - 

594# Remix" never gets the original and "Jóga - Live" never the studio take. 

595_VERSION_WORDS = ( 

596 'remix', 

597 'live', 

598 'acoustic', 

599 'instrumental', 

600 'demo', 

601 'unplugged', 

602 'karaoke', 

603 'acapella', 

604 'a cappella', 

605 'sped up', 

606 'slowed', 

607 'nightcore', 

608 'reprise', 

609 'orchestral', 

610) 

611 

612 

613def _version_words(text: str) -> list[str]: 

614 folded = ' '.join(re.split(r'[\W_]+', _fold_accents(text).casefold())) 

615 return [ 

616 word for word in _VERSION_WORDS if re.search(rf'\b{word}\b', folded) 

617 ] 

618 

619 

620def _missing_version_word(song: dict[str, Any], filename: str) -> bool: 

621 title = str(song.get('name') or '') 

622 album = str(song.get('album_name') or '') 

623 wanted = [ 

624 w for w in _version_words(title) if w not in _version_words(album) 

625 ] + [w for w in _version_words(album) if w in _version_words(title)] 

626 if not wanted: 

627 return False 

628 path = ' '.join(re.split(r'[\W_]+', _fold_accents(filename).casefold())) 

629 return any(word not in path for word in wanted) 

630 

631 

632_BRACKETED = re.compile(r'\s*[\(\[][^\)\]]*[\)\]]') 

633 

634 

635def _bare_title(title: str) -> str: 

636 """:func:`_core_title` without bracketed extras that don't make it a 

637 different version - ``Gangnam Style (강남스타일)`` -> ``Gangnam Style``, 

638 ``Superhero (Heroes & Villains)`` -> ``Superhero`` - or ``""`` when 

639 there are none, or one names a version (``(Taylor's Version)``, 

640 ``(Remix)``).""" 

641 

642 core = _core_title(title) 

643 parts = _BRACKETED.findall(core) 

644 if not parts: 

645 return '' 

646 if any( 

647 _version_words(part) or re.search(r'version|mix|edit', part, re.I) 

648 for part in parts 

649 ): 

650 return '' 

651 return _BRACKETED.sub('', core).strip() 

652 

653 

654def _duo_surnames_in(artist: str, path_alnum: str) -> str: 

655 """For a duo or group credited by full names (``Daryl Hall & John 

656 Oates``), the first surname when every member's surname is in 

657 *path_alnum* - files often say ``Hall & Oates`` - else ``""``.""" 

658 

659 parts = [ 

660 p 

661 for p in re.split(r'\s*(?:,|&|\+|\band\b)\s*', artist, flags=re.I) 

662 if p.strip() 

663 ] 

664 if len(parts) < 2: 

665 return '' 

666 surnames = [_alnum_only(part.split()[-1]) for part in parts] 

667 if all(len(name) >= 3 and name in path_alnum for name in surnames): 

668 return surnames[0] 

669 return '' 

670 

671 

672def _artist_key(artist: str) -> str: 

673 """*artist* as a file name is compared with it: :func:`_alnum_only`, 

674 without a leading "The" (``The Killers`` is often filed as ``Killers``).""" 

675 

676 name = re.sub(r'^\s*the\s+', '', str(artist or ''), flags=re.IGNORECASE) 

677 return _alnum_only(name) or _alnum_only(artist) 

678 

679 

680def _soulseek_words(text: str, *, join_apostrophes: bool = False) -> str: 

681 """*text* as Soulseek search words. Peers match whole words of a shared 

682 path, split at punctuation, so ``That's It (feat. A & B)`` is searched 

683 as ``That s It feat A B`` - the way Nicotine+ sends it - since 

684 ``Thats`` or ``(feat.`` match no file. *join_apostrophes* gives the 

685 ``Thats It`` spelling instead, for files named without the apostrophe.""" 

686 

687 folded = unicodedata.normalize('NFKC', str(text or '')) 

688 # A censored word ("F**kin'") matches no file ("Fuckin"): left out. 

689 folded = re.sub(r'\S*[^\W\d_]\*+\S*', ' ', folded) 

690 folded = re.sub(r"['`\u2019]", '' if join_apostrophes else ' ', folded) 

691 return re.sub(r'[\W_]+', ' ', folded).strip() 

692 

693 

694def _censored_title_in(title: str, base_alnum: str) -> bool: 

695 """Whether *title*, censored by Spotify (``F**kin' Problems``), is in a 

696 file name that spells it out (``Fuckin Problems``): each ``*`` run 

697 stands for up to four letters, or none (``Fkin``).""" 

698 

699 if not re.search(r'[^\W\d_]\*', title): 

700 return False 

701 pieces = [_alnum_only(piece) for piece in re.split(r'\*+', title)] 

702 if not any(pieces): 

703 return False 

704 pattern = r'\w{0,4}'.join(re.escape(piece) for piece in pieces) 

705 return re.search(pattern, base_alnum) is not None 

706 

707 

708def _title_in_basename(filename: str, title_alnum: str) -> bool: 

709 """Require title as a basename token (avoids folder-only and substring false hits).""" 

710 

711 if not title_alnum: 

712 return True 

713 base = _file_basename(filename) 

714 base_alnum = _alnum_only(base) 

715 if title_alnum == base_alnum: 

716 return True 

717 folded = _fold_accents(_normalize_search_text(base)).casefold() 

718 tokens = [ 

719 _alnum_only(part) 

720 for part in re.split(r'[\W_]+', folded) 

721 if _alnum_only(part) 

722 ] 

723 if title_alnum in tokens: 

724 return True 

725 if len(title_alnum) >= 6 and title_alnum in base_alnum: 

726 return True 

727 # A short title of several words ("Hey Ya!") is in "OutKast - Hey Ya!" 

728 # when it covers whole words there, not part of one ("Theyyard"). 

729 joined = ''.join(tokens) 

730 starts, ends, position = set(), set(), 0 

731 for token in tokens: 

732 starts.add(position) 

733 position += len(token) 

734 ends.add(position) 

735 at = joined.find(title_alnum) 

736 while at >= 0: 

737 if at in starts and at + len(title_alnum) in ends: 

738 return True 

739 at = joined.find(title_alnum, at + 1) 

740 return False 

741 

742 

743def _slskd_search_queries(song: dict[str, Any]) -> list[str]: 

744 """What to search Soulseek for, most likely first, as plain words 

745 (:func:`_soulseek_words`): the artist and the song's own name 

746 (:func:`_core_title`, no "(feat. …)"), the same without apostrophes, 

747 the artist with the full title (``Loud Enough Radio Mix``), the song's 

748 name alone, and the artist and name without accents. A peer only 

749 answers when every word is in a file's path, so fewer, plainer words 

750 find more; the ranking (:func:`_score_slskd_candidate`) decides which 

751 file is the song.""" 

752 

753 artists = [ 

754 str(a).strip() 

755 for a in (song.get('artists') or [])[:2] 

756 if str(a).strip() 

757 ] 

758 artist = artists[0] if artists else '' 

759 title = str(song.get('name') or '').strip() 

760 core = _core_title(title) 

761 short_title = _primary_title(title) 

762 queries: list[str] = [] 

763 seen: set[str] = set() 

764 

765 def add(q: str, *, join_apostrophes: bool = False) -> None: 

766 words = _soulseek_words(q, join_apostrophes=join_apostrophes) 

767 if words and words.casefold() not in seen: 

768 seen.add(words.casefold()) 

769 queries.append(words) 

770 

771 if artist and core: 

772 add(f'{artist} {core}') 

773 add(f'{artist} {core}', join_apostrophes=True) 

774 if artist and title: 

775 add(f'{artist} {_CREDIT_PART.sub("", title)}') 

776 if short_title != core: 

777 add(f'{artist} {short_title}') 

778 plain_artist = _plain_name(artist) 

779 if artist and core and plain_artist != _soulseek_words(artist): 

780 add(f'{plain_artist} {core}') 

781 bare = _bare_title(title) 

782 if artist and bare: 

783 add(f'{artist} {bare}') 

784 if core: 

785 add(core) 

786 if artist and core: 

787 add(_fold_accents(f'{artist} {core}')) 

788 return queries 

789 

790 

791# Words that carry little meaning in a search, dropped first when a search 

792# has to be loosened (see _blocked_phrase_queries). 

793_FILLER_WORDS = frozenset({ 

794 'a', 

795 'an', 

796 'and', 

797 'at', 

798 'by', 

799 'for', 

800 'from', 

801 'in', 

802 'is', 

803 'it', 

804 'me', 

805 'my', 

806 'of', 

807 'on', 

808 'or', 

809 'the', 

810 'to', 

811 'with', 

812 'you', 

813 'your', 

814}) 

815_BLOCKED_PHRASE_TRIES = 3 

816_BLOCKED_PAIR_TRIES = 2 

817 

818 

819def _blocked_phrase_queries( 

820 song: dict[str, Any], tried: list[str] 

821) -> list[str]: 

822 """Searches with words left out, for when nobody answered any of 

823 *tried*. The Soulseek server silently answers nothing to some word 

824 combinations - artist names such as "Frank Ocean" or "Lady Gaga", and 

825 some titles such as "Starting From Zero" or "Hold My Hand" - in any 

826 order, while "Ocean Nights", "Justice Starting Zero" and "Gaga Hold 

827 Hand" find the files (all measured). Up to three searches leave one 

828 word out - filler words (``From``) first, then the shortest - then up 

829 to two leave out two, for when the artist and the title are both 

830 blocked. At least two words always remain.""" 

831 

832 queries = _slskd_search_queries(song) 

833 if not queries: 

834 return [] 

835 words = queries[0].split() 

836 if len(words) < 3: 

837 return [] 

838 order = sorted( 

839 range(len(words)), 

840 key=lambda i: ( 

841 words[i].casefold() not in _FILLER_WORDS, 

842 len(words[i]), 

843 ), 

844 ) 

845 seen = {q.casefold() for q in tried} 

846 out: list[str] = [] 

847 

848 def add(dropped: set[int], limit: int) -> None: 

849 query = ' '.join(w for i, w in enumerate(words) if i not in dropped) 

850 if ( 

851 len(out) < limit 

852 and len(words) - len(dropped) >= 2 

853 and query.casefold() not in seen 

854 ): 

855 seen.add(query.casefold()) 

856 out.append(query) 

857 

858 for index in order: 

859 add({index}, _BLOCKED_PHRASE_TRIES) 

860 if len(words) >= 4: 

861 pairs = [(order[0], order[1]), (order[0], order[2])] 

862 for pair in pairs: 

863 add(set(pair), _BLOCKED_PHRASE_TRIES + _BLOCKED_PAIR_TRIES) 

864 return out 

865 

866 

867def _file_extension(filename: str) -> str: 

868 ext = Path(filename.replace('\\', '/')).suffix.lower().lstrip('.') 

869 return re.sub(r'[^a-z0-9]+', '', ext) 

870 

871 

872def _path_segments(filename: str) -> list[str]: 

873 """Parent folders in a Soulseek path (people often encode artist/album there).""" 

874 normalized = str(filename or '').replace('\\', '/') 

875 parent = Path(normalized).parent 

876 return [part for part in parent.parts if part not in {'.', '/'}] 

877 

878 

879def _contains_keyword( 

880 song: dict[str, Any], 

881 filename: str, 

882 *, 

883 allow_mix_variants: bool = False, 

884) -> bool: 

885 """Filter remix/live/etc. on the file name, not parent folder names.""" 

886 # The album counts too: a track of "Homogenic (Live)" is a live take. 

887 title = f'{song.get("name") or ""} {song.get("album_name") or ""}' 

888 artists = [str(a) for a in (song.get('artists') or []) if str(a).strip()] 

889 basename = _file_basename(filename) 

890 haystacks = [basename] 

891 segments = _path_segments(filename) 

892 if segments: 

893 # Immediate parent folder (e.g. "Artist - Album") — not the whole tree. 

894 haystacks.append(segments[-1]) 

895 skip = ( 

896 MIX_VARIANT_REMOTE_SKIP_KEYWORDS if allow_mix_variants else frozenset() 

897 ) 

898 return any( 

899 remote_text_unacceptable( 

900 title, 

901 haystack, 

902 spotify_artists=artists, 

903 skip_variant_keywords=skip, 

904 ) 

905 for haystack in haystacks 

906 ) 

907 

908 

909def _parse_duration_seconds(value: Any) -> int: 

910 if isinstance(value, int): 

911 return value 

912 text = str(value or '').strip() 

913 if not text: 

914 return 0 

915 if text.isdigit(): 

916 return int(text) 

917 parts = text.split(':') 

918 try: 

919 nums = [int(p) for p in parts] 

920 except ValueError: 

921 return 0 

922 if len(nums) == 2: 

923 return nums[0] * 60 + nums[1] 

924 if len(nums) == 3: 

925 return nums[0] * 3600 + nums[1] * 60 + nums[2] 

926 return 0 

927 

928 

929def _response_has_free_slot(resp: dict[str, Any]) -> bool: 

930 return resp.get('hasFreeUploadSlot') is True 

931 

932 

933def _file_is_locked(file_row: dict[str, Any]) -> bool: 

934 if file_row.get('isLocked') is True: 

935 return True 

936 if file_row.get('IsLocked') is True: 

937 return True 

938 return False 

939 

940 

941def _locked_filenames(resp: dict[str, Any]) -> set[str]: 

942 names: set[str] = set() 

943 for file_row in resp.get('lockedFiles') or []: 

944 if not isinstance(file_row, dict): 

945 continue 

946 filename = str( 

947 file_row.get('filename') 

948 or file_row.get('fileName') 

949 or file_row.get('path') 

950 or '' 

951 ).strip() 

952 if filename: 

953 names.add(filename.casefold()) 

954 return names 

955 

956 

957def _filter_slskd_responses( 

958 responses: list[dict[str, Any]], 

959) -> list[dict[str, Any]]: 

960 """Drop peers without a free upload slot (slskd UI: hide no free slots).""" 

961 return [r for r in responses if _response_has_free_slot(r)] 

962 

963 

964def _busy_responses(responses: list[dict[str, Any]]) -> list[dict[str, Any]]: 

965 """Peers whose upload slots are all taken. A download from one waits in 

966 its queue (``queued_timeout_seconds``), which still beats YouTube when 

967 no peer with a free slot has the song.""" 

968 

969 return [ 

970 r 

971 for r in responses 

972 if not _response_has_free_slot(r) and int(r.get('fileCount') or 0) > 0 

973 ] 

974 

975 

976def _song_duration_seconds(song: dict[str, Any]) -> int: 

977 target_duration = int(song.get('duration') or 0) 

978 if target_duration > 1000: 

979 return target_duration // 1000 

980 return target_duration 

981 

982 

983def _title_is_ambiguous(title_alnum: str) -> bool: 

984 return len(title_alnum) < _AMBIGUOUS_TITLE_ALNUM_LEN 

985 

986 

987def _match_min_score(settings: dict[str, Any]) -> int: 

988 try: 

989 value = int( 

990 settings.get('match_min_score') or _DEFAULT_MATCH_MIN_SCORE 

991 ) 

992 except (TypeError, ValueError): 

993 value = _DEFAULT_MATCH_MIN_SCORE 

994 return max(0, value) 

995 

996 

997def _score_slskd_candidate( # noqa: PLR0914 

998 song: dict[str, Any], 

999 filename: str, 

1000 file_row: dict[str, Any], 

1001 *, 

1002 target_duration: int, 

1003 mix_variant_duration: bool = False, 

1004 settings: Optional[dict[str, Any]] = None, 

1005) -> Optional[tuple[int, list[str]]]: 

1006 """Return (score, reasons) or None when hard requirements fail.""" 

1007 tol = duration_tolerances_from_settings(settings) 

1008 album = _alnum_only(str(song.get('album_name') or '')) 

1009 raw_name = str(song.get('name') or '') 

1010 title = _alnum_only(_core_title(raw_name)) 

1011 full_title = _alnum_only(raw_name) 

1012 sanitized_name = _alnum_only(filename) 

1013 basename = _file_basename(filename) 

1014 base_alnum = _alnum_only(basename) 

1015 path_segments = _path_segments(filename) 

1016 # The first credited artist, or another one when only that one is in 

1017 # the path ("Metro Boomin - …" for a Yung Lean song featuring him). 

1018 artist_keys = [ 

1019 key 

1020 for a in (song.get('artists') or [])[:3] 

1021 for key in dict.fromkeys(( 

1022 _artist_key(str(a)), 

1023 _artist_key(_plain_name(str(a))), 

1024 )) 

1025 if key 

1026 ] 

1027 artist = next( 

1028 (key for key in artist_keys if key in sanitized_name), 

1029 '', 

1030 ) or next( 

1031 ( 

1032 key 

1033 for a in (song.get('artists') or [])[:3] 

1034 if (key := _duo_surnames_in(str(a), sanitized_name)) 

1035 ), 

1036 artist_keys[0] if artist_keys else '', 

1037 ) 

1038 

1039 if not artist and not title and not full_title: 

1040 return None 

1041 

1042 # Soulseek paths often include the requested album/title in folders while 

1043 # the leaf file is a different track — require title on the filename itself. 

1044 title_ok = False 

1045 bare = _alnum_only(_bare_title(raw_name)) 

1046 if title and _title_in_basename(filename, title): 

1047 title_ok = True 

1048 elif ( 

1049 full_title 

1050 and full_title != title 

1051 and _title_in_basename(filename, full_title) 

1052 ): 

1053 title_ok = True 

1054 elif bare and _title_in_basename(filename, bare): 

1055 title_ok = True 

1056 title = bare 

1057 elif _censored_title_in(_core_title(raw_name), base_alnum): 

1058 title_ok = True 

1059 title = '' 

1060 if (title or full_title) and not title_ok: 

1061 return None 

1062 if _missing_version_word(song, filename): 

1063 return None 

1064 

1065 artist_in_leaf = bool(artist and artist in base_alnum) 

1066 artist_in_path = bool( 

1067 artist and any(artist in _alnum_only(seg) for seg in path_segments) 

1068 ) 

1069 if artist and not (artist_in_leaf or artist_in_path): 

1070 return None 

1071 

1072 length = _parse_duration_seconds( 

1073 file_row.get('length') or file_row.get('duration') 

1074 ) 

1075 if _title_is_ambiguous(title): 

1076 if not (target_duration and length): 

1077 return None 

1078 if abs(target_duration - length) > _STRICT_DURATION_SECONDS: 

1079 return None 

1080 elif target_duration and length: 

1081 if mix_variant_duration: 

1082 duration_ok = media_duration_matches_mix_variant( 

1083 song, 

1084 length, 

1085 tolerance_percent=tol['mix_percent'], 

1086 normal_tolerance_seconds=tol['seconds'], 

1087 normal_tolerance_percent=tol['percent'], 

1088 ) 

1089 else: 

1090 duration_ok = media_duration_matches_song( 

1091 song, 

1092 length, 

1093 tolerance_seconds=tol['seconds'], 

1094 tolerance_percent=tol['percent'], 

1095 ) 

1096 if not duration_ok: 

1097 return None 

1098 

1099 score = 0 

1100 reasons: list[str] = [] 

1101 

1102 if artist and ( 

1103 base_alnum.startswith(artist) or base_alnum.startswith(f'the{artist}') 

1104 ): 

1105 score += 3 

1106 reasons.append('artist_prefix') 

1107 elif artist and artist in base_alnum: 

1108 score += 1 

1109 reasons.append('artist') 

1110 elif artist and artist in sanitized_name: 

1111 score += 2 

1112 reasons.append('artist_in_path') 

1113 

1114 if title and _title_in_basename(filename, title): 

1115 score += 2 

1116 reasons.append('title') 

1117 if artist and base_alnum.find(artist) < base_alnum.find(title): 

1118 score += 2 

1119 reasons.append('artist_before_title') 

1120 elif ( 

1121 full_title 

1122 and full_title != title 

1123 and _title_in_basename(filename, full_title) 

1124 ): 

1125 score += 2 

1126 reasons.append('title_full') 

1127 elif title and title in sanitized_name: 

1128 score += 2 

1129 reasons.append('title_in_path') 

1130 

1131 for segment in path_segments: 

1132 segment_alnum = _alnum_only(segment) 

1133 if not segment_alnum: 

1134 continue 

1135 if ( 

1136 artist 

1137 and title 

1138 and artist in segment_alnum 

1139 and title in segment_alnum 

1140 ): 

1141 score += 2 

1142 reasons.append('folder_segment') 

1143 break 

1144 if album and album in segment_alnum: 

1145 score += 1 

1146 reasons.append('album_folder') 

1147 break 

1148 

1149 if target_duration and length: 

1150 delta = abs(target_duration - length) 

1151 if delta <= min(_STRICT_DURATION_SECONDS, tol['seconds']): 

1152 score += 3 

1153 reasons.append('duration_3s') 

1154 elif delta <= tol['seconds']: 

1155 score += 1 

1156 reasons.append('duration_10s') 

1157 

1158 if album and album in sanitized_name: 

1159 score += 1 

1160 reasons.append('album') 

1161 

1162 # Soft penalty only when the leaf file name lacks title (dump folders). 

1163 path_folded = filename.casefold() 

1164 if ( 

1165 title 

1166 and title not in base_alnum 

1167 and any(keyword in path_folded for keyword in _PATH_PENALTY_KEYWORDS) 

1168 ): 

1169 score -= 1 

1170 reasons.append('path_penalty') 

1171 

1172 try: 

1173 bitrate = int(file_row.get('bitRate') or file_row.get('bitrate') or 0) 

1174 except (TypeError, ValueError): 

1175 bitrate = 0 

1176 if bitrate >= 320: 

1177 score += 1 

1178 reasons.append('bitrate_320') 

1179 elif bitrate >= 192: 

1180 score += 1 

1181 reasons.append('bitrate_192') 

1182 

1183 return score, reasons 

1184 

1185 

1186def _rank_slskd_candidates( 

1187 song: dict[str, Any], 

1188 responses: list[dict[str, Any]], 

1189 settings: Optional[dict[str, Any]] = None, 

1190 *, 

1191 allow_mix_variants: bool = False, 

1192 include_busy: bool = False, 

1193) -> list[dict[str, Any]]: 

1194 """Score and sort all viable files (highest confidence first); peers 

1195 without a free upload slot only with *include_busy*.""" 

1196 target_duration = _song_duration_seconds(song) 

1197 ranked: list[dict[str, Any]] = [] 

1198 

1199 for resp in ( 

1200 responses if include_busy else _filter_slskd_responses(responses) 

1201 ): 

1202 if int(resp.get('fileCount') or 0) <= 0: 

1203 continue 

1204 username = str(resp.get('username') or '').strip() 

1205 locked_names = _locked_filenames(resp) 

1206 for file_row in resp.get('files') or []: 

1207 if not isinstance(file_row, dict): 

1208 continue 

1209 if _file_is_locked(file_row): 

1210 continue 

1211 filename = str( 

1212 file_row.get('filename') 

1213 or file_row.get('fileName') 

1214 or file_row.get('path') 

1215 or '' 

1216 ).strip() 

1217 if not filename: 

1218 continue 

1219 if filename.casefold() in locked_names: 

1220 continue 

1221 ext = _file_extension(filename) 

1222 if ext and ext not in _AUDIO_EXTENSIONS: 

1223 continue 

1224 if _contains_keyword( 

1225 song, filename, allow_mix_variants=allow_mix_variants 

1226 ): 

1227 continue 

1228 

1229 scored = _score_slskd_candidate( 

1230 song, 

1231 filename, 

1232 file_row, 

1233 target_duration=target_duration, 

1234 mix_variant_duration=allow_mix_variants, 

1235 settings=settings, 

1236 ) 

1237 if scored is None: 

1238 continue 

1239 score, reasons = scored 

1240 ranked.append({ 

1241 **file_row, 

1242 'username': username, 

1243 'filename': filename, 

1244 'match_score': score, 

1245 'match_reasons': reasons, 

1246 }) 

1247 

1248 ranked.sort( 

1249 key=lambda row: ( 

1250 -int(row.get('match_score') or 0), 

1251 -int(row.get('bitRate') or row.get('bitrate') or 0), 

1252 ) 

1253 ) 

1254 return ranked 

1255 

1256 

1257def _collect_matching_files( 

1258 song: dict[str, Any], responses: list[dict[str, Any]] 

1259) -> list[dict[str, Any]]: 

1260 """Ranked candidates without applying the minimum score gate (tests).""" 

1261 return _rank_slskd_candidates(song, responses) 

1262 

1263 

1264def _select_download_candidates( 

1265 ranked: list[dict[str, Any]], settings: dict[str, Any] 

1266) -> list[dict[str, Any]]: 

1267 """Choose candidates by score, or in ordered format tiers when enabled.""" 

1268 raw_ext = settings.get('extensions') or ['mp3', 'flac'] 

1269 extensions = list( 

1270 dict.fromkeys( 

1271 str(e).strip().lower().lstrip('.') 

1272 for e in raw_ext 

1273 if str(e).strip() 

1274 ) 

1275 ) or ['mp3', 'flac'] 

1276 min_bitrate = int(settings.get('min_bitrate') or 0) 

1277 max_files = int(settings.get('download_attempts') or 5) 

1278 strict_priority = bool(settings.get('strict_format_priority', False)) 

1279 whitelist = bool(settings.get('extensions_whitelist', False)) 

1280 quality = normalize_slskd_quality(settings) 

1281 if not quality['advanced']: 

1282 quality = normalize_slskd_quality({}) 

1283 

1284 def bitrate_of(file_row: dict[str, Any]) -> int: 

1285 try: 

1286 return int(file_row.get('bitRate') or file_row.get('bitrate') or 0) 

1287 except (TypeError, ValueError): 

1288 return 0 

1289 

1290 def rank_key(file_row: dict[str, Any]) -> tuple[int, int]: 

1291 score = int(file_row.get('match_score') or 0) 

1292 if quality['prefer_bitrate']: 

1293 return (-bitrate_of(file_row), -score) 

1294 return (-score, -bitrate_of(file_row)) 

1295 

1296 candidates = [ 

1297 row 

1298 for row in ranked 

1299 if not whitelist 

1300 or _file_extension(str(row.get('filename') or '')) in extensions 

1301 ] 

1302 

1303 def passes_bitrate(file_row: dict[str, Any]) -> bool: 

1304 bitrate = bitrate_of(file_row) 

1305 ext = _file_extension(str(file_row.get('filename') or '')) 

1306 if quality['max_bitrate'] and bitrate > quality['max_bitrate']: 

1307 return False 

1308 if strict_priority and ext == 'flac': 

1309 return True 

1310 floor = quality['format_min_bitrate'].get(ext, min_bitrate) 

1311 if not bitrate: 

1312 if quality['unknown_bitrate'] == 'allow': 

1313 return True 

1314 if quality['unknown_bitrate'] == 'reject': 

1315 return False 

1316 return not (strict_priority and floor) 

1317 if file_row.get('isVariableBitRate') and floor: 

1318 # A VBR file reports its average: LAME V0, as good as 320 CBR, 

1319 # averages ~220-260 kbps, so it passes at 85 % of the floor. 

1320 return bitrate >= floor * _VBR_FLOOR_SHARE 

1321 return bitrate >= floor 

1322 

1323 if strict_priority: 

1324 selected: list[dict[str, Any]] = [] 

1325 tiers = [ 

1326 [ 

1327 row 

1328 for row in candidates 

1329 if _file_extension(str(row.get('filename') or '')) == ext 

1330 ] 

1331 for ext in extensions 

1332 ] 

1333 if not whitelist: 

1334 tiers.append([ 

1335 row 

1336 for row in candidates 

1337 if _file_extension(str(row.get('filename') or '')) 

1338 not in extensions 

1339 ]) 

1340 

1341 for tier in tiers: 

1342 accepted = [row for row in tier if passes_bitrate(row)] 

1343 accepted.sort(key=rank_key) 

1344 selected.extend(accepted[:max_files]) 

1345 return selected 

1346 

1347 # Grouped by match score, so the format order breaks ties; with 

1348 # ``prefer_bitrate`` grouped by bitrate instead (best match first). 

1349 by_group: dict[int, list[dict[str, Any]]] = {} 

1350 for row in sorted(candidates, key=rank_key): 

1351 by_group.setdefault(rank_key(row)[0], []).append(row) 

1352 

1353 selected: list[dict[str, Any]] = [] 

1354 for group in sorted(by_group.keys()): 

1355 bucket = by_group[group] 

1356 for ext in extensions: 

1357 for file_row in bucket: 

1358 if _file_extension(str(file_row.get('filename') or '')) != ext: 

1359 continue 

1360 if not passes_bitrate(file_row): 

1361 continue 

1362 selected.append(file_row) 

1363 if len(selected) >= max_files: 

1364 return selected 

1365 for file_row in bucket: 

1366 if file_row in selected: 

1367 continue 

1368 if not passes_bitrate(file_row): 

1369 continue 

1370 selected.append(file_row) 

1371 if len(selected) >= max_files: 

1372 return selected 

1373 return selected 

1374 

1375 

1376def _file_basename(filename: str) -> str: 

1377 return Path(str(filename or '').replace('\\', '/')).name 

1378 

1379 

1380def _paths_match(left: str, right: str) -> bool: 

1381 if not left or not right: 

1382 return False 

1383 if left == right: 

1384 return True 

1385 return _file_basename(left).casefold() == _file_basename(right).casefold() 

1386 

1387 

1388def _extract_directory_paths(data: Any) -> list[str]: 

1389 paths: list[str] = [] 

1390 

1391 def walk(node: Any) -> None: 

1392 if isinstance(node, dict): 

1393 directories = node.get('directories') 

1394 if isinstance(directories, dict): 

1395 for key in ('downloads', 'incomplete', 'download'): 

1396 raw = directories.get(key) 

1397 if isinstance(raw, str) and raw.strip(): 

1398 paths.append(raw.strip()) 

1399 for value in node.values(): 

1400 walk(value) 

1401 elif isinstance(node, list): 

1402 for item in node: 

1403 walk(item) 

1404 

1405 walk(data) 

1406 out: list[str] = [] 

1407 seen: set[str] = set() 

1408 for raw in paths: 

1409 if raw not in seen: 

1410 seen.add(raw) 

1411 out.append(raw) 

1412 return out 

1413 

1414 

1415def _search_roots(settings: dict[str, Any], client: SlskdClient) -> list[Path]: 

1416 roots: list[Path] = [] 

1417 seen: set[str] = set() 

1418 for raw in ( 

1419 settings.get('source_dir'), 

1420 settings.get('output_dir'), 

1421 settings.get('download_dir'), 

1422 *client.remote_download_directories(), 

1423 ): 

1424 text = str(raw or '').strip() 

1425 if not text or text in seen: 

1426 continue 

1427 seen.add(text) 

1428 roots.append(Path(text)) 

1429 return roots 

1430 

1431 

1432def _parse_soulseek_path(filename: str) -> tuple[str, str]: 

1433 normalized = filename.replace('\\', '/') 

1434 parent = Path(normalized).parent 

1435 parent_name = '' if str(parent) in {'.', '/'} else parent.name 

1436 return Path(normalized).name, parent_name 

1437 

1438 

1439def _transfer_failed(status: dict[str, Any]) -> bool: 

1440 state = str(status.get('state') or '') 

1441 return any( 

1442 failure in state 

1443 for failure in ( 

1444 'Errored', 

1445 'Cancelled', 

1446 'Aborted', 

1447 'Rejected', 

1448 'TimedOut', 

1449 ) 

1450 ) 

1451 

1452 

1453def _transfer_succeeded(status: dict[str, Any]) -> bool: 

1454 state = str(status.get('state') or '') 

1455 remaining = int(status.get('bytesRemaining') or 0) 

1456 percent = float(status.get('percentComplete') or 0) 

1457 return ( 

1458 remaining == 0 

1459 or percent >= 100 

1460 or 'Succeeded' in state 

1461 or 'Completed' in state 

1462 ) 

1463 

1464 

1465def _slskd_transfer_progress_pct( 

1466 *, 

1467 transfer: Optional[dict[str, Any]] = None, 

1468 on_disk_bytes: int = 0, 

1469 expected_size: int = 0, 

1470 poll_attempt: int = 0, 

1471) -> tuple[float, str]: 

1472 """Map an active slskd transfer to overall job progress (40–92%).""" 

1473 

1474 lo, hi = 40.0, 92.0 

1475 span = hi - lo 

1476 if transfer: 

1477 try: 

1478 pct_complete = float(transfer.get('percentComplete') or 0) 

1479 except (TypeError, ValueError): 

1480 pct_complete = 0.0 

1481 if 0 < pct_complete <= 100: 

1482 return lo + span * (pct_complete / 100.0), 'Downloading' 

1483 try: 

1484 transferred = int(transfer.get('bytesTransferred') or 0) 

1485 size = int(transfer.get('size') or 0) or int(expected_size or 0) 

1486 except (TypeError, ValueError): 

1487 transferred = 0 

1488 size = 0 

1489 if size > 0 and transferred >= 0: 

1490 ratio = min(1.0, transferred / size) 

1491 return lo + span * ratio, 'Downloading' 

1492 if expected_size > 0 and on_disk_bytes > 0: 

1493 ratio = min(1.0, on_disk_bytes / expected_size) 

1494 return lo + span * ratio, 'Downloading' 

1495 fallback = lo + min(span * 0.12, max(0, poll_attempt) * 0.4) 

1496 return min(hi - 4.0, fallback), 'Waiting for slskd' 

1497 

1498 

1499def _normalize_token(text: str) -> str: 

1500 folded = unicodedata.normalize('NFKD', text) 

1501 stripped = ''.join(ch for ch in folded if not unicodedata.combining(ch)) 

1502 return re.sub(r'\s+', ' ', stripped).casefold().strip() 

1503 

1504 

1505def _disk_complete(path: Path, expected_size: int) -> bool: 

1506 try: 

1507 size = path.stat().st_size 

1508 except OSError: 

1509 return False 

1510 if expected_size > 0: 

1511 return size >= int(expected_size * 0.95) 

1512 return size > 50_000 

1513 

1514 

1515def _find_on_disk( 

1516 roots: list[Path], 

1517 soulseek_filename: str, 

1518 *, 

1519 username: str = '', 

1520 min_size: int = 1, 

1521 deep_scan: bool = True, 

1522) -> Optional[Path]: 

1523 basename, parent = _parse_soulseek_path(soulseek_filename) 

1524 if not basename: 

1525 return None 

1526 relative_candidates: list[Path] = [Path(basename)] 

1527 if parent: 

1528 relative_candidates.append(Path(parent) / basename) 

1529 if username: 

1530 relative_candidates.append(Path(username) / basename) 

1531 if parent: 

1532 relative_candidates.append(Path(username) / parent / basename) 

1533 

1534 for root in roots: 

1535 if not root.exists(): 

1536 continue 

1537 for rel in relative_candidates: 

1538 candidate = root / rel 

1539 if candidate.is_file() and candidate.stat().st_size >= min_size: 

1540 return candidate 

1541 

1542 if not deep_scan: 

1543 return None 

1544 best: Optional[Path] = None 

1545 best_mtime = 0.0 

1546 for root in roots: 

1547 if not root.exists(): 

1548 continue 

1549 try: 

1550 matches = list(root.rglob(basename)) 

1551 except OSError: 

1552 continue 

1553 for candidate in matches: 

1554 if not candidate.is_file(): 

1555 continue 

1556 try: 

1557 size = candidate.stat().st_size 

1558 mtime = candidate.stat().st_mtime 

1559 except OSError: 

1560 continue 

1561 if size < min_size: 

1562 continue 

1563 if mtime >= best_mtime: 

1564 best = candidate 

1565 best_mtime = mtime 

1566 return best 

1567 

1568 

1569def _find_on_disk_for_song( 

1570 roots: list[Path], 

1571 song: dict[str, Any], 

1572 soulseek_filename: str, 

1573 *, 

1574 username: str = '', 

1575 expected_size: int = 0, 

1576 extensions: Optional[frozenset[str]] = None, 

1577 deep_scan: bool = True, 

1578) -> Optional[Path]: 

1579 min_size = max(1, int(expected_size * 0.95) if expected_size else 1) 

1580 found = _find_on_disk( 

1581 roots, 

1582 soulseek_filename, 

1583 username=username, 

1584 min_size=min_size, 

1585 deep_scan=deep_scan, 

1586 ) 

1587 if found is not None: 

1588 return found 

1589 if not deep_scan: 

1590 return None 

1591 

1592 title = _normalize_token(str(song.get('name') or '')) 

1593 if len(title) < 3: 

1594 return None 

1595 exts = extensions or _AUDIO_EXTENSIONS 

1596 best: Optional[Path] = None 

1597 best_mtime = 0.0 

1598 for root in roots: 

1599 if not root.exists(): 

1600 continue 

1601 for ext in exts: 

1602 pattern = ext if ext.startswith('.') else f'.{ext}' 

1603 try: 

1604 matches = list(root.rglob(f'*{pattern}')) 

1605 except OSError: 

1606 continue 

1607 for candidate in matches: 

1608 if not candidate.is_file(): 

1609 continue 

1610 if title not in _normalize_token(candidate.name): 

1611 continue 

1612 try: 

1613 size = candidate.stat().st_size 

1614 mtime = candidate.stat().st_mtime 

1615 except OSError: 

1616 continue 

1617 if size < min_size: 

1618 continue 

1619 if mtime >= best_mtime: 

1620 best = candidate 

1621 best_mtime = mtime 

1622 return best 

1623 

1624 

1625def _resolve_downloaded_file( 

1626 roots: list[Path], 

1627 song: dict[str, Any], 

1628 soulseek_filename: str, 

1629 *, 

1630 username: str, 

1631 expected_size: int = 0, 

1632) -> Optional[Path]: 

1633 return _find_on_disk_for_song( 

1634 roots, 

1635 song, 

1636 soulseek_filename, 

1637 username=username, 

1638 expected_size=expected_size, 

1639 ) 

1640 

1641 

1642def _finalize_slskd_path(found: Path) -> Path: 

1643 """Return the original transfer; Downloader owns import and cleanup.""" 

1644 

1645 return found 

1646 

1647 

1648def _wait_for_slskd_file( 

1649 client: SlskdClient, 

1650 song: dict[str, Any], 

1651 username: str, 

1652 filename: str, 

1653 settings: dict[str, Any], 

1654 roots: list[Path], 

1655 *, 

1656 expected_size: int = 0, 

1657 progress_cb: Optional[ProgressCallback] = None, 

1658 deadline: Optional[float] = None, 

1659 cancel_check: Optional[Callable[[], None]] = None, 

1660) -> Optional[Path]: 

1661 """Wait for slskd to finish, then return the file path on disk (if found).""" 

1662 poll = _PollSchedule(settings) 

1663 queued_timeout = _int_setting( 

1664 settings, 

1665 'queued_timeout_seconds', 

1666 _DEFAULT_QUEUED_TIMEOUT_SECONDS, 

1667 minimum=15, 

1668 maximum=3600, 

1669 ) 

1670 last_bytes = -1 

1671 last_progress = poll.started 

1672 last_reported_pct = -1.0 

1673 

1674 for attempt in range(poll.attempts): 

1675 if cancel_check: 

1676 cancel_check() 

1677 if deadline is not None and _past_deadline(deadline): 

1678 logger.info( 

1679 'slskd: download timeout while waiting for file title={!r} ' 

1680 'user={!r} file={!r}', 

1681 song.get('name'), 

1682 username, 

1683 _file_basename(filename)[:120], 

1684 ) 

1685 return None 

1686 if attempt and poll.remaining_sleep <= 0: 

1687 break 

1688 transfer = client.find_transfer(username, filename) 

1689 found = _find_on_disk_for_song( 

1690 roots, 

1691 song, 

1692 filename, 

1693 username=username, 

1694 expected_size=expected_size, 

1695 deep_scan=poll.should_scan(attempt, transfer), 

1696 ) 

1697 on_disk_bytes = 0 

1698 if found is not None: 

1699 try: 

1700 on_disk_bytes = found.stat().st_size 

1701 except OSError: 

1702 on_disk_bytes = 0 

1703 if _disk_complete(found, expected_size): 

1704 if progress_cb is not None: 

1705 progress_cb(92.0, 'slskd · downloading', 'slskd') 

1706 return found 

1707 

1708 if transfer: 

1709 try: 

1710 expected_size = max( 

1711 expected_size, int(transfer.get('size') or 0) 

1712 ) 

1713 except (TypeError, ValueError): 

1714 pass 

1715 if _transfer_failed(transfer): 

1716 return None 

1717 transferred = int(transfer.get('bytesTransferred') or 0) 

1718 if transferred > last_bytes: 

1719 last_bytes = transferred 

1720 last_progress = time.monotonic() 

1721 elif time.monotonic() - last_progress > queued_timeout: 

1722 logger.info( 

1723 'slskd: stalled (no progress) title={!r} user={!r} ' 

1724 'bytes={} state={!r}', 

1725 song.get('name'), 

1726 username, 

1727 transferred, 

1728 transfer.get('state'), 

1729 ) 

1730 return None 

1731 elif time.monotonic() - poll.started > queued_timeout: 

1732 logger.info( 

1733 'slskd: queued timeout (transfer not started) title={!r} ' 

1734 'user={!r} file={!r}', 

1735 song.get('name'), 

1736 username, 

1737 _file_basename(filename)[:120], 

1738 ) 

1739 return None 

1740 

1741 if progress_cb is not None: 

1742 pct, message = _slskd_transfer_progress_pct( 

1743 transfer=transfer, 

1744 on_disk_bytes=on_disk_bytes, 

1745 expected_size=expected_size, 

1746 poll_attempt=attempt, 

1747 ) 

1748 if pct > last_reported_pct or attempt == 0: 

1749 last_reported_pct = pct 

1750 progress_cb(pct, message, 'slskd') 

1751 

1752 poll.sleep( 

1753 transfer, last_progress, queued_timeout, deadline, cancel_check 

1754 ) 

1755 

1756 return _find_on_disk_for_song( 

1757 roots, 

1758 song, 

1759 filename, 

1760 username=username, 

1761 expected_size=expected_size, 

1762 ) 

1763 

1764 

1765# ── Why slskd didn't deliver ─────────────────────────────────────────── 

1766# A download that slskd can't serve falls through to the next source. The 

1767# reason is kept for the thread that asked (one download per thread), so 

1768# the downloader can say why another source was used (see 

1769# downtify.slskd_misses). 

1770 

1771#: Reasons, in the order a download gets further: when several queries 

1772#: fail differently, the one that got furthest is reported. 

1773MISS_REASONS = ( 

1774 'not_configured', 

1775 'unreachable', 

1776 'search_failed', 

1777 'search_timeout', 

1778 'no_results', 

1779 'no_match', 

1780 'low_confidence', 

1781 'quality_filtered', 

1782 'timeout', 

1783 'transfer_failed', 

1784 'tag_mismatch', 

1785) 

1786 

1787_miss = threading.local() 

1788 

1789 

1790def take_miss() -> Optional[dict[str, str]]: 

1791 """Why the last :func:`download_from_slskd` on this thread found 

1792 nothing (``{reason, detail}``), once; ``None`` when it didn't fail or 

1793 was never called.""" 

1794 

1795 found = getattr(_miss, 'value', None) 

1796 _miss.value = None 

1797 return found 

1798 

1799 

1800def _missed(reason: str, detail: str = '') -> None: 

1801 """Remember why slskd found nothing, unless an earlier query of the 

1802 same download already got further. Returns ``None`` for ``return 

1803 _missed(...)``.""" 

1804 

1805 current = getattr(_miss, 'value', None) 

1806 if current is None or MISS_REASONS.index(reason) >= MISS_REASONS.index( 

1807 current['reason'] 

1808 ): 

1809 _miss.value = {'reason': reason, 'detail': str(detail)[:200]} 

1810 

1811 

1812def download_from_slskd( # noqa: PLR0914 # search, rank, enqueue, poll, finalize 

1813 song: dict[str, Any], 

1814 settings: dict[str, Any], 

1815 progress_cb: Optional[ProgressCallback] = None, 

1816 *, 

1817 cancel_check=None, 

1818) -> Optional[Path]: 

1819 _miss.value = None 

1820 if cancel_check: 

1821 cancel_check() 

1822 if not bool(settings.get('enabled')): 

1823 return None 

1824 client = SlskdClient(settings) 

1825 if not client.configured(): 

1826 logger.info( 

1827 'slskd: missing configuration title={!r}', song.get('name') 

1828 ) 

1829 return _missed('not_configured') 

1830 if not client.can_connect(): 

1831 logger.info( 

1832 'slskd: connectivity check failed base_url={!r}', client.base_url 

1833 ) 

1834 return _missed('unreachable') 

1835 

1836 output_dir = Path( 

1837 str( 

1838 settings.get('output_dir') 

1839 or settings.get('download_dir') 

1840 or '/downloads' 

1841 ) 

1842 ) 

1843 source_dir = Path( 

1844 str( 

1845 settings.get('source_dir') 

1846 or settings.get('download_dir') 

1847 or output_dir 

1848 ) 

1849 ) 

1850 spotify_row = snapshot_spotify_metadata(song) 

1851 queries = _slskd_search_queries(spotify_row) 

1852 if not queries: 

1853 return _missed('no_match', 'no title or artist to search for') 

1854 

1855 label = f'{song.get("name")} - {", ".join(song.get("artists") or [])}' 

1856 

1857 def report(pct: float, message: str) -> None: 

1858 if progress_cb is not None: 

1859 try: 

1860 text = ( 

1861 message 

1862 if str(message).lower().startswith('slskd') 

1863 else f'slskd · {message}' 

1864 ) 

1865 progress_cb(pct, text, 'slskd') 

1866 except Exception: 

1867 logger.opt(exception=True).debug( 

1868 'slskd progress callback error' 

1869 ) 

1870 

1871 deadline = _slskd_deadline(settings) 

1872 report(2.0, 'searching') 

1873 

1874 search_id = '' 

1875 

1876 # Hold the parallel slot for search, enqueue, and transfer. 

1877 with _slskd_semaphore(settings): 

1878 used_query = '' 

1879 candidates: list[dict[str, Any]] = [] 

1880 files: list[dict[str, Any]] = [] 

1881 min_score = _match_min_score(settings) 

1882 

1883 # Nobody answering any search may mean the server blocks one of 

1884 # its word combinations: then a few looser searches are added. 

1885 answered = False 

1886 loosened_from: Optional[int] = None 

1887 for index, query in enumerate(queries): 

1888 if ( 

1889 loosened_from is not None 

1890 and index >= loosened_from 

1891 and answered 

1892 ): 

1893 break 

1894 if ( 

1895 loosened_from is None 

1896 and index == len(queries) - 1 

1897 and not answered 

1898 ): 

1899 loosened_from = len(queries) 

1900 queries.extend(_blocked_phrase_queries(spotify_row, queries)) 

1901 if cancel_check: 

1902 cancel_check() 

1903 if _past_deadline(deadline): 

1904 logger.info( 

1905 'slskd: download timeout during search title={!r}', 

1906 song.get('name'), 

1907 ) 

1908 return _missed('search_timeout') 

1909 report(8.0, 'searching') 

1910 search_id = client.start_search(query) or '' 

1911 if not search_id: 

1912 _missed('search_failed') 

1913 continue 

1914 if not client.wait_search_complete( 

1915 search_id, 

1916 label, 

1917 on_poll=lambda pct: report(pct, 'searching'), 

1918 deadline=deadline, 

1919 **({'cancel_check': cancel_check} if cancel_check else {}), 

1920 ): 

1921 _missed('search_timeout') 

1922 client.delete_search(search_id) 

1923 search_id = '' 

1924 continue 

1925 raw_responses = client.search_responses(search_id) 

1926 if raw_responses: 

1927 answered = True 

1928 responses = _filter_slskd_responses(raw_responses) 

1929 if not responses and not _busy_responses(raw_responses): 

1930 _missed( 

1931 'no_results', 

1932 f'{len(raw_responses)} users answered, none with a free ' 

1933 'slot and an unlocked file' 

1934 if raw_responses 

1935 else 'nobody had it', 

1936 ) 

1937 client.delete_search(search_id) 

1938 search_id = '' 

1939 continue 

1940 

1941 ranked = _rank_slskd_candidates(song, responses, settings) 

1942 if not ranked and (busy := _busy_responses(raw_responses)): 

1943 ranked = _rank_slskd_candidates( 

1944 song, busy, settings, include_busy=True 

1945 ) 

1946 if ranked: 

1947 logger.info( 

1948 'slskd: only busy peers have {!r}; queueing', 

1949 song.get('name'), 

1950 ) 

1951 if not ranked: 

1952 ranked = _rank_slskd_candidates( 

1953 song, 

1954 responses, 

1955 settings, 

1956 allow_mix_variants=True, 

1957 ) 

1958 if ranked: 

1959 logger.info( 

1960 'slskd: using extended-mix last resort for query={!r} ' 

1961 'title={!r}', 

1962 query[:120], 

1963 song.get('name'), 

1964 ) 

1965 if not ranked: 

1966 logger.info( 

1967 'slskd: no matching audio for query={!r} title={!r} ' 

1968 'responses={}', 

1969 query[:120], 

1970 song.get('name'), 

1971 len(responses), 

1972 ) 

1973 _missed('no_match', f'{len(raw_responses)} users answered') 

1974 client.delete_search(search_id) 

1975 search_id = '' 

1976 continue 

1977 

1978 qualified = [ 

1979 row 

1980 for row in ranked 

1981 if int(row.get('match_score') or 0) >= min_score 

1982 ] 

1983 if not qualified: 

1984 top = ranked[0] 

1985 logger.info( 

1986 'slskd: low confidence for query={!r} title={!r} ' 

1987 'top_score={} top_file={!r} min_score={}', 

1988 query[:120], 

1989 song.get('name'), 

1990 top.get('match_score'), 

1991 _file_basename(str(top.get('filename') or '')), 

1992 min_score, 

1993 ) 

1994 _missed( 

1995 'low_confidence', 

1996 f'best match {top.get("match_score")}, needs {min_score}: ' 

1997 f'{_file_basename(str(top.get("filename") or ""))}', 

1998 ) 

1999 client.delete_search(search_id) 

2000 search_id = '' 

2001 continue 

2002 

2003 selected = _select_download_candidates(qualified, settings) 

2004 if not selected: 

2005 _missed( 

2006 'quality_filtered', 

2007 f'{len(qualified)} matching files, none passed the ' 

2008 'format and bitrate rules', 

2009 ) 

2010 logger.info( 

2011 'slskd: no files passed quality filters for query={!r} ' 

2012 'title={!r}', 

2013 query[:120], 

2014 song.get('name'), 

2015 ) 

2016 client.delete_search(search_id) 

2017 search_id = '' 

2018 continue 

2019 

2020 used_query = query 

2021 candidates = ranked 

2022 files = selected 

2023 break 

2024 

2025 if not files: 

2026 logger.info( 

2027 'slskd: no matching audio files title={!r} queries={}', 

2028 song.get('name'), 

2029 queries[:6], 

2030 ) 

2031 if search_id: 

2032 client.delete_search(search_id) 

2033 return None 

2034 

2035 pick = files[0] 

2036 logger.info( 

2037 'slskd: picked score={} reasons={} file={!r} user={!r} ' 

2038 'query={!r} ranked={} selected={} (download_attempts={})', 

2039 pick.get('match_score'), 

2040 ','.join(pick.get('match_reasons') or []), 

2041 _file_basename(str(pick.get('filename') or '')), 

2042 pick.get('username'), 

2043 used_query[:120], 

2044 len(candidates), 

2045 len(files), 

2046 int(settings.get('download_attempts') or 5), 

2047 ) 

2048 

2049 if _past_deadline(deadline): 

2050 client.delete_search(search_id) 

2051 logger.info( 

2052 'slskd: download timeout before transfer title={!r}', 

2053 song.get('name'), 

2054 ) 

2055 return _missed('timeout') 

2056 

2057 roots = _search_roots(settings, client) 

2058 

2059 def _root_key(path: Path) -> str: 

2060 try: 

2061 return str(path.resolve()) 

2062 except OSError: 

2063 return str(path) 

2064 

2065 root_keys = {_root_key(r) for r in roots} 

2066 if _root_key(source_dir) not in root_keys: 

2067 roots.insert(0, source_dir) 

2068 if _root_key(output_dir) not in root_keys: 

2069 roots.append(output_dir) 

2070 

2071 for attempt_idx, file_row in enumerate(files, start=1): 

2072 if cancel_check: 

2073 cancel_check() 

2074 if _past_deadline(deadline): 

2075 logger.info( 

2076 'slskd: download timeout before trying candidate {} title={!r}', 

2077 attempt_idx, 

2078 song.get('name'), 

2079 ) 

2080 break 

2081 

2082 username = str(file_row.get('username') or '') 

2083 filename = str(file_row.get('filename') or '') 

2084 if not client.enqueue_download(file_row): 

2085 logger.info( 

2086 'slskd: enqueue failed candidate={}/{} title={!r} user={!r} file={!r}', 

2087 attempt_idx, 

2088 len(files), 

2089 song.get('name'), 

2090 username, 

2091 _file_basename(filename)[:120], 

2092 ) 

2093 continue 

2094 

2095 try: 

2096 queued_size = int(file_row.get('size') or 0) 

2097 except (TypeError, ValueError): 

2098 queued_size = 0 

2099 

2100 report(36.0, f'queued ({attempt_idx}/{len(files)})') 

2101 

2102 found = _wait_for_slskd_file( 

2103 client, 

2104 song, 

2105 username, 

2106 filename, 

2107 settings, 

2108 roots, 

2109 expected_size=queued_size, 

2110 progress_cb=progress_cb, 

2111 **({'cancel_check': cancel_check} if cancel_check else {}), 

2112 deadline=deadline, 

2113 ) 

2114 if found is None: 

2115 found = _resolve_downloaded_file( 

2116 roots, 

2117 song, 

2118 filename, 

2119 username=username, 

2120 expected_size=queued_size, 

2121 ) 

2122 

2123 if found is not None: 

2124 if not verify_downloaded_file_matches_spotify( 

2125 found, spotify_row 

2126 ): 

2127 meta = read_audio_metadata(found) 

2128 mismatch_row = { 

2129 **spotify_row, 

2130 'name': str(meta.get('title') or ''), 

2131 'artists': list(meta.get('artists') or []), 

2132 'library_from_tags': True, 

2133 } 

2134 logger.info( 

2135 'slskd: tags mismatch after download {}; ' 

2136 'retaining source and trying next candidate ' 

2137 '({}/{}) file={!r}', 

2138 spotify_file_tag_mismatch_label(mismatch_row), 

2139 attempt_idx, 

2140 len(files), 

2141 _file_basename(filename)[:120], 

2142 ) 

2143 _missed( 

2144 'tag_mismatch', 

2145 f'{spotify_file_tag_mismatch_label(mismatch_row)}: ' 

2146 f'{_file_basename(filename)}', 

2147 ) 

2148 found = None 

2149 

2150 if found is not None: 

2151 if search_id: 

2152 client.delete_search(search_id) 

2153 return _finalize_slskd_path(found) 

2154 

2155 logger.info( 

2156 'slskd: candidate failed candidate={}/{} title={!r} user={!r} file={!r}', 

2157 attempt_idx, 

2158 len(files), 

2159 song.get('name'), 

2160 username, 

2161 _file_basename(filename)[:120], 

2162 ) 

2163 

2164 if search_id: 

2165 client.delete_search(search_id) 

2166 

2167 logger.info( 

2168 'slskd: all candidates failed title={!r} tried={}', 

2169 song.get('name'), 

2170 len(files), 

2171 ) 

2172 if _past_deadline(deadline): 

2173 return _missed('timeout', f'{len(files)} files tried') 

2174 return _missed( 

2175 'transfer_failed', 

2176 f'{len(files)} files tried: none arrived complete', 

2177 )