7 from django.shortcuts import render_to_response, HttpResponse
8 from django.template import RequestContext as Context
9 from django.http import HttpResponseRedirect
10 from django.contrib.admin.views.decorators import staff_member_required
11 from django.views.decorators.cache import never_cache
12 from django.utils.translation import ugettext as _
13 from django.conf import settings
14 from django import forms
15 from django.core.urlresolvers import reverse
16 from django.core.exceptions import ImproperlyConfigured
17 from django.dispatch import Signal
18 from django.views.decorators.csrf import csrf_exempt
20 from django.utils.encoding import smart_unicode, smart_str
23 from filebrowser.fb_settings import *
25 from filebrowser.functions import (
26 _url_to_path, _path_to_url, _get_path, _get_file, _get_version_path,
27 _get_breadcrumbs, _get_filterdate, _get_settings_var, _handle_file_upload,
28 _get_file_type, _url_join, _convert_filename)
30 from filebrowser.templatetags.fb_tags import query_helper
31 from filebrowser.base import FileObject
32 from filebrowser.decorators import flash_login_required
34 # Precompile regular expressions
38 filter_re.append(re.compile(exp))
39 for k, v in VERSIONS.iteritems():
40 exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST))
41 filter_re.append(re.compile(exp))
46 Browse Files/Directories.
51 path = _get_path(query.get('dir', ''))
52 directory = _get_path('')
55 msg = _('Directory/File does not exist.')
56 request.user.message_set.create(message=msg)
58 # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
59 raise ImproperlyConfigured(_("Error finding upload directory: %s. Maybe it does not exist?" % os.path.join(MEDIA_ROOT, DIRECTORY)))
60 redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
61 return HttpResponseRedirect(redirect_url)
62 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
65 results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0}
67 for k, v in EXTENSIONS.iteritems():
70 dir_list = os.listdir(abs_path)
72 # print "LISTING FILES: ", dir_list
75 # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
76 filtered = file.startswith('.')
77 for re_prefix in filter_re:
78 if re_prefix.search(file):
82 results_var['results_total'] += 1
85 fileobject = FileObject(os.path.join(smart_str(DIRECTORY), smart_str(path), smart_str(file)))
89 if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and _get_filterdate(request.GET.get('filter_date', ''), fileobject.date):
91 if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()):
96 files.append(fileobject)
97 results_var['results_current'] += 1
99 if fileobject.filetype == 'Image':
100 results_var['images_total'] += 1
101 if fileobject.filetype != 'Folder':
102 results_var['delete_total'] += 1
103 elif fileobject.filetype == 'Folder' and fileobject.is_empty:
104 results_var['delete_total'] += 1
105 if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]:
106 results_var['select_total'] += 1
107 elif not query.get('type'):
108 results_var['select_total'] += 1
111 if fileobject.filetype:
112 counter[fileobject.filetype] += 1
115 files.sort(key=lambda e: getattr(e, request.GET.get('o', DEFAULT_ORDER)))
116 if request.GET.get('ot') == "desc":
119 return render_to_response('filebrowser/index.html', {
122 'results_var': results_var,
125 'title': _(u'FileBrowser'),
126 'settings_var': _get_settings_var(),
127 'breadcrumbs': _get_breadcrumbs(query, path, ''),
128 }, context_instance=Context(request))
129 browse = staff_member_required(never_cache(browse))
133 filebrowser_pre_createdir = Signal(providing_args=["path", "dirname"])
134 filebrowser_post_createdir = Signal(providing_args=["path", "dirname"])
142 from filebrowser.forms import MakeDirForm
146 path = _get_path(query.get('dir', ''))
148 msg = _('Directory/File does not exist.')
149 request.user.message_set.create(message=msg)
150 return HttpResponseRedirect(reverse("fb_browse"))
151 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
153 if request.method == 'POST':
154 form = MakeDirForm(abs_path, request.POST)
156 server_path = os.path.join(abs_path, form.cleaned_data['dir_name'])
159 filebrowser_pre_createdir.send(sender=request, path=path, dirname=form.cleaned_data['dir_name'])
161 os.mkdir(server_path)
162 os.chmod(server_path, 0775)
164 filebrowser_post_createdir.send(sender=request, path=path, dirname=form.cleaned_data['dir_name'])
166 msg = _('The Folder %s was successfully created.') % (form.cleaned_data['dir_name'])
167 request.user.message_set.create(message=msg)
168 # on redirect, sort by date desc to see the new directory on top of the list
169 # remove filter in order to actually _see_ the new folder
170 redirect_url = reverse("fb_browse") + query_helper(query, "ot=desc,o=date", "ot,o,filter_type,filter_date,q")
171 return HttpResponseRedirect(redirect_url)
172 except OSError, (errno, strerror):
174 form.errors['dir_name'] = forms.util.ErrorList([_('Permission denied.')])
176 form.errors['dir_name'] = forms.util.ErrorList([_('Error creating directory.')])
178 form = MakeDirForm(abs_path)
180 return render_to_response('filebrowser/makedir.html', {
183 'title': _(u'New Folder'),
184 'settings_var': _get_settings_var(),
185 'breadcrumbs': _get_breadcrumbs(query, path, _(u'New Folder')),
186 }, context_instance=Context(request))
187 mkdir = staff_member_required(never_cache(mkdir))
196 from django.http import parse_cookie
200 path = _get_path(query.get('dir', ''))
202 msg = _('Directory/File does not exist.')
203 request.user.message_set.create(message=msg)
204 return HttpResponseRedirect(reverse("fb_browse"))
205 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
207 # SESSION (used for flash-uploading)
208 cookie_dict = parse_cookie(request.META.get('HTTP_COOKIE', ''))
209 engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
210 session_key = cookie_dict.get(settings.SESSION_COOKIE_NAME, None)
212 return render_to_response('filebrowser/upload.html', {
214 'title': _(u'Select files to upload'),
215 'settings_var': _get_settings_var(),
216 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Upload')),
217 'session_key': session_key,
218 }, context_instance=Context(request))
219 upload = staff_member_required(never_cache(upload))
223 def _check_file(request):
225 Check if file already exists on the server.
228 from django.utils import simplejson
230 folder = request.POST.get('folder')
231 fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload"))
232 folder = fb_uploadurl_re.sub('', folder)
235 if request.method == 'POST':
236 for k, v in request.POST.items():
238 v = _convert_filename(v)
239 if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, v)):
242 return HttpResponse(simplejson.dumps(fileArray))
246 filebrowser_pre_upload = Signal(providing_args=["path", "file"])
247 filebrowser_post_upload = Signal(providing_args=["path", "file"])
250 def _upload_file(request):
252 Upload file to the server.
256 from django.core.files.move import file_move_safe
258 if request.method == 'POST':
259 folder = request.POST.get('folder')
260 fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload"))
261 folder = fb_uploadurl_re.sub('', folder)
262 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, folder)
264 filedata = request.FILES['Filedata']
265 filedata.name = _convert_filename(filedata.name)
267 filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata)
269 uploadedfile = _handle_file_upload(abs_path, filedata)
271 # if file already exists
272 if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, filedata.name)):
273 old_file = os.path.join(abs_path, filedata.name)
274 new_file = os.path.join(abs_path, uploadedfile)
275 file_move_safe(new_file, old_file)
277 filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=FileObject(os.path.join(DIRECTORY, folder, filedata.name)))
278 return HttpResponse('True')
279 _upload_file = csrf_exempt(flash_login_required(_upload_file))
283 filebrowser_pre_delete = Signal(providing_args=["path", "filename"])
284 filebrowser_post_delete = Signal(providing_args=["path", "filename"])
289 Delete existing File/Directory.
291 When trying to delete a Directory, the Directory has to be empty.
296 path = _get_path(query.get('dir', ''))
297 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
298 if path is None or filename is None:
299 msg = _('Directory/File does not exist.')
300 request.user.message_set.create(message=msg)
301 return HttpResponseRedirect(reverse("fb_browse"))
302 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
306 if request.GET.get('filetype') != "Folder":
307 relative_server_path = os.path.join(DIRECTORY, path, filename)
310 filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
311 # DELETE IMAGE VERSIONS/THUMBNAILS
312 for version in VERSIONS:
314 os.unlink(os.path.join(MEDIA_ROOT, _get_version_path(relative_server_path, version)))
318 os.unlink(os.path.join(abs_path, filename))
320 filebrowser_post_delete.send(sender=request, path=path, filename=filename)
322 msg = _('The file %s was successfully deleted.') % (filename.lower())
323 request.user.message_set.create(message=msg)
324 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
325 return HttpResponseRedirect(redirect_url)
327 # todo: define error message
332 filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
334 os.rmdir(os.path.join(abs_path, filename))
336 filebrowser_post_delete.send(sender=request, path=path, filename=filename)
338 msg = _('The directory %s was successfully deleted.') % (filename.lower())
339 request.user.message_set.create(message=msg)
340 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
341 return HttpResponseRedirect(redirect_url)
343 # todo: define error message
347 request.user.message_set.create(message=msg)
349 return render_to_response('filebrowser/index.html', {
351 'file': request.GET.get('filename', ''),
353 'settings_var': _get_settings_var(),
354 'breadcrumbs': _get_breadcrumbs(query, dir_name, ''),
355 }, context_instance=Context(request))
356 delete = staff_member_required(never_cache(delete))
360 filebrowser_pre_rename = Signal(providing_args=["path", "filename"])
361 filebrowser_post_rename = Signal(providing_args=["path", "filename"])
366 Rename existing File/Directory.
368 Includes renaming existing Image Versions/Thumbnails.
371 from filebrowser.forms import RenameForm
375 path = _get_path(query.get('dir', ''))
376 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
377 if path is None or filename is None:
378 msg = _('Directory/File does not exist.')
379 request.user.message_set.create(message=msg)
380 return HttpResponseRedirect(reverse("fb_browse"))
381 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
382 file_extension = os.path.splitext(filename)[1].lower()
384 if request.method == 'POST':
385 form = RenameForm(abs_path, file_extension, request.POST)
387 relative_server_path = os.path.join(DIRECTORY, path, filename)
388 new_relative_server_path = os.path.join(DIRECTORY, path, form.cleaned_data['name'] + file_extension)
391 filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
392 # DELETE IMAGE VERSIONS/THUMBNAILS
393 # regenerating versions/thumbs will be done automatically
394 for version in VERSIONS:
396 os.unlink(os.path.join(MEDIA_ROOT, _get_version_path(relative_server_path, version)))
400 os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path))
402 filebrowser_post_delete.send(sender=request, path=path, filename=filename)
404 msg = _('Renaming was successful.')
405 request.user.message_set.create(message=msg)
406 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename")
407 return HttpResponseRedirect(redirect_url)
408 except OSError, (errno, strerror):
409 form.errors['name'] = forms.util.ErrorList([_('Error.')])
411 form = RenameForm(abs_path, file_extension)
413 return render_to_response('filebrowser/rename.html', {
416 'file_extension': file_extension,
417 'title': _(u'Rename "%s"') % filename,
418 'settings_var': _get_settings_var(),
419 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Rename')),
420 }, context_instance=Context(request))
421 rename = staff_member_required(never_cache(rename))
424 def versions(request):
426 Show all Versions for an Image according to ADMIN_VERSIONS.
431 path = _get_path(query.get('dir', ''))
432 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
433 if path is None or filename is None:
434 msg = _('Directory/File does not exist.')
435 request.user.message_set.create(message=msg)
436 return HttpResponseRedirect(reverse("fb_browse"))
437 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
439 return render_to_response('filebrowser/versions.html', {
440 'original': _path_to_url(os.path.join(DIRECTORY, path, filename)),
442 'title': _(u'Versions for "%s"') % filename,
443 'settings_var': _get_settings_var(),
444 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Versions for "%s"') % filename),
445 }, context_instance=Context(request))
447 versions = staff_member_required(never_cache(versions))