Skip to content

Commit

Permalink
Merge pull request #303 from aither64/pygments-content-type
Browse files Browse the repository at this point in the history
utils/upload: guess file content type also using pygments
  • Loading branch information
ThomasWaldmann authored May 23, 2023
2 parents f296e20 + 3ca2a32 commit 5df0245
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/bepasty/utils/upload.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import re
import time
import mimetypes
from pygments.lexers import get_lexer_for_filename
from pygments.util import ClassNotFound as NoPygmentsLexer
from werkzeug.exceptions import BadRequest, RequestEntityTooLarge

from flask import current_app
Expand Down Expand Up @@ -87,6 +89,15 @@ def filter_type(cls, ct, ct_hint, filename=None):
"""
if not ct and filename:
ct, encoding = mimetypes.guess_type(filename)

if not ct:
try:
lexer = get_lexer_for_filename(filename)
except NoPygmentsLexer:
pass
else:
if len(lexer.mimetypes) > 0:
ct = lexer.mimetypes[0]
if not ct:
return ct_hint, True
return cls._type_re.sub('', ct)[:50], False
Expand Down

0 comments on commit 5df0245

Please sign in to comment.