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.
255 from django.core.files.move import file_move_safe
257 if request.method == 'POST':
258 folder = request.POST.get('folder')
259 fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload"))
260 folder = fb_uploadurl_re.sub('', folder)
261 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, folder)
263 filedata = request.FILES['Filedata']
264 filedata.name = _convert_filename(filedata.name)
266 filebrowser_pre_upload.send(sender=request, path=request.POST.get('folder'), file=filedata)
268 uploadedfile = _handle_file_upload(abs_path, filedata)
270 # if file already exists
271 if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, filedata.name)):
272 old_file = os.path.join(abs_path, filedata.name)
273 new_file = os.path.join(abs_path, uploadedfile)
274 file_move_safe(new_file, old_file)
276 filebrowser_post_upload.send(sender=request, path=request.POST.get('folder'), file=FileObject(os.path.join(DIRECTORY, folder, filedata.name)))
277 return HttpResponse('True')
278 _upload_file = csrf_exempt(flash_login_required(_upload_file))
282 filebrowser_pre_delete = Signal(providing_args=["path", "filename"])
283 filebrowser_post_delete = Signal(providing_args=["path", "filename"])
288 Delete existing File/Directory.
290 When trying to delete a Directory, the Directory has to be empty.
295 path = _get_path(query.get('dir', ''))
296 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
297 if path is None or filename is None:
298 msg = _('Directory/File does not exist.')
299 request.user.message_set.create(message=msg)
300 return HttpResponseRedirect(reverse("fb_browse"))
301 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
305 if request.GET.get('filetype') != "Folder":
306 relative_server_path = os.path.join(DIRECTORY, path, filename)
309 filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
310 # DELETE IMAGE VERSIONS/THUMBNAILS
311 for version in VERSIONS:
313 os.unlink(os.path.join(MEDIA_ROOT, _get_version_path(relative_server_path, version)))
317 os.unlink(os.path.join(abs_path, filename))
319 filebrowser_post_delete.send(sender=request, path=path, filename=filename)
321 msg = _('The file %s was successfully deleted.') % (filename.lower())
322 request.user.message_set.create(message=msg)
323 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
324 return HttpResponseRedirect(redirect_url)
326 # todo: define error message
331 filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
333 os.rmdir(os.path.join(abs_path, filename))
335 filebrowser_post_delete.send(sender=request, path=path, filename=filename)
337 msg = _('The directory %s was successfully deleted.') % (filename.lower())
338 request.user.message_set.create(message=msg)
339 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
340 return HttpResponseRedirect(redirect_url)
342 # todo: define error message
346 request.user.message_set.create(message=msg)
348 return render_to_response('filebrowser/index.html', {
350 'file': request.GET.get('filename', ''),
352 'settings_var': _get_settings_var(),
353 'breadcrumbs': _get_breadcrumbs(query, dir_name, ''),
354 }, context_instance=Context(request))
355 delete = staff_member_required(never_cache(delete))
359 filebrowser_pre_rename = Signal(providing_args=["path", "filename"])
360 filebrowser_post_rename = Signal(providing_args=["path", "filename"])
365 Rename existing File/Directory.
367 Includes renaming existing Image Versions/Thumbnails.
370 from filebrowser.forms import RenameForm
374 path = _get_path(query.get('dir', ''))
375 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
376 if path is None or filename is None:
377 msg = _('Directory/File does not exist.')
378 request.user.message_set.create(message=msg)
379 return HttpResponseRedirect(reverse("fb_browse"))
380 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
381 file_extension = os.path.splitext(filename)[1].lower()
383 if request.method == 'POST':
384 form = RenameForm(abs_path, file_extension, request.POST)
386 relative_server_path = os.path.join(DIRECTORY, path, filename)
387 new_relative_server_path = os.path.join(DIRECTORY, path, form.cleaned_data['name'] + file_extension)
390 filebrowser_pre_delete.send(sender=request, path=path, filename=filename)
391 # DELETE IMAGE VERSIONS/THUMBNAILS
392 # regenerating versions/thumbs will be done automatically
393 for version in VERSIONS:
395 os.unlink(os.path.join(MEDIA_ROOT, _get_version_path(relative_server_path, version)))
399 os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path))
401 filebrowser_post_delete.send(sender=request, path=path, filename=filename)
403 msg = _('Renaming was successful.')
404 request.user.message_set.create(message=msg)
405 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename")
406 return HttpResponseRedirect(redirect_url)
407 except OSError, (errno, strerror):
408 form.errors['name'] = forms.util.ErrorList([_('Error.')])
410 form = RenameForm(abs_path, file_extension)
412 return render_to_response('filebrowser/rename.html', {
415 'file_extension': file_extension,
416 'title': _(u'Rename "%s"') % filename,
417 'settings_var': _get_settings_var(),
418 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Rename')),
419 }, context_instance=Context(request))
420 rename = staff_member_required(never_cache(rename))
423 def versions(request):
425 Show all Versions for an Image according to ADMIN_VERSIONS.
430 path = _get_path(query.get('dir', ''))
431 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
432 if path is None or filename is None:
433 msg = _('Directory/File does not exist.')
434 request.user.message_set.create(message=msg)
435 return HttpResponseRedirect(reverse("fb_browse"))
436 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
438 return render_to_response('filebrowser/versions.html', {
439 'original': _path_to_url(os.path.join(DIRECTORY, path, filename)),
441 'title': _(u'Versions for "%s"') % filename,
442 'settings_var': _get_settings_var(),
443 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Versions for "%s"') % filename),
444 }, context_instance=Context(request))
446 versions = staff_member_required(never_cache(versions))