Debian Codegraph @

lib/utils/mimetype.py

raw
1 # -*- coding: utf-8 -*-
2 # This program is free software; you can redistribute it and/or modify
3 # it under the terms of the GNU General Public License as published by
4 # the Free Software Foundation; either version 2 of the License, or
5 # (at your option) any later version.
6 #
7 # This program is distributed in the hope that it will be useful,
8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 # GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License
13 # along with this program; if not, write to the Free Software
14 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
15 # MA 02110-1301, USA.
16 #
17 # Author: Mauro Soria
18
19 import re
20 import json
21 from typing_extensions import LiteralString
22
23 from defusedxml import ElementTree
24
25 from lib.core.settings import QUERY_STRING_REGEX
26
27
28 class MimeTypeUtils:
29 @staticmethod
30 def is_json(content):
31 try:
32 json.loads(content)
33 return True
34 except json.decoder.JSONDecodeError:
35 return False
36
37 @staticmethod
38 def is_xml(content):
39 try:
40 ElementTree.fromstring(content)
41 return True
42 except ElementTree.ParseError:
43 return False
44 except Exception:
45 return True
46
47 @staticmethod
48 def is_query_string(content):
49 if re.match(QUERY_STRING_REGEX, content):
50 return True
51
52 return False
53
54
55 def guess_mimetype(content) -> LiteralString:
56 if MimeTypeUtils.is_json(content):
57 return "application/json"
58 elif MimeTypeUtils.is_xml(content):
59 return "application/xml"
60 elif MimeTypeUtils.is_query_string(content):
61 return "application/x-www-form-urlencoded"
62 else:
63 return "text/plain"