|
16 | 16 | logger = logging.getLogger(__name__) |
17 | 17 |
|
18 | 18 |
|
| 19 | +def _find_body_start(data: bytes, start: int) -> int: |
| 20 | + """Find the blank line separating headers from body, returning the index of the body start.""" |
| 21 | + crlf_pos = data.find(b"\r\n\r\n", start) |
| 22 | + if crlf_pos != -1: |
| 23 | + return crlf_pos + 4 |
| 24 | + |
| 25 | + lf_pos = data.find(b"\n\n", start) |
| 26 | + if lf_pos != -1: |
| 27 | + return lf_pos + 2 |
| 28 | + |
| 29 | + raise ValueError("Could not find header/body separator in audio part") |
| 30 | + |
| 31 | + |
19 | 32 | @dataclass |
20 | 33 | class SongMetadata: |
21 | 34 | title: str |
@@ -145,16 +158,7 @@ def _parse_multipart(self, stream: typing.Iterator[bytes]) -> MultipartResponse: |
145 | 158 | raise ValueError('Could not find audio part boundary') |
146 | 159 |
|
147 | 160 | # Find the start of audio data (after headers and empty line) |
148 | | - audio_start = second_boundary + len(boundary_bytes) |
149 | | - |
150 | | - # Skip past the headers to find the empty line (\n\n) |
151 | | - while audio_start < len(response_bytes) - 1: |
152 | | - if (response_bytes[audio_start] == 0x0A and |
153 | | - response_bytes[audio_start + 1] == 0x0A): |
154 | | - # Found \n\n - audio starts after this |
155 | | - audio_start += 2 |
156 | | - break |
157 | | - audio_start += 1 |
| 161 | + audio_start = _find_body_start(response_bytes, second_boundary + len(boundary_bytes)) |
158 | 162 |
|
159 | 163 | # Audio goes until the end (or until we find another boundary) |
160 | 164 | audio_buffer = response_bytes[audio_start:] |
@@ -281,16 +285,7 @@ async def _parse_multipart_async(self, stream: typing.AsyncIterator[bytes]) -> M |
281 | 285 | raise ValueError('Could not find audio part boundary') |
282 | 286 |
|
283 | 287 | # Find the start of audio data (after headers and empty line) |
284 | | - audio_start = second_boundary + len(boundary_bytes) |
285 | | - |
286 | | - # Skip past the headers to find the empty line (\n\n) |
287 | | - while audio_start < len(response_bytes) - 1: |
288 | | - if (response_bytes[audio_start] == 0x0A and |
289 | | - response_bytes[audio_start + 1] == 0x0A): |
290 | | - # Found \n\n - audio starts after this |
291 | | - audio_start += 2 |
292 | | - break |
293 | | - audio_start += 1 |
| 288 | + audio_start = _find_body_start(response_bytes, second_boundary + len(boundary_bytes)) |
294 | 289 |
|
295 | 290 | # Audio goes until the end (or until we find another boundary) |
296 | 291 | audio_buffer = response_bytes[audio_start:] |
|
0 commit comments