gem

a fork of khuxkm's gemini to web proxy
Log | Files | Refs

mimeparse.py (2263B)


      1 import string
      2 # Utility function to parse a MIME type
      3 def parse_mime(mimetype):
      4     mimetype = mimetype.strip()
      5     index = 0
      6     type = ""
      7     # type is everything before the /
      8     while index<len(mimetype) and mimetype[index]!="/":
      9         type+=mimetype[index]
     10         index+=1
     11     index+=1
     12     subtype = ""
     13     # subtype is everything after the slash and before the semicolon (if the latter exists)
     14     while index<len(mimetype) and mimetype[index]!=";":
     15         subtype+=mimetype[index]
     16         index+=1
     17     index+=1
     18     # if there's no semicolon, there are no params
     19     if index>=len(mimetype): return [type,subtype], dict()
     20     params = dict()
     21     while index<len(mimetype):
     22         # skip whitespace
     23         while index<len(mimetype) and mimetype[index] in string.whitespace:
     24             index+=1
     25         paramName = ""
     26         # the parameter name is everything before the = or ;
     27         while index<len(mimetype) and mimetype[index] not in "=;":
     28             paramName+=mimetype[index]
     29             index+=1
     30         # if the string is over or there isn't an equals sign, there's no param value
     31         if index>=len(mimetype) or mimetype[index]==";":
     32             index+=1
     33             params[paramName]=None
     34             continue
     35         # otherwise, grab the param value
     36         index+=1
     37         paramValue = ""
     38         if mimetype[index]=='"':
     39             index+=1
     40             while True:
     41                 while index<len(mimetype) and mimetype[index] not in '\\"':
     42                     paramValue+=mimetype[index]
     43                     index+=1
     44                 if index>=len(mimetype): break
     45                 c = mimetype[index]
     46                 index+=1
     47                 if c=="\\":
     48                     if index>=len(mimetype):
     49                         paramValue+=c
     50                         break
     51                     paramValue+=mimetype[index]
     52                     index+=1
     53                 else:
     54                     break
     55             # skip until next ;
     56             while index<len(mimetype) and mimetype[index]!=";": index+=1
     57         else:
     58             while index<len(mimetype) and mimetype[index]!=";":
     59                 paramValue+=mimetype[index]
     60                 index+=1
     61         if paramName: params[paramName]=paramValue
     62     return [type, subtype], params