Commit 17b5753b authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix Shazam proxy routing - pass proxy= directly to recognize()

The previous attempt (Shazam(http_client=ProxiedClient)) silently did
nothing: shazamio's recognize() already passes proxy=None explicitly
all the way down to the HTTP client's request(), so a kwargs.setdefault
on an already-present key was a no-op. recognize() itself accepts a
proxy= kwarg directly - use that instead, which is also the officially
supported extension point.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent f485f7ae
Pipeline #1309 failed with stage
......@@ -6,9 +6,7 @@ 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
......@@ -44,36 +42,18 @@ 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)
def _shazam_proxy() -> str | None:
"""The HTTPS_PROXY/HTTP_PROXY env vars this host's systemd unit already sets point at a
local HTTP CONNECT bridge -> SSH SOCKS5 tunnel -> an unrestricted relay, specifically built
to reach services blocked on this network (confirmed: `curl -x http://127.0.0.1:8118
https://amp.shazam.com/` gets a real response, while a direct connection even with DNS
bypassed via --resolve still fails - this is a network-level block on the destination
itself, not just DNS hijacking). shazamio's internal aiohttp client builds its session with
trust_env left at the default (False), so those env vars are never picked up automatically
- recognize()'s own `proxy=` kwarg is the one hook it exposes for this instead. A dev
machine with no tunnel configured (no env var set) gets None, i.e. unchanged direct
behavior."""
return os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or None
async def compute_fingerprint(file_path: str) -> str | None:
......@@ -94,8 +74,8 @@ async def identify_audio(file_path: str) -> list:
# 1. Shazamio
try:
shazam = _make_shazam()
out = await shazam.recognize(file_path)
shazam = Shazam()
out = await shazam.recognize(file_path, proxy=_shazam_proxy())
if 'track' in out:
t = out['track']
title = t.get('title', 'Unknown')
......
......@@ -2,7 +2,7 @@ import asyncio
import os
from src.services.music_identification import (
_ProxiedShazamHTTPClient,
_shazam_proxy,
fetch_lyrics,
fingerprint_hash,
identify_audio,
......@@ -27,36 +27,51 @@ 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."""
def test_shazam_proxy_reads_https_proxy_env_var():
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"
assert _shazam_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."""
def test_shazam_proxy_falls_back_to_http_proxy_env_var():
os.environ.pop("HTTPS_PROXY", None)
os.environ["HTTP_PROXY"] = "http://127.0.0.1:8118"
try:
assert _shazam_proxy() == "http://127.0.0.1:8118"
finally:
del os.environ["HTTP_PROXY"]
def test_shazam_proxy_is_none_on_a_dev_machine_with_no_tunnel_configured():
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={})
assert _shazam_proxy() is None
def test_identify_audio_passes_the_proxy_through_to_shazams_recognize(mocker):
"""Regression: shazamio's internal aiohttp client builds its session with trust_env left at
the default (False), so the HTTPS_PROXY/HTTP_PROXY env vars this host's systemd unit sets
(a tunnel specifically built to reach services blocked on this network) were never picked
up automatically. recognize()'s own `proxy=` kwarg is the hook that actually works - a
first attempt at this used Shazam(http_client=...) with kwargs.setdefault("proxy", ...),
which silently did nothing because shazamio's recognize() already passes proxy=None
explicitly all the way down, so the key always existed and setdefault was a no-op."""
os.environ["HTTPS_PROXY"] = "http://127.0.0.1:8118"
try:
shazam_instance = mocker.Mock()
shazam_instance.recognize = mocker.AsyncMock(return_value={})
mocker.patch("src.services.music_identification.Shazam", return_value=shazam_instance)
mocker.patch("src.services.music_identification.acoustid.match", return_value=[])
asyncio.run(identify_audio("/tmp/does-not-matter.mp3"))
shazam_instance.recognize.assert_called_once_with(
"/tmp/does-not-matter.mp3", proxy="http://127.0.0.1:8118"
)
client = _ProxiedShazamHTTPClient()
asyncio.run(client.request("GET", "https://amp.shazam.com/foo"))
assert "proxy" not in parent_request.call_args.kwargs
finally:
del os.environ["HTTPS_PROXY"]
def test_parse_lrc_basic_lines():
......
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