Commit f485f7ae authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Route Shazam's HTTP calls through the configured proxy tunnel

Shazam identification has been failing on prod (network-level block on
amp.shazam.com - confirmed DNS-hijacked AND SNI-blocked directly). A
proxy tunnel (SSH SOCKS5 -> privoxy -> HTTPS_PROXY env var) was already
built and working for exactly this, but shazamio's own aiohttp client
builds its session with trust_env left at the default (False), so those
env vars were silently ignored. Shazam() accepts an injectable
http_client - subclass it to force proxy= onto every request when one's
configured; a no-proxy dev machine behaves exactly as before.

This matters more now that short 5-second mic-listen clips are involved:
AcoustID (the only path that was actually reaching out) matches full
tracks reliably but frequently returns zero candidates for a bare 5s
clip, which is exactly what Discovery's mic button sends.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 54534bce
Pipeline #1307 canceled with stage
import asyncio
import hashlib
import os
import re
import acoustid
import aiohttp
import musicbrainzngs
import syncedlyrics
from aiohttp_retry import ExponentialRetry
from shazamio import Shazam
from shazamio.client import HTTPClient
from src.core.config import logger, ACOUSTID_API_KEY, GEMINI_API_KEY
import google.generativeai as genai
import json
......@@ -41,6 +44,38 @@ async def _fetch_cover_art_archive_url(release_id: str) -> str | None:
logger.error(f"Cover Art Archive lookup failed for release {release_id}: {e}")
return None
class _ProxiedShazamHTTPClient(HTTPClient):
"""shazamio's own HTTPClient wraps an aiohttp_retry.RetryClient with trust_env left at its
default (False) - the HTTPS_PROXY/HTTP_PROXY env vars this host's systemd unit already sets
(pointing at a local HTTP CONNECT bridge -> SSH SOCKS5 tunnel -> an unrestricted relay,
specifically built to reach services blocked on this network) were therefore silently
ignored, even though the tunnel itself works - confirmed with `curl -x
http://127.0.0.1:8118 https://amp.shazam.com/` getting a real response from Shazam, while a
direct connection (bypassing DNS too, via --resolve) still fails: this is a network-level
block on the destination itself, not just DNS hijacking, so nothing short of actually using
the tunnel fixes it. Injecting `proxy=` into every request is the one hook shazamio exposes
for this (Shazam(http_client=...)) without forking the library."""
async def request(self, method, url, *args, **kwargs):
proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
if proxy:
kwargs.setdefault("proxy", proxy)
return await super().request(method, url, *args, **kwargs)
def _make_shazam() -> Shazam:
# Mirrors shazamio's own Shazam.__init__ default retry_options exactly - only the
# http_client class changes, so retry/backoff behavior is unaffected by this.
http_client = _ProxiedShazamHTTPClient(
retry_options=ExponentialRetry(
attempts=20,
max_timeout=60,
statuses={500, 502, 503, 504, 429},
),
)
return Shazam(http_client=http_client)
async def compute_fingerprint(file_path: str) -> str | None:
"""Local Chromaprint fingerprint of the audio content - no network call. Used as the
cache key so re-uploads of the same song skip identification entirely. Returns None if
......@@ -59,7 +94,7 @@ async def identify_audio(file_path: str) -> list:
# 1. Shazamio
try:
shazam = Shazam()
shazam = _make_shazam()
out = await shazam.recognize(file_path)
if 'track' in out:
t = out['track']
......
import asyncio
import os
from src.services.music_identification import fetch_lyrics, fingerprint_hash, identify_audio, parse_lrc
from src.services.music_identification import (
_ProxiedShazamHTTPClient,
fetch_lyrics,
fingerprint_hash,
identify_audio,
parse_lrc,
)
def test_fingerprint_hash_is_fixed_length_regardless_of_input_size():
......@@ -20,6 +27,38 @@ def test_fingerprint_hash_is_deterministic_and_input_sensitive():
assert fingerprint_hash("input-a") != fingerprint_hash("input-b")
def test_shazam_http_client_routes_through_the_proxy_when_env_var_set(mocker):
"""Regression: shazamio's own HTTPClient builds its aiohttp RetryClient with trust_env left
at the default (False), so the HTTPS_PROXY/HTTP_PROXY env vars this host's systemd unit
already sets (a tunnel specifically built to reach services blocked on this network) were
silently ignored - Shazam identification kept failing even though the tunnel itself works.
_ProxiedShazamHTTPClient is the fix: inject proxy= explicitly since shazamio exposes no
other hook for it."""
os.environ["HTTPS_PROXY"] = "http://127.0.0.1:8118"
try:
parent_request = mocker.patch(
"src.services.music_identification.HTTPClient.request", new=mocker.AsyncMock(return_value={})
)
client = _ProxiedShazamHTTPClient()
asyncio.run(client.request("GET", "https://amp.shazam.com/foo"))
assert parent_request.call_args.kwargs.get("proxy") == "http://127.0.0.1:8118"
finally:
del os.environ["HTTPS_PROXY"]
def test_shazam_http_client_leaves_requests_alone_with_no_proxy_configured(mocker):
"""Dev machines with no tunnel set up (no HTTPS_PROXY/HTTP_PROXY) must behave exactly like
unmodified shazamio - no proxy kwarg should be injected at all, not even proxy=None."""
for var in ("HTTPS_PROXY", "HTTP_PROXY"):
os.environ.pop(var, None)
parent_request = mocker.patch(
"src.services.music_identification.HTTPClient.request", new=mocker.AsyncMock(return_value={})
)
client = _ProxiedShazamHTTPClient()
asyncio.run(client.request("GET", "https://amp.shazam.com/foo"))
assert "proxy" not in parent_request.call_args.kwargs
def test_parse_lrc_basic_lines():
lrc = "[00:12.34]First line\n[00:15.00]Second line"
assert parse_lrc(lrc) == [[12.34, "First line"], [15.0, "Second line"]]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment