7 from django.utils.translation import ugettext as _
8 from django.utils.safestring import mark_safe
9 from time import gmtime, strftime, localtime, mktime, time
10 from django.core.files import File
11 from django.core.files.storage import default_storage
13 from urlparse import urlparse
16 from filebrowser.fb_settings import *
28 def _url_to_path(value):
31 Value has to be an URL relative to MEDIA URL or a full URL (including MEDIA_URL).
33 Returns a PATH relative to MEDIA_ROOT.
35 print "URL2PATH", repr(value)
36 mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL))
37 value = mediaurl_re.sub(u'', value)
41 def _path_to_url(value):
44 Value has to be a PATH relative to MEDIA_ROOT.
46 Return an URL relative to MEDIA_ROOT.
48 mediaroot_re = re.compile(r'^(%s)' % (MEDIA_ROOT))
49 value = mediaroot_re.sub('', value)
50 return _url_join(MEDIA_URL, value)
53 def _dir_from_url(value):
55 Get the relative server directory from a URL.
56 URL has to be an absolute URL including MEDIA_URL or
57 an URL relative to MEDIA_URL.
60 mediaurl_re = re.compile(r'^(%s)' % (MEDIA_URL))
61 value = mediaurl_re.sub('', value)
62 directory_re = re.compile(r'^(%s)' % (DIRECTORY))
63 value = directory_re.sub('', value)
64 return os.path.split(value)[0]
67 def _get_version_path(value, version_prefix):
69 Construct the PATH to an Image version.
70 Value has to be server-path, relative to MEDIA_ROOT.
72 version_filename = filename + version_prefix + ext
73 Returns a path relative to MEDIA_ROOT.
75 if os.path.isfile(os.path.join(MEDIA_ROOT, value)):
76 path, filename = os.path.split(value)
77 filename, ext = os.path.splitext(filename)
78 version_filename = filename + u"_" + version_prefix + ext
79 return os.path.join(VERSIONS_BASEDIR, path, version_filename)
85 if args[0].startswith(u"http://"):
90 arg = unicode(arg).replace(u"\\", u"/")
91 arg_split = arg.split(u"/")
92 for elem in arg_split:
93 if elem != u"" and elem != u"http:":
94 url = url + elem + u"/"
95 # remove trailing slash for filenames
96 if os.path.splitext(args[-1])[1]:
97 url = url.rstrip(u"/")
106 if os.path.isabs(path) or not os.path.isdir(os.path.join(MEDIA_ROOT, DIRECTORY, path)):
111 def _get_file(path, filename):
116 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)):
121 def _get_breadcrumbs(query, path, title):
129 for item in path.split(os.sep):
130 dir_query = os.path.join(dir_query, item)
131 breadcrumbs.append([item, dir_query])
133 breadcrumbs.append([title, ''])
137 def _get_filterdate(filterDate, dateTime):
142 dateYear = strftime("%Y", gmtime(dateTime))
143 dateMonth = strftime("%m", gmtime(dateTime))
144 dateDay = strftime("%d", gmtime(dateTime))
146 if filterDate == 'today' and int(dateYear) == int(localtime()[0]) and int(dateMonth) == int(localtime()[1]) and int(dateDay) == int(localtime()[2]):
149 if filterDate == 'thismonth' and dateTime >= time() - 2592000:
152 if filterDate == 'thisyear' and int(dateYear) == int(localtime()[0]):
155 if filterDate == 'past7days' and dateTime >= time() - 604800:
158 return 'true' if filterDate == '' else ''
161 def _get_settings_var():
163 Get settings variables used for FileBrowser listing.
168 settings_var['DEBUG'] = DEBUG
169 settings_var['MEDIA_ROOT'] = MEDIA_ROOT
170 settings_var['MEDIA_URL'] = MEDIA_URL
171 settings_var['DIRECTORY'] = DIRECTORY
173 settings_var['URL_FILEBROWSER_MEDIA'] = URL_FILEBROWSER_MEDIA
174 settings_var['PATH_FILEBROWSER_MEDIA'] = PATH_FILEBROWSER_MEDIA
176 settings_var['URL_TINYMCE'] = URL_TINYMCE
177 settings_var['PATH_TINYMCE'] = PATH_TINYMCE
178 # Extensions/Formats (for FileBrowseField)
179 settings_var['EXTENSIONS'] = EXTENSIONS
180 settings_var['SELECT_FORMATS'] = SELECT_FORMATS
182 settings_var['VERSIONS_BASEDIR'] = VERSIONS_BASEDIR
183 settings_var['VERSIONS'] = VERSIONS
184 settings_var['ADMIN_VERSIONS'] = ADMIN_VERSIONS
185 settings_var['ADMIN_THUMBNAIL'] = ADMIN_THUMBNAIL
186 # FileBrowser Options
187 settings_var['MAX_UPLOAD_SIZE'] = MAX_UPLOAD_SIZE
189 settings_var['CONVERT_FILENAME'] = CONVERT_FILENAME
193 def _handle_file_upload(path, file):
198 file_path = os.path.join(path, file.name)
199 uploadedfile = default_storage.save(file_path, file)
203 def _get_file_type(filename):
205 Get file type as defined in EXTENSIONS.
207 file_extension = os.path.splitext(filename)[1].lower()
208 for ftype, ext_list in EXTENSIONS.iteritems():
209 if file_extension in map(str.lower, ext_list):
214 def _is_selectable(filename, selecttype):
216 Get select type as defined in FORMATS.
219 file_extension = os.path.splitext(filename)[1].lower()
221 for k, v in SELECT_FORMATS.iteritems():
223 if file_extension == extension.lower():
224 select_types.append(k)
228 def _version_generator(value, version_prefix, force=None):
230 Generate Version for an Image.
231 value has to be a serverpath relative to MEDIA_ROOT.
234 # PIL's Error "Suspension not allowed here" work around:
235 # s. http://mail.python.org/pipermail/image-sig/1999-August/000816.html
237 from PIL import ImageFile
240 from PIL import ImageFile
243 ImageFile.MAXBLOCK = IMAGE_MAXBLOCK # default is 64k
246 im = Image.open(os.path.join(MEDIA_ROOT, value))
247 version_path = _get_version_path(value, version_prefix)
248 absolute_version_path = os.path.join(MEDIA_ROOT, version_path)
249 version_dir = os.path.split(absolute_version_path)[0]
250 if not os.path.isdir(version_dir):
251 os.makedirs(version_dir)
252 os.chmod(version_dir, 0775)
253 version = scale_and_crop(im, VERSIONS[version_prefix]['width'], VERSIONS[version_prefix]['height'], VERSIONS[version_prefix]['opts'])
255 version.save(absolute_version_path, quality=90, optimize=1)
257 version.save(absolute_version_path, quality=90)
263 def scale_and_crop(im, width, height, opts):
264 x, y = [float(v) for v in im.size]
268 xr = float(x * height / y)
272 yr = float(y * width / x)
275 r = max(xr / x, yr / y)
277 r = min(xr / x, yr / y)
279 if r < 1.0 or (r > 1.0 and 'upscale' in opts):
280 im = im.resize((int(x * r), int(y * r)), resample=Image.ANTIALIAS)
283 x, y = [float(v) for v in im.size]
284 ex, ey = (x - min(x, xr)) / 2, (y - min(y, yr)) / 2
286 im = im.crop((int(ex), int(ey), int(x - ex), int(y - ey)))
288 scale_and_crop.valid_options = ('crop', 'upscale')
291 def _convert_filename(value):
293 return value.replace(" ", "_").lower()