OLD | NEW |
(Empty) | |
| 1 # Copyright (C) 2001-2007 Python Software Foundation |
| 2 # Author: Anthony Baxter |
| 3 # Contact: email-sig@python.org |
| 4 |
| 5 """Class representing audio/* type MIME documents.""" |
| 6 from __future__ import unicode_literals |
| 7 from __future__ import division |
| 8 from __future__ import absolute_import |
| 9 |
| 10 __all__ = ['MIMEAudio'] |
| 11 |
| 12 import sndhdr |
| 13 |
| 14 from io import BytesIO |
| 15 from future.backports.email import encoders |
| 16 from future.backports.email.mime.nonmultipart import MIMENonMultipart |
| 17 |
| 18 |
| 19 _sndhdr_MIMEmap = {'au' : 'basic', |
| 20 'wav' :'x-wav', |
| 21 'aiff':'x-aiff', |
| 22 'aifc':'x-aiff', |
| 23 } |
| 24 |
| 25 # There are others in sndhdr that don't have MIME types. :( |
| 26 # Additional ones to be added to sndhdr? midi, mp3, realaudio, wma?? |
| 27 def _whatsnd(data): |
| 28 """Try to identify a sound file type. |
| 29 |
| 30 sndhdr.what() has a pretty cruddy interface, unfortunately. This is why |
| 31 we re-do it here. It would be easier to reverse engineer the Unix 'file' |
| 32 command and use the standard 'magic' file, as shipped with a modern Unix. |
| 33 """ |
| 34 hdr = data[:512] |
| 35 fakefile = BytesIO(hdr) |
| 36 for testfn in sndhdr.tests: |
| 37 res = testfn(hdr, fakefile) |
| 38 if res is not None: |
| 39 return _sndhdr_MIMEmap.get(res[0]) |
| 40 return None |
| 41 |
| 42 |
| 43 class MIMEAudio(MIMENonMultipart): |
| 44 """Class for generating audio/* MIME documents.""" |
| 45 |
| 46 def __init__(self, _audiodata, _subtype=None, |
| 47 _encoder=encoders.encode_base64, **_params): |
| 48 """Create an audio/* type MIME document. |
| 49 |
| 50 _audiodata is a string containing the raw audio data. If this data |
| 51 can be decoded by the standard Python `sndhdr' module, then the |
| 52 subtype will be automatically included in the Content-Type header. |
| 53 Otherwise, you can specify the specific audio subtype via the |
| 54 _subtype parameter. If _subtype is not given, and no subtype can be |
| 55 guessed, a TypeError is raised. |
| 56 |
| 57 _encoder is a function which will perform the actual encoding for |
| 58 transport of the image data. It takes one argument, which is this |
| 59 Image instance. It should use get_payload() and set_payload() to |
| 60 change the payload to the encoded form. It should also add any |
| 61 Content-Transfer-Encoding or other headers to the message as |
| 62 necessary. The default encoding is Base64. |
| 63 |
| 64 Any additional keyword arguments are passed to the base class |
| 65 constructor, which turns them into parameters on the Content-Type |
| 66 header. |
| 67 """ |
| 68 if _subtype is None: |
| 69 _subtype = _whatsnd(_audiodata) |
| 70 if _subtype is None: |
| 71 raise TypeError('Could not find audio MIME subtype') |
| 72 MIMENonMultipart.__init__(self, 'audio', _subtype, **_params) |
| 73 self.set_payload(_audiodata) |
| 74 _encoder(self) |
OLD | NEW |