logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

mimetypes.py (22618B)


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