Debian Codegraph @

lib-python/3/mimetypes.py

raw symbols SCIP
1 """Guess the MIME type of a file.
2
3 This module defines two useful functions:
4
5 guess_type(url, strict=True) -- guess the MIME type and encoding of a URL.
6
7 guess_extension(type, strict=True) -- guess the extension for a given MIME type.
8
9 It also contains the following, for tuning the behavior:
10
11 Data:
12
13 knownfiles -- list of files to parse
14 inited -- flag set when init() has been called
15 suffix_map -- dictionary mapping suffixes to suffixes
16 encodings_map -- dictionary mapping suffixes to encodings
17 types_map -- dictionary mapping suffixes to types
18
19 Functions:
20
21 init([files]) -- parse a list of files, default knownfiles (on Windows, the
22 default values are taken from the registry)
23 read_mime_types(file) -- parse one file, return a dictionary or None
24 """
25
26 import os
27 import sys
28 import posixpath
29 import urllib.parse
30
31 try:
32 from _winapi import _mimetypes_read_windows_registry
33 except ImportError:
34 _mimetypes_read_windows_registry = None
35
36 try:
37 import winreg as _winreg
38 except ImportError:
39 _winreg = None
40
41 __all__ = [
42 "knownfiles", "inited", "MimeTypes",
43 "guess_type", "guess_all_extensions", "guess_extension",
44 "add_type", "init", "read_mime_types",
45 "suffix_map", "encodings_map", "types_map", "common_types"
46 ]
47
48 knownfiles = [
49 "/etc/mime.types",
50 "/etc/httpd/mime.types", # Mac OS X
51 "/etc/httpd/conf/mime.types", # Apache
52 "/etc/apache/mime.types", # Apache 1
53 "/etc/apache2/mime.types", # Apache 2
54 "/usr/local/etc/httpd/conf/mime.types",
55 "/usr/local/lib/netscape/mime.types",
56 "/usr/local/etc/httpd/conf/mime.types", # Apache 1.2
57 "/usr/local/etc/mime.types", # Apache 1.3
58 ]
59
60 inited = False
61 _db = None
62
63
64 class MimeTypes:
65 """MIME-types datastore.
66
67 This datastore can handle information from mime.types-style files
68 and supports basic determination of MIME type from a filename or
69 URL, and can guess a reasonable extension given a MIME type.
70 """
71
72 def __init__(self, filenames=(), strict=True):
73 if not inited:
74 init()
75 self.encodings_map = _encodings_map_default.copy()
76 self.suffix_map = _suffix_map_default.copy()
77 self.types_map = ({}, {}) # dict for (non-strict, strict)
78 self.types_map_inv = ({}, {})
79 for (ext, type) in _types_map_default.items():
80 self.add_type(type, ext, True)
81 for (ext, type) in _common_types_default.items():
82 self.add_type(type, ext, False)
83 for name in filenames:
84 self.read(name, strict)
85
86 def add_type(self, type, ext, strict=True):
87 """Add a mapping between a type and an extension.
88
89 When the extension is already known, the new
90 type will replace the old one. When the type
91 is already known the extension will be added
92 to the list of known extensions.
93
94 If strict is true, information will be added to
95 list of standard types, else to the list of non-standard
96 types.
97 """
98 self.types_map[strict][ext] = type
99 exts = self.types_map_inv[strict].setdefault(type, [])
100 if ext not in exts:
101 exts.append(ext)
102
103 def guess_type(self, url, strict=True):
104 """Guess the type of a file which is either a URL or a path-like object.
105
106 Return value is a tuple (type, encoding) where type is None if
107 the type can't be guessed (no or unknown suffix) or a string
108 of the form type/subtype, usable for a MIME Content-type
109 header; and encoding is None for no encoding or the name of
110 the program used to encode (e.g. compress or gzip). The
111 mappings are table driven. Encoding suffixes are case
112 sensitive; type suffixes are first tried case sensitive, then
113 case insensitive.
114
115 The suffixes .tgz, .taz and .tz (case sensitive!) are all
116 mapped to '.tar.gz'. (This is table-driven too, using the
117 dictionary suffix_map.)
118
119 Optional `strict' argument when False adds a bunch of commonly found,
120 but non-standard types.
121 """
122 url = os.fspath(url)
123 p = urllib.parse.urlparse(url)
124 if p.scheme and len(p.scheme) > 1:
125 scheme = p.scheme
126 url = p.path
127 else:
128 scheme = None
129 url = os.path.splitdrive(url)[1]
130 if scheme == 'data':
131 # syntax of data URLs:
132 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
133 # mediatype := [ type "/" subtype ] *( ";" parameter )
134 # data := *urlchar
135 # parameter := attribute "=" value
136 # type/subtype defaults to "text/plain"
137 comma = url.find(',')
138 if comma < 0:
139 # bad data URL
140 return None, None
141 semi = url.find(';', 0, comma)
142 if semi >= 0:
143 type = url[:semi]
144 else:
145 type = url[:comma]
146 if '=' in type or '/' not in type:
147 type = 'text/plain'
148 return type, None # never compressed, so encoding is None
149 base, ext = posixpath.splitext(url)
150 while (ext_lower := ext.lower()) in self.suffix_map:
151 base, ext = posixpath.splitext(base + self.suffix_map[ext_lower])
152 # encodings_map is case sensitive
153 if ext in self.encodings_map:
154 encoding = self.encodings_map[ext]
155 base, ext = posixpath.splitext(base)
156 else:
157 encoding = None
158 ext = ext.lower()
159 types_map = self.types_map[True]
160 if ext in types_map:
161 return types_map[ext], encoding
162 elif strict:
163 return None, encoding
164 types_map = self.types_map[False]
165 if ext in types_map:
166 return types_map[ext], encoding
167 else:
168 return None, encoding
169
170 def guess_all_extensions(self, type, strict=True):
171 """Guess the extensions for a file based on its MIME type.
172
173 Return value is a list of strings giving the possible filename
174 extensions, including the leading dot ('.'). The extension is not
175 guaranteed to have been associated with any particular data stream,
176 but would be mapped to the MIME type `type' by guess_type().
177
178 Optional `strict' argument when false adds a bunch of commonly found,
179 but non-standard types.
180 """
181 type = type.lower()
182 extensions = list(self.types_map_inv[True].get(type, []))
183 if not strict:
184 for ext in self.types_map_inv[False].get(type, []):
185 if ext not in extensions:
186 extensions.append(ext)
187 return extensions
188
189 def guess_extension(self, type, strict=True):
190 """Guess the extension for a file based on its MIME type.
191
192 Return value is a string giving a filename extension,
193 including the leading dot ('.'). The extension is not
194 guaranteed to have been associated with any particular data
195 stream, but would be mapped to the MIME type `type' by
196 guess_type(). If no extension can be guessed for `type', None
197 is returned.
198
199 Optional `strict' argument when false adds a bunch of commonly found,
200 but non-standard types.
201 """
202 extensions = self.guess_all_extensions(type, strict)
203 if not extensions:
204 return None
205 return extensions[0]
206
207 def read(self, filename, strict=True):
208 """
209 Read a single mime.types-format file, specified by pathname.
210
211 If strict is true, information will be added to
212 list of standard types, else to the list of non-standard
213 types.
214 """
215 with open(filename, encoding='utf-8') as fp:
216 self.readfp(fp, strict)
217
218 def readfp(self, fp, strict=True):
219 """
220 Read a single mime.types-format file.
221
222 If strict is true, information will be added to
223 list of standard types, else to the list of non-standard
224 types.
225 """
226 while 1:
227 line = fp.readline()
228 if not line:
229 break
230 words = line.split()
231 for i in range(len(words)):
232 if words[i][0] == '#':
233 del words[i:]
234 break
235 if not words:
236 continue
237 type, suffixes = words[0], words[1:]
238 for suff in suffixes:
239 self.add_type(type, '.' + suff, strict)
240
241 def read_windows_registry(self, strict=True):
242 """
243 Load the MIME types database from Windows registry.
244
245 If strict is true, information will be added to
246 list of standard types, else to the list of non-standard
247 types.
248 """
249
250 if not _mimetypes_read_windows_registry and not _winreg:
251 return
252
253 add_type = self.add_type
254 if strict:
255 add_type = lambda type, ext: self.add_type(type, ext, True)
256
257 # Accelerated function if it is available
258 if _mimetypes_read_windows_registry:
259 _mimetypes_read_windows_registry(add_type)
260 elif _winreg:
261 self._read_windows_registry(add_type)
262
263 @classmethod
264 def _read_windows_registry(cls, add_type):
265 def enum_types(mimedb):
266 i = 0
267 while True:
268 try:
269 ctype = _winreg.EnumKey(mimedb, i)
270 except OSError:
271 break
272 else:
273 if '\0' not in ctype:
274 yield ctype
275 i += 1
276
277 with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, '') as hkcr:
278 for subkeyname in enum_types(hkcr):
279 try:
280 with _winreg.OpenKey(hkcr, subkeyname) as subkey:
281 # Only check file extensions
282 if not subkeyname.startswith("."):
283 continue
284 # raises OSError if no 'Content Type' value
285 mimetype, datatype = _winreg.QueryValueEx(
286 subkey, 'Content Type')
287 if datatype != _winreg.REG_SZ:
288 continue
289 add_type(mimetype, subkeyname)
290 except OSError:
291 continue
292
293 def guess_type(url, strict=True):
294 """Guess the type of a file based on its URL.
295
296 Return value is a tuple (type, encoding) where type is None if the
297 type can't be guessed (no or unknown suffix) or a string of the
298 form type/subtype, usable for a MIME Content-type header; and
299 encoding is None for no encoding or the name of the program used
300 to encode (e.g. compress or gzip). The mappings are table
301 driven. Encoding suffixes are case sensitive; type suffixes are
302 first tried case sensitive, then case insensitive.
303
304 The suffixes .tgz, .taz and .tz (case sensitive!) are all mapped
305 to ".tar.gz". (This is table-driven too, using the dictionary
306 suffix_map).
307
308 Optional `strict' argument when false adds a bunch of commonly found, but
309 non-standard types.
310 """
311 if _db is None:
312 init()
313 return _db.guess_type(url, strict)
314
315
316 def guess_all_extensions(type, strict=True):
317 """Guess the extensions for a file based on its MIME type.
318
319 Return value is a list of strings giving the possible filename
320 extensions, including the leading dot ('.'). The extension is not
321 guaranteed to have been associated with any particular data
322 stream, but would be mapped to the MIME type `type' by
323 guess_type(). If no extension can be guessed for `type', None
324 is returned.
325
326 Optional `strict' argument when false adds a bunch of commonly found,
327 but non-standard types.
328 """
329 if _db is None:
330 init()
331 return _db.guess_all_extensions(type, strict)
332
333 def guess_extension(type, strict=True):
334 """Guess the extension for a file based on its MIME type.
335
336 Return value is a string giving a filename extension, including the
337 leading dot ('.'). The extension is not guaranteed to have been
338 associated with any particular data stream, but would be mapped to the
339 MIME type `type' by guess_type(). If no extension can be guessed for
340 `type', None is returned.
341
342 Optional `strict' argument when false adds a bunch of commonly found,
343 but non-standard types.
344 """
345 if _db is None:
346 init()
347 return _db.guess_extension(type, strict)
348
349 def add_type(type, ext, strict=True):
350 """Add a mapping between a type and an extension.
351
352 When the extension is already known, the new
353 type will replace the old one. When the type
354 is already known the extension will be added
355 to the list of known extensions.
356
357 If strict is true, information will be added to
358 list of standard types, else to the list of non-standard
359 types.
360 """
361 if _db is None:
362 init()
363 return _db.add_type(type, ext, strict)
364
365
366 def init(files=None):
367 global suffix_map, types_map, encodings_map, common_types
368 global inited, _db
369 inited = True # so that MimeTypes.__init__() doesn't call us again
370
371 if files is None or _db is None:
372 db = MimeTypes()
373 # Quick return if not supported
374 db.read_windows_registry()
375
376 if files is None:
377 files = knownfiles
378 else:
379 files = knownfiles + list(files)
380 else:
381 db = _db
382
383 for file in files:
384 if os.path.isfile(file):
385 db.read(file)
386 encodings_map = db.encodings_map
387 suffix_map = db.suffix_map
388 types_map = db.types_map[True]
389 common_types = db.types_map[False]
390 # Make the DB a global variable now that it is fully initialized
391 _db = db
392
393
394 def read_mime_types(file):
395 try:
396 f = open(file, encoding='utf-8')
397 except OSError:
398 return None
399 with f:
400 db = MimeTypes()
401 db.readfp(f, True)
402 return db.types_map[True]
403
404
405 def _default_mime_types():
406 global suffix_map, _suffix_map_default
407 global encodings_map, _encodings_map_default
408 global types_map, _types_map_default
409 global common_types, _common_types_default
410
411 suffix_map = _suffix_map_default = {
412 '.svgz': '.svg.gz',
413 '.tgz': '.tar.gz',
414 '.taz': '.tar.gz',
415 '.tz': '.tar.gz',
416 '.tbz2': '.tar.bz2',
417 '.txz': '.tar.xz',
418 }
419
420 encodings_map = _encodings_map_default = {
421 '.gz': 'gzip',
422 '.Z': 'compress',
423 '.bz2': 'bzip2',
424 '.xz': 'xz',
425 '.br': 'br',
426 }
427
428 # Before adding new types, make sure they are either registered with IANA,
429 # at http://www.iana.org/assignments/media-types
430 # or extensions, i.e. using the x- prefix
431
432 # If you add to these, please keep them sorted by mime type.
433 # Make sure the entry with the preferred file extension for a particular mime type
434 # appears before any others of the same mimetype.
435 types_map = _types_map_default = {
436 '.js' : 'application/javascript',
437 '.mjs' : 'application/javascript',
438 '.json' : 'application/json',
439 '.webmanifest': 'application/manifest+json',
440 '.doc' : 'application/msword',
441 '.dot' : 'application/msword',
442 '.wiz' : 'application/msword',
443 '.nq' : 'application/n-quads',
444 '.nt' : 'application/n-triples',
445 '.bin' : 'application/octet-stream',
446 '.a' : 'application/octet-stream',
447 '.dll' : 'application/octet-stream',
448 '.exe' : 'application/octet-stream',
449 '.o' : 'application/octet-stream',
450 '.obj' : 'application/octet-stream',
451 '.so' : 'application/octet-stream',
452 '.oda' : 'application/oda',
453 '.pdf' : 'application/pdf',
454 '.p7c' : 'application/pkcs7-mime',
455 '.ps' : 'application/postscript',
456 '.ai' : 'application/postscript',
457 '.eps' : 'application/postscript',
458 '.trig' : 'application/trig',
459 '.m3u' : 'application/vnd.apple.mpegurl',
460 '.m3u8' : 'application/vnd.apple.mpegurl',
461 '.xls' : 'application/vnd.ms-excel',
462 '.xlb' : 'application/vnd.ms-excel',
463 '.ppt' : 'application/vnd.ms-powerpoint',
464 '.pot' : 'application/vnd.ms-powerpoint',
465 '.ppa' : 'application/vnd.ms-powerpoint',
466 '.pps' : 'application/vnd.ms-powerpoint',
467 '.pwz' : 'application/vnd.ms-powerpoint',
468 '.wasm' : 'application/wasm',
469 '.bcpio' : 'application/x-bcpio',
470 '.cpio' : 'application/x-cpio',
471 '.csh' : 'application/x-csh',
472 '.dvi' : 'application/x-dvi',
473 '.gtar' : 'application/x-gtar',
474 '.hdf' : 'application/x-hdf',
475 '.h5' : 'application/x-hdf5',
476 '.latex' : 'application/x-latex',
477 '.mif' : 'application/x-mif',
478 '.cdf' : 'application/x-netcdf',
479 '.nc' : 'application/x-netcdf',
480 '.p12' : 'application/x-pkcs12',
481 '.pfx' : 'application/x-pkcs12',
482 '.ram' : 'application/x-pn-realaudio',
483 '.pyc' : 'application/x-python-code',
484 '.pyo' : 'application/x-python-code',
485 '.sh' : 'application/x-sh',
486 '.shar' : 'application/x-shar',
487 '.swf' : 'application/x-shockwave-flash',
488 '.sv4cpio': 'application/x-sv4cpio',
489 '.sv4crc' : 'application/x-sv4crc',
490 '.tar' : 'application/x-tar',
491 '.tcl' : 'application/x-tcl',
492 '.tex' : 'application/x-tex',
493 '.texi' : 'application/x-texinfo',
494 '.texinfo': 'application/x-texinfo',
495 '.roff' : 'application/x-troff',
496 '.t' : 'application/x-troff',
497 '.tr' : 'application/x-troff',
498 '.man' : 'application/x-troff-man',
499 '.me' : 'application/x-troff-me',
500 '.ms' : 'application/x-troff-ms',
501 '.ustar' : 'application/x-ustar',
502 '.src' : 'application/x-wais-source',
503 '.xsl' : 'application/xml',
504 '.rdf' : 'application/xml',
505 '.wsdl' : 'application/xml',
506 '.xpdl' : 'application/xml',
507 '.zip' : 'application/zip',
508 '.3gp' : 'audio/3gpp',
509 '.3gpp' : 'audio/3gpp',
510 '.3g2' : 'audio/3gpp2',
511 '.3gpp2' : 'audio/3gpp2',
512 '.aac' : 'audio/aac',
513 '.adts' : 'audio/aac',
514 '.loas' : 'audio/aac',
515 '.ass' : 'audio/aac',
516 '.au' : 'audio/basic',
517 '.snd' : 'audio/basic',
518 '.mp3' : 'audio/mpeg',
519 '.mp2' : 'audio/mpeg',
520 '.opus' : 'audio/opus',
521 '.aif' : 'audio/x-aiff',
522 '.aifc' : 'audio/x-aiff',
523 '.aiff' : 'audio/x-aiff',
524 '.ra' : 'audio/x-pn-realaudio',
525 '.wav' : 'audio/x-wav',
526 '.avif' : 'image/avif',
527 '.bmp' : 'image/bmp',
528 '.gif' : 'image/gif',
529 '.ief' : 'image/ief',
530 '.jpg' : 'image/jpeg',
531 '.jpe' : 'image/jpeg',
532 '.jpeg' : 'image/jpeg',
533 '.heic' : 'image/heic',
534 '.heif' : 'image/heif',
535 '.png' : 'image/png',
536 '.svg' : 'image/svg+xml',
537 '.tiff' : 'image/tiff',
538 '.tif' : 'image/tiff',
539 '.ico' : 'image/vnd.microsoft.icon',
540 '.ras' : 'image/x-cmu-raster',
541 '.pnm' : 'image/x-portable-anymap',
542 '.pbm' : 'image/x-portable-bitmap',
543 '.pgm' : 'image/x-portable-graymap',
544 '.ppm' : 'image/x-portable-pixmap',
545 '.rgb' : 'image/x-rgb',
546 '.xbm' : 'image/x-xbitmap',
547 '.xpm' : 'image/x-xpixmap',
548 '.xwd' : 'image/x-xwindowdump',
549 '.eml' : 'message/rfc822',
550 '.mht' : 'message/rfc822',
551 '.mhtml' : 'message/rfc822',
552 '.nws' : 'message/rfc822',
553 '.css' : 'text/css',
554 '.csv' : 'text/csv',
555 '.html' : 'text/html',
556 '.htm' : 'text/html',
557 '.n3' : 'text/n3',
558 '.txt' : 'text/plain',
559 '.bat' : 'text/plain',
560 '.c' : 'text/plain',
561 '.h' : 'text/plain',
562 '.ksh' : 'text/plain',
563 '.pl' : 'text/plain',
564 '.srt' : 'text/plain',
565 '.rtx' : 'text/richtext',
566 '.tsv' : 'text/tab-separated-values',
567 '.vtt' : 'text/vtt',
568 '.py' : 'text/x-python',
569 '.etx' : 'text/x-setext',
570 '.sgm' : 'text/x-sgml',
571 '.sgml' : 'text/x-sgml',
572 '.vcf' : 'text/x-vcard',
573 '.xml' : 'text/xml',
574 '.mp4' : 'video/mp4',
575 '.mpeg' : 'video/mpeg',
576 '.m1v' : 'video/mpeg',
577 '.mpa' : 'video/mpeg',
578 '.mpe' : 'video/mpeg',
579 '.mpg' : 'video/mpeg',
580 '.mov' : 'video/quicktime',
581 '.qt' : 'video/quicktime',
582 '.webm' : 'video/webm',
583 '.avi' : 'video/x-msvideo',
584 '.movie' : 'video/x-sgi-movie',
585 }
586
587 # These are non-standard types, commonly found in the wild. They will
588 # only match if strict=0 flag is given to the API methods.
589
590 # Please sort these too
591 common_types = _common_types_default = {
592 '.rtf' : 'application/rtf',
593 '.midi': 'audio/midi',
594 '.mid' : 'audio/midi',
595 '.jpg' : 'image/jpg',
596 '.pict': 'image/pict',
597 '.pct' : 'image/pict',
598 '.pic' : 'image/pict',
599 '.webp': 'image/webp',
600 '.xul' : 'text/xul',
601 }
602
603
604 _default_mime_types()
605
606
607 def _main():
608 import getopt
609
610 USAGE = """\
611 Usage: mimetypes.py [options] type
612
613 Options:
614 --help / -h -- print this message and exit
615 --lenient / -l -- additionally search of some common, but non-standard
616 types.
617 --extension / -e -- guess extension instead of type
618
619 More than one type argument may be given.
620 """
621
622 def usage(code, msg=''):
623 print(USAGE)
624 if msg: print(msg)
625 sys.exit(code)
626
627 try:
628 opts, args = getopt.getopt(sys.argv[1:], 'hle',
629 ['help', 'lenient', 'extension'])
630 except getopt.error as msg:
631 usage(1, msg)
632
633 strict = 1
634 extension = 0
635 for opt, arg in opts:
636 if opt in ('-h', '--help'):
637 usage(0)
638 elif opt in ('-l', '--lenient'):
639 strict = 0
640 elif opt in ('-e', '--extension'):
641 extension = 1
642 for gtype in args:
643 if extension:
644 guess = guess_extension(gtype, strict)
645 if not guess: print("I don't know anything about type", gtype)
646 else: print(guess)
647 else:
648 guess, encoding = guess_type(gtype, strict)
649 if not guess: print("I don't know anything about type", gtype)
650 else: print('type:', guess, 'encoding:', encoding)
651
652
653 if __name__ == '__main__':
654 _main()