5 from time import gmtime, strftime
8 from django.shortcuts import render_to_response, HttpResponse
9 from django.template import RequestContext as Context
10 from django.http import HttpResponseRedirect
11 from django.contrib.admin.views.decorators import staff_member_required
12 from django.views.decorators.cache import never_cache
13 from django.utils.translation import ugettext as _
14 from django.conf import settings
15 from django import forms
16 from django.core.urlresolvers import reverse
17 from django.core.exceptions import ImproperlyConfigured
18 from django.dispatch import Signal
21 from filebrowser.fb_settings import *
22 from filebrowser.functions import _url_to_path, _path_to_url, _get_path, _get_file, _get_version_path, _get_breadcrumbs, _get_filterdate, _get_settings_var, _handle_file_upload, _get_file_type, _url_join, _convert_filename
23 from filebrowser.templatetags.fb_tags import query_helper
24 from filebrowser.base import FileObject
25 from filebrowser.decorators import flash_login_required
27 # Precompile regular expressions
30 filter_re.append(re.compile(exp))
31 for k, v in VERSIONS.iteritems():
32 exp = (r'_%s.(%s)') % (k, '|'.join(EXTENSION_LIST))
33 filter_re.append(re.compile(exp))
38 Browse Files/Directories.
43 path = _get_path(query.get('dir', ''))
44 directory = _get_path('')
47 msg = _('Directory/File does not exist.')
48 request.user.message_set.create(message = msg)
50 # The DIRECTORY does not exist, raise an error to prevent eternal redirecting.
51 raise ImproperlyConfigured, _("Error finding upload directory. Maybe it does not exist?")
52 redirect_url = reverse("fb_browse") + query_helper(query, "", "dir")
53 return HttpResponseRedirect(redirect_url)
54 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
57 results_var = {'results_total': 0, 'results_current': 0, 'delete_total': 0, 'images_total': 0, 'select_total': 0 }
59 for k, v in EXTENSIONS.iteritems():
62 dir_list = os.listdir(abs_path)
66 # EXCLUDE FILES MATCHING VERSIONS_PREFIX OR ANY OF THE EXCLUDE PATTERNS
67 filtered = file.startswith('.')
68 for re_prefix in filter_re:
69 if re_prefix.search(file):
73 results_var['results_total'] += 1
76 fileobject = FileObject(os.path.join(DIRECTORY, path, file))
80 if fileobject.filetype == request.GET.get('filter_type', fileobject.filetype) and _get_filterdate(request.GET.get('filter_date', ''), fileobject.date):
82 if request.GET.get('q') and not re.compile(request.GET.get('q').lower(), re.M).search(file.lower()):
87 files.append(fileobject)
88 results_var['results_current'] += 1
90 if fileobject.filetype == 'Image':
91 results_var['images_total'] += 1
92 if fileobject.filetype != 'Folder':
93 results_var['delete_total'] += 1
94 elif fileobject.filetype == 'Folder' and fileobject.is_empty:
95 results_var['delete_total'] += 1
96 if query.get('type') and query.get('type') in SELECT_FORMATS and fileobject.filetype in SELECT_FORMATS[query.get('type')]:
97 results_var['select_total'] += 1
98 elif not query.get('type'):
99 results_var['select_total'] += 1
102 if fileobject.filetype:
103 counter[fileobject.filetype] += 1
106 files.sort(key = lambda e: getattr(e, request.GET.get('o', DEFAULT_ORDER)))
107 if request.GET.get('ot') == "desc":
110 return render_to_response('filebrowser/index.html', {
113 'results_var': results_var,
116 'title': _(u'FileBrowser'),
117 'settings_var': _get_settings_var(),
118 'breadcrumbs': _get_breadcrumbs(query, path, ''),
119 }, context_instance = Context(request))
120 browse = staff_member_required(never_cache(browse))
124 filebrowser_pre_createdir = Signal(providing_args = ["path", "dirname"])
125 filebrowser_post_createdir = Signal(providing_args = ["path", "dirname"])
132 from filebrowser.forms import MakeDirForm
136 path = _get_path(query.get('dir', ''))
138 msg = _('Directory/File does not exist.')
139 request.user.message_set.create(message = msg)
140 return HttpResponseRedirect(reverse("fb_browse"))
141 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
143 if request.method == 'POST':
144 form = MakeDirForm(abs_path, request.POST)
146 server_path = os.path.join(abs_path, form.cleaned_data['dir_name'])
149 filebrowser_pre_createdir.send(sender = request, path = path, dirname = form.cleaned_data['dir_name'])
151 os.mkdir(server_path)
152 os.chmod(server_path, 0775)
154 filebrowser_post_createdir.send(sender = request, path = path, dirname = form.cleaned_data['dir_name'])
156 msg = _('The Folder %s was successfully created.') % (form.cleaned_data['dir_name'])
157 request.user.message_set.create(message = msg)
158 # on redirect, sort by date desc to see the new directory on top of the list
159 # remove filter in order to actually _see_ the new folder
160 redirect_url = reverse("fb_browse") + query_helper(query, "ot=desc,o=date", "ot,o,filter_type,filter_date,q")
161 return HttpResponseRedirect(redirect_url)
162 except OSError, (errno, strerror):
164 form.errors['dir_name'] = forms.util.ErrorList([_('Permission denied.')])
166 form.errors['dir_name'] = forms.util.ErrorList([_('Error creating directory.')])
168 form = MakeDirForm(abs_path)
170 return render_to_response('filebrowser/makedir.html', {
173 'title': _(u'New Folder'),
174 'settings_var': _get_settings_var(),
175 'breadcrumbs': _get_breadcrumbs(query, path, _(u'New Folder')),
176 }, context_instance = Context(request))
177 mkdir = staff_member_required(never_cache(mkdir))
185 from django.http import parse_cookie
189 path = _get_path(query.get('dir', ''))
191 msg = _('Directory/File does not exist.')
192 request.user.message_set.create(message = msg)
193 return HttpResponseRedirect(reverse("fb_browse"))
194 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
196 # SESSION (used for flash-uploading)
197 cookie_dict = parse_cookie(request.META.get('HTTP_COOKIE', ''))
198 engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
199 session_key = cookie_dict.get(settings.SESSION_COOKIE_NAME, None)
201 return render_to_response('filebrowser/upload.html', {
203 'title': _(u'Select files to upload'),
204 'settings_var': _get_settings_var(),
205 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Upload')),
206 'session_key': session_key,
207 }, context_instance = Context(request))
208 upload = staff_member_required(never_cache(upload))
211 def _check_file(request):
213 Check if file already exists on the server.
216 from django.utils import simplejson
218 folder = request.POST.get('folder')
219 fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload"))
220 folder = fb_uploadurl_re.sub('', folder)
223 if request.method == 'POST':
224 for k, v in request.POST.items():
226 v = _convert_filename(v)
227 if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, v)):
230 return HttpResponse(simplejson.dumps(fileArray))
234 filebrowser_pre_upload = Signal(providing_args = ["path", "file"])
235 filebrowser_post_upload = Signal(providing_args = ["path", "file"])
237 def _upload_file(request):
239 Upload file to the server.
242 from django.core.files.move import file_move_safe
244 if request.method == 'POST':
245 folder = request.POST.get('folder')
246 fb_uploadurl_re = re.compile(r'^(%s)' % reverse("fb_upload"))
247 folder = fb_uploadurl_re.sub('', folder)
248 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, folder)
250 filedata = request.FILES['Filedata']
251 filedata.name = _convert_filename(filedata.name)
253 filebrowser_pre_upload.send(sender = request, path = request.POST.get('folder'), file = filedata)
255 uploadedfile = _handle_file_upload(abs_path, filedata)
257 # if file already exists
258 if os.path.isfile(os.path.join(MEDIA_ROOT, DIRECTORY, folder, filedata.name)):
259 old_file = os.path.join(abs_path, filedata.name)
260 new_file = os.path.join(abs_path, uploadedfile)
261 file_move_safe(new_file, old_file)
263 filebrowser_post_upload.send(sender = request, path = request.POST.get('folder'), file = FileObject(os.path.join(DIRECTORY, folder, filedata.name)))
264 return HttpResponse('True')
265 _upload_file = flash_login_required(_upload_file)
269 filebrowser_pre_delete = Signal(providing_args = ["path", "filename"])
270 filebrowser_post_delete = Signal(providing_args = ["path", "filename"])
274 Delete existing File/Directory.
276 When trying to delete a Directory, the Directory has to be empty.
281 path = _get_path(query.get('dir', ''))
282 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
283 if path is None or filename is None:
284 msg = _('Directory/File does not exist.')
285 request.user.message_set.create(message = msg)
286 return HttpResponseRedirect(reverse("fb_browse"))
287 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
291 if request.GET.get('filetype') != "Folder":
292 relative_server_path = os.path.join(DIRECTORY, path, filename)
295 filebrowser_pre_delete.send(sender = request, path = path, filename = filename)
296 # DELETE IMAGE VERSIONS/THUMBNAILS
297 for version in VERSIONS:
299 os.unlink(os.path.join(MEDIA_ROOT, _get_version_path(relative_server_path, version)))
303 os.unlink(os.path.join(abs_path, filename))
305 filebrowser_post_delete.send(sender = request, path = path, filename = filename)
307 msg = _('The file %s was successfully deleted.') % (filename.lower())
308 request.user.message_set.create(message = msg)
309 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
310 return HttpResponseRedirect(redirect_url)
312 # todo: define error message
317 filebrowser_pre_delete.send(sender = request, path = path, filename = filename)
319 os.rmdir(os.path.join(abs_path, filename))
321 filebrowser_post_delete.send(sender = request, path = path, filename = filename)
323 msg = _('The directory %s was successfully deleted.') % (filename.lower())
324 request.user.message_set.create(message = msg)
325 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename,filetype")
326 return HttpResponseRedirect(redirect_url)
328 # todo: define error message
332 request.user.message_set.create(message = msg)
334 return render_to_response('filebrowser/index.html', {
336 'file': request.GET.get('filename', ''),
338 'settings_var': _get_settings_var(),
339 'breadcrumbs': _get_breadcrumbs(query, dir_name, ''),
340 }, context_instance = Context(request))
341 delete = staff_member_required(never_cache(delete))
345 filebrowser_pre_rename = Signal(providing_args = ["path", "filename"])
346 filebrowser_post_rename = Signal(providing_args = ["path", "filename"])
350 Rename existing File/Directory.
352 Includes renaming existing Image Versions/Thumbnails.
355 from filebrowser.forms import RenameForm
359 path = _get_path(query.get('dir', ''))
360 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
361 if path is None or filename is None:
362 msg = _('Directory/File does not exist.')
363 request.user.message_set.create(message = msg)
364 return HttpResponseRedirect(reverse("fb_browse"))
365 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
366 file_extension = os.path.splitext(filename)[1].lower()
368 if request.method == 'POST':
369 form = RenameForm(abs_path, file_extension, request.POST)
371 relative_server_path = os.path.join(DIRECTORY, path, filename)
372 new_relative_server_path = os.path.join(DIRECTORY, path, form.cleaned_data['name'] + file_extension)
375 filebrowser_pre_delete.send(sender = request, path = path, filename = filename)
376 # DELETE IMAGE VERSIONS/THUMBNAILS
377 # regenerating versions/thumbs will be done automatically
378 for version in VERSIONS:
380 os.unlink(os.path.join(MEDIA_ROOT, _get_version_path(relative_server_path, version)))
384 os.rename(os.path.join(MEDIA_ROOT, relative_server_path), os.path.join(MEDIA_ROOT, new_relative_server_path))
386 filebrowser_post_delete.send(sender = request, path = path, filename = filename)
388 msg = _('Renaming was successful.')
389 request.user.message_set.create(message = msg)
390 redirect_url = reverse("fb_browse") + query_helper(query, "", "filename")
391 return HttpResponseRedirect(redirect_url)
392 except OSError, (errno, strerror):
393 form.errors['name'] = forms.util.ErrorList([_('Error.')])
395 form = RenameForm(abs_path, file_extension)
397 return render_to_response('filebrowser/rename.html', {
400 'file_extension': file_extension,
401 'title': _(u'Rename "%s"') % filename,
402 'settings_var': _get_settings_var(),
403 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Rename')),
404 }, context_instance = Context(request))
405 rename = staff_member_required(never_cache(rename))
408 def versions(request):
410 Show all Versions for an Image according to ADMIN_VERSIONS.
415 path = _get_path(query.get('dir', ''))
416 filename = _get_file(query.get('dir', ''), query.get('filename', ''))
417 if path is None or filename is None:
418 msg = _('Directory/File does not exist.')
419 request.user.message_set.create(message = msg)
420 return HttpResponseRedirect(reverse("fb_browse"))
421 abs_path = os.path.join(MEDIA_ROOT, DIRECTORY, path)
423 return render_to_response('filebrowser/versions.html', {
424 'original': _path_to_url(os.path.join(DIRECTORY, path, filename)),
426 'title': _(u'Versions for "%s"') % filename,
427 'settings_var': _get_settings_var(),
428 'breadcrumbs': _get_breadcrumbs(query, path, _(u'Versions for "%s"') % filename),
429 }, context_instance = Context(request))
430 versions = staff_member_required(never_cache(versions))