2013-12-07 02:57:47 +01:00
|
|
|
import mimetypes
|
|
|
|
import os.path
|
2014-02-26 01:11:04 +01:00
|
|
|
import random
|
|
|
|
import string
|
2013-12-07 02:57:47 +01:00
|
|
|
|
|
|
|
from django.core.files.storage import default_storage
|
|
|
|
from django.template.defaultfilters import slugify
|
2015-04-22 21:56:40 +02:00
|
|
|
from django.utils.encoding import force_text
|
2013-12-07 02:57:47 +01:00
|
|
|
|
|
|
|
|
2014-08-24 19:43:20 +02:00
|
|
|
class NotAnImageException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2013-12-07 02:57:47 +01:00
|
|
|
def slugify_filename(filename):
|
2013-12-21 02:16:25 +01:00
|
|
|
""" Slugify filename """
|
2013-12-07 02:57:47 +01:00
|
|
|
name, ext = os.path.splitext(filename)
|
2014-02-26 01:11:04 +01:00
|
|
|
slugified = get_slugified_name(name)
|
|
|
|
return slugified + ext
|
|
|
|
|
|
|
|
|
|
|
|
def get_slugified_name(filename):
|
|
|
|
slugified = slugify(filename)
|
|
|
|
return slugified or get_random_string()
|
|
|
|
|
|
|
|
|
|
|
|
def get_random_string():
|
2015-02-06 23:55:52 +01:00
|
|
|
return ''.join(random.sample(string.ascii_lowercase * 6, 6))
|
2013-12-07 02:57:47 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_thumb_filename(file_name):
|
|
|
|
"""
|
|
|
|
Generate thumb filename by adding _thumb to end of
|
|
|
|
filename before . (if present)
|
|
|
|
"""
|
2015-04-22 21:56:40 +02:00
|
|
|
return force_text('{0}_thumb{1}').format(*os.path.splitext(file_name))
|
2013-12-07 02:57:47 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_image_format(extension):
|
|
|
|
mimetypes.init()
|
2014-02-28 01:17:28 +01:00
|
|
|
return mimetypes.types_map[extension.lower()]
|
2013-12-07 02:57:47 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_media_url(path):
|
|
|
|
"""
|
|
|
|
Determine system file's media URL.
|
|
|
|
"""
|
|
|
|
return default_storage.url(path)
|