This repository has been archived on 2024-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
Bebop/bebop/mime.py

45 lines
1.2 KiB
Python
Raw Permalink Normal View History

2021-03-14 00:04:55 +01:00
"""Basic MIME utilities (RFC 2046)."""
from dataclasses import dataclass
from typing import Optional
DEFAULT_CHARSET = "utf-8"
@dataclass
class MimeType:
main_type: str
sub_type: str
parameters: dict
2021-04-17 22:59:54 +02:00
@property
def short(self):
return f"{self.main_type or '*'}/{self.sub_type or '*'}"
2021-03-14 00:04:55 +01:00
@property
def charset(self):
return self.parameters.get("charset", DEFAULT_CHARSET)
@staticmethod
def from_str(mime_string) -> Optional["MimeType"]:
"""Parse a MIME string into a MimeType instance, or None on error."""
if ";" in mime_string:
2021-05-24 20:10:04 +02:00
type_str, *param_strs = mime_string.split(";")
2021-03-14 00:04:55 +01:00
parameters = {}
2021-05-24 20:10:04 +02:00
for param in map(lambda s: s.strip().lower(), param_strs):
2021-03-14 00:04:55 +01:00
if param.count("=") != 1:
return None
param_name, param_value = param.split("=")
parameters[param_name] = param_value
else:
type_str = mime_string.strip()
parameters = {}
if type_str.count("/") != 1:
return None
main_type, sub_type = type_str.split("/")
return MimeType(main_type, sub_type, parameters)
DEFAULT_MIME_TYPE = MimeType("text", "gemini", {"charset": DEFAULT_CHARSET})