Skip to content

Commit 209fc85

Browse files
committed
Refactor the mime audio module
1 parent cbb0aa7 commit 209fc85

File tree

1 file changed

+8
-54
lines changed

1 file changed

+8
-54
lines changed

Lib/email/mime/audio.py

Lines changed: 8 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
__all__ = ['MIMEAudio']
88

9-
from io import BytesIO
109
from email import encoders
1110
from email.mime.nonmultipart import MIMENonMultipart
1211

@@ -36,65 +35,20 @@ def __init__(self, _audiodata, _subtype=None,
3635
constructor, which turns them into parameters on the Content-Type
3736
header.
3837
"""
39-
if _subtype is None:
40-
_subtype = _what(_audiodata)
41-
if _subtype is None:
42-
raise TypeError('Could not find audio MIME subtype')
38+
_subtype = _subtype or _infer_subtype(_audiodata)
4339
MIMENonMultipart.__init__(self, 'audio', _subtype, policy=policy,
4440
**_params)
4541
self.set_payload(_audiodata)
4642
_encoder(self)
4743

4844

49-
_rules = []
50-
51-
52-
# Originally from the sndhdr module.
53-
#
54-
# There are others in sndhdr that don't have MIME types. :(
55-
# Additional ones to be added to sndhdr? midi, mp3, realaudio, wma??
56-
def _what(data):
57-
# Try to identify a sound file type.
58-
#
59-
# sndhdr.what() had a pretty cruddy interface, unfortunately. This is why
60-
# we re-do it here. It would be easier to reverse engineer the Unix 'file'
61-
# command and use the standard 'magic' file, as shipped with a modern Unix.
62-
hdr = data[:512]
63-
fakefile = BytesIO(hdr)
64-
for testfn in _rules:
65-
if res := testfn(hdr, fakefile):
66-
return res
67-
else:
68-
return None
69-
70-
71-
def rule(rulefunc):
72-
_rules.append(rulefunc)
73-
return rulefunc
74-
75-
76-
@rule
77-
def _aiff(h, f):
78-
if not h.startswith(b'FORM'):
79-
return None
80-
if h[8:12] in {b'AIFC', b'AIFF'}:
45+
def _infer_subtype(h: bytes) -> str:
46+
if h.startswith(b'FORM') and h[8:12] in (b'AIFC', b'AIFF'):
8147
return 'x-aiff'
82-
else:
83-
return None
84-
85-
86-
@rule
87-
def _au(h, f):
88-
if h.startswith(b'.snd'):
48+
elif h.startswith(b'.snd'):
8949
return 'basic'
90-
else:
91-
return None
92-
50+
elif h.startswith(b'RIFF') and h[8:12] == b'WAVE' and h[12:16] == b'fmt ':
51+
# 'RIFF' <len> 'WAVE' 'fmt ' <len>
52+
return 'x-wav'
9353

94-
@rule
95-
def _wav(h, f):
96-
# 'RIFF' <len> 'WAVE' 'fmt ' <len>
97-
if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ':
98-
return None
99-
else:
100-
return "x-wav"
54+
raise TypeError('Could not find audio MIME subtype')

0 commit comments

Comments
 (0)