3 from django.utils.translation import ugettext as _
4 from django.utils.safestring import mark_safe
5 from time import gmtime, strftime, localtime, mktime, time
6 from django.core.files import File
7 from django.core.files.storage import default_storage
9 from urlparse import urlparse
12 from filebrowser.fb_settings import *
24 def _url_to_path(value):
27 Value has to be an URL relative to MEDIA URL or a full URL (including MEDIA_URL).
29 Returns a PATH relative to MEDIA_ROOT.
31 mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL))
32 value = mediaurl_re.sub('', value)
36 def _path_to_url(value):
39 Value has to be a PATH relative to MEDIA_ROOT.
41 Return an URL relative to MEDIA_ROOT.
43 mediaroot_re = re.compile(r'^(%s)' % (MEDIA_ROOT))
44 value = mediaroot_re.sub('', value)
45 return _url_join(MEDIA_URL, value)
48 def _dir_from_url(value):
50 Get the relative server directory from a URL.
51 URL has to be an absolute URL including MEDIA_URL or
52 an URL relative to MEDIA_URL.
55 mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL))
56 value = mediaurl_re.sub('', value)
57 directory_re = re.compile(r'^(%s)' % (DIRECTORY))
58 value = directory_re.sub('', value)
59 return os.path.split(value)[0]
62 def _get_version_path(value, version_prefix):
64 Construct the PATH to an Image version.
65 Value has to be server-path, relative to MEDIA_ROOT.
67 version_filename = filename + version_prefix + ext
68 Returns a path relative to MEDIA_ROOT.
70 if os.path.isfile(os.path.join(MEDIA_ROOT, value)):
71 path, filename = os.path.split(value)
72 filename, ext = os.path.splitext(filename)
73 version_filename = filename + "_" + version_prefix + ext
74 return os.path.join(VERSIONS_BASEDIR, path, version_filename)
79 def _sort_by_attr(seq, attr):
81 Sort the sequence of objects by object's attribute
84 seq - the list or any sequence (including immutable one) of objects to sort.
85 attr - the name of attribute to sort by
88 the sorted list of objects.
92 # Use the "Schwartzian transform"
93 # Create the auxiliary list of tuples where every i-th tuple has form
94 # (seq[i].attr, i, seq[i]) and sort it. The second item of tuple is needed not
95 # only to provide stable sorting, but mainly to eliminate comparison of objects
96 # (which can be expensive or prohibited) in case of equal attribute values.
97 intermed = map(None, map(getattr, seq, (attr,)*len(seq)), xrange(len(seq)), seq)
99 return map(operator.getitem, intermed, (-1,) * len(intermed))
102 def _url_join(*args):
103 if args[0].startswith("http://"):
108 arg = str(arg).replace("\\", "/")
109 arg_split = arg.split("/")
110 for elem in arg_split:
111 if elem != "" and elem != "http:":
112 url = url + elem + "/"
113 # remove trailing slash for filenames
114 if os.path.splitext(args[-1])[1]:
115 url = url.rstrip("/")
124 if os.path.isabs(path) or not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path)):
129 def _get_file(path, filename):
134 if not os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)) and not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path, filename)):
139 def _get_breadcrumbs(query, path, title):
147 for item in path.split(os.sep):
148 dir_query = os.path.join(dir_query,item)
149 breadcrumbs.append([item,dir_query])
151 breadcrumbs.append([title,''])
155 def _get_filterdate(filterDate, dateTime):
161 dateYear = strftime("%Y", gmtime(dateTime))
162 dateMonth = strftime("%m", gmtime(dateTime))
163 dateDay = strftime("%d", gmtime(dateTime))
164 if filterDate == 'today' and int(dateYear) == int(localtime()[0]) and int(dateMonth) == int(localtime()[1]) and int(dateDay) == int(localtime()[2]): returnvalue = 'true'
165 elif filterDate == 'thismonth' and dateTime >= time()-2592000: returnvalue = 'true'
166 elif filterDate == 'thisyear' and int(dateYear) == int(localtime()[0]): returnvalue = 'true'
167 elif filterDate == 'past7days' and dateTime >= time()-604800: returnvalue = 'true'
168 elif filterDate == '': returnvalue = 'true'
172 def _get_settings_var():
174 Get settings variables used for FileBrowser listing.
179 settings_var['DEBUG'] = DEBUG
180 settings_var['MEDIA_ROOT'] = MEDIA_ROOT
181 settings_var['MEDIA_URL'] = MEDIA_URL
182 settings_var['DIRECTORY'] = DIRECTORY
184 settings_var['URL_FILEBROWSER_MEDIA'] = URL_FILEBROWSER_MEDIA
185 settings_var['PATH_FILEBROWSER_MEDIA'] = PATH_FILEBROWSER_MEDIA
187 settings_var['URL_TINYMCE'] = URL_TINYMCE
188 settings_var['PATH_TINYMCE'] = PATH_TINYMCE
189 # Extensions/Formats (for FileBrowseField)
190 settings_var['EXTENSIONS'] = EXTENSIONS
191 settings_var['SELECT_FORMATS'] = SELECT_FORMATS
193 settings_var['VERSIONS_BASEDIR'] = VERSIONS_BASEDIR
194 settings_var['VERSIONS'] = VERSIONS
195 settings_var['ADMIN_VERSIONS'] = ADMIN_VERSIONS
196 settings_var['ADMIN_THUMBNAIL'] = ADMIN_THUMBNAIL
197 # FileBrowser Options
198 settings_var['MAX_UPLOAD_SIZE'] = MAX_UPLOAD_SIZE
200 settings_var['CONVERT_FILENAME'] = CONVERT_FILENAME
204 def _handle_file_upload(path, file):
209 file_path = os.path.join(path, file.name)
210 uploadedfile = default_storage.save(file_path, file)
214 def _get_file_type(filename):
216 Get file type as defined in EXTENSIONS.
219 file_extension = os.path.splitext(filename)[1].lower()
221 for k,v in EXTENSIONS.iteritems():
223 if file_extension == extension.lower():
228 def _is_selectable(filename, selecttype):
230 Get select type as defined in FORMATS.
233 file_extension = os.path.splitext(filename)[1].lower()
235 for k,v in SELECT_FORMATS.iteritems():
237 if file_extension == extension.lower():
238 select_types.append(k)
242 def _version_generator(value, version_prefix, force=None):
244 Generate Version for an Image.
245 value has to be a serverpath relative to MEDIA_ROOT.
248 # PIL's Error "Suspension not allowed here" work around:
249 # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html
251 from PIL import ImageFile
254 from PIL import ImageFile
257 ImageFile.MAXBLOCK = IMAGE_MAXBLOCK # default is 64k
260 im = Image.open(os.path.join(MEDIA_ROOT, value))
261 version_path = _get_version_path(value, version_prefix)
262 absolute_version_path = os.path.join(MEDIA_ROOT, version_path)
263 version_dir = os.path.split(absolute_version_path)[0]
264 if not os.path.isdir(version_dir):
265 os.makedirs(version_dir)
266 os.chmod(version_dir, 0775)
267 version = scale_and_crop(im, VERSIONS[version_prefix]['width'], VERSIONS[version_prefix]['height'], VERSIONS[version_prefix]['opts'])
269 version.save(absolute_version_path, quality=90, optimize=1)
271 version.save(absolute_version_path, quality=90)
277 def scale_and_crop(im, width, height, opts):
278 x, y = [float(v) for v in im.size]
282 xr = float(x*height/y)
286 yr = float(y*width/x)
293 if r < 1.0 or (r > 1.0 and 'upscale' in opts):
294 im = im.resize((int(x*r), int(y*r)), resample=Image.ANTIALIAS)
297 x, y = [float(v) for v in im.size]
298 ex, ey = (x-min(x, xr))/2, (y-min(y, yr))/2
300 im = im.crop((int(ex), int(ey), int(x-ex), int(y-ey)))
302 scale_and_crop.valid_options = ('crop', 'upscale')
305 def _convert_filename(value):
307 return value.replace(" ", "_").lower()