from typing import List, Sequence from .form_file_check_types import FileInfo # ASCII whitespace only, so all three languages trim the same characters. _SPACE = " \t\n\r\f\v" _MIME_PUNCTUATION = "!#$&^_.+-" def _lower(value: str) -> str: return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in value) def _upper(value: str) -> str: return "".join(chr(ord(c) - 32) if "a" <= c <= "z" else c for c in value) def _is_mime_name(value: str) -> bool: # RFC 6838's restricted-name characters. return value != "" and all( "a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9" or c in _MIME_PUNCTUATION for c in value ) def accept_tokens(accept: str) -> List[str]: """The accept attribute's tokens, trimmed and lower-cased, empty ones dropped. Anything that is not an extension, a MIME type or a type/* wildcard raises.""" tokens: List[str] = [] for raw in accept.split(","): token = _lower(raw.strip(_SPACE)) if token == "": continue ok = False if token.startswith("."): ext = token[1:] ok = ext != "" and "/" not in ext and not any(c in _SPACE for c in ext) else: slash = token.find("/") if slash > 0: kind, subtype = token[:slash], token[slash + 1 :] ok = _is_mime_name(kind) and (subtype == "*" or _is_mime_name(subtype)) if not ok: raise ValueError( 'accept token "%s" is not an extension (.pdf), a MIME type (application/pdf) or a wildcard (image/*)' % raw.strip(_SPACE) ) tokens.append(token) return tokens def describe_accept(tokens: Sequence[str]) -> str: """What the accepted types are called in an error message: "a PDF", "an image", "a PDF, JPG or PNG".""" words: List[str] = [] for token in tokens: if token.startswith("."): word = _upper(token[1:]) elif token.endswith("/*"): word = token[:-2] else: word = _upper(token[token.find("/") + 1 :]) if word not in words: words.append(word) listed = words[0] if len(words) == 1 else "%s or %s" % (", ".join(words[:-1]), words[-1]) first = words[0][0] # A lower-case word is said as a word; an initialism letter by letter. an = first in "aeiou" if "a" <= first <= "z" else first in "AEFHILMNORSX8" return "%s %s" % ("an" if an else "a", listed) def matches_accept(tokens: Sequence[str], file: FileInfo) -> bool: if not tokens: return True name = _lower(file.name) kind = _lower(file.mime_type) for token in tokens: if token.startswith("."): if name.endswith(token): return True elif token.endswith("/*"): if kind.startswith(token[:-1]): return True elif kind == token: return True return False def accepts_file(accept: str, file: FileInfo) -> bool: """Whether a browser's file chooser would offer this file for an accept attribute: by extension, exact MIME type or type/* wildcard, ignoring case. An empty accept takes anything.""" return matches_accept(accept_tokens(accept), file)