Skip to content

Commit

Permalink
Merge pull request #27 from scream4ik/master
Browse files Browse the repository at this point in the history
several improvements
  • Loading branch information
miguelramos authored Nov 21, 2016
2 parents 8cbbfaf + 34882b7 commit 0f30d23
Show file tree
Hide file tree
Showing 29 changed files with 1,157 additions and 717 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ dist/
django_media_manager.egg-info
example/example/local_settings.py
.DS_Store
.idea/
1 change: 1 addition & 0 deletions filebrowser/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
default_app_config = "filebrowser.apps.FilebrowserAppConfig"
50 changes: 50 additions & 0 deletions filebrowser/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from django.apps import AppConfig
from django.views.decorators.cache import never_cache
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _

from filebrowser.conf import fb_settings


class FilebrowserAppConfig(AppConfig):
name = 'filebrowser'

def ready(self):
from django.contrib import admin
from django.contrib.admin import sites

class FilebrowserAdminSite(admin.AdminSite):
@never_cache
def index(self, request, extra_context=None):
resp = super(FilebrowserAdminSite, self).index(request,
extra_context)
app_dict = {
'app_url': reverse('fb_browse'),
'models': [
{
'admin_url': reverse('fb_browse'),
'name': 'Browse',
'add_url': None
},
{
'admin_url': reverse('fb_mkdir'),
'name': _('New Folder'),
'add_url': None
},
{
'admin_url': reverse('fb_upload'),
'name': _('Upload'),
'add_url': None
}
],
'has_module_perms': True,
'name': _('Filebrowser'),
'app_label': 'filebrowser'
}
resp.context_data['app_list'].append(app_dict)
return resp

if fb_settings.SHOW_AT_ADMIN_PANEL:
fb = FilebrowserAdminSite()
admin.site = fb
sites.site = fb
86 changes: 46 additions & 40 deletions filebrowser/base.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,15 @@
# coding: utf-8

# imports
import os, re, datetime
from time import gmtime, strftime

# django imports
from django.conf import settings
import os
import re
import datetime
from PIL import Image

# filebrowser imports
from filebrowser.settings import *
from filebrowser.settings import SAVE_FULL_URL, ADMIN_THUMBNAIL
from filebrowser.conf import fb_settings
from filebrowser.functions import get_file_type, url_join, is_selectable, get_version_path

# PIL import
if STRICT_PIL:
from PIL import Image
else:
try:
from PIL import Image
except ImportError:
import Image
from filebrowser.functions import get_file_type, url_join, get_version_path


class FileObject(object):
Expand All @@ -30,21 +20,29 @@ class FileObject(object):
"""

def __init__(self, path):
'''
`os.path.split` Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty.
'''
"""
`os.path.split` Split the pathname path into a pair, (head, tail)
where tail is the last pathname component and head is everything
leading up to that. The tail part will never contain a slash;
if path ends in a slash, tail will be empty.
If there is no slash in path, head will be empty.
If path is empty, both head and tail are empty.
"""
self.path = path
self.url_rel = path.replace("\\","/")
self.url_rel = path.replace("\\", "/")
self.head, self.filename = os.path.split(path)
self.filename_lower = self.filename.lower() # important for sorting
self.filetype = get_file_type(self.filename) # strange if file no extension then this folder
# important for sorting
self.filename_lower = self.filename.lower()
# strange if file no extension then this folder
self.filetype = get_file_type(self.filename)

def _filesize(self):
"""
Filesize.
"""
path = (self.path)
if os.path.isfile(os.path.join(fb_settings.MEDIA_ROOT, path)) or os.path.isdir(os.path.join(fb_settings.MEDIA_ROOT, path)):
path = self.path
if os.path.isfile(os.path.join(fb_settings.MEDIA_ROOT, path)) or \
os.path.isdir(os.path.join(fb_settings.MEDIA_ROOT, path)):
return os.path.getsize(os.path.join(fb_settings.MEDIA_ROOT, path))
return ""
filesize = property(_filesize)
Expand All @@ -53,8 +51,11 @@ def _date(self):
"""
Date.
"""
if os.path.isfile(os.path.join(fb_settings.MEDIA_ROOT, self.path)) or os.path.isdir(os.path.join(fb_settings.MEDIA_ROOT, self.path)):
return os.path.getmtime(os.path.join(fb_settings.MEDIA_ROOT, self.path))
if os.path.isfile(os.path.join(fb_settings.MEDIA_ROOT, self.path)) or \
os.path.isdir(os.path.join(fb_settings.MEDIA_ROOT, self.path)):
return os.path.getmtime(
os.path.join(fb_settings.MEDIA_ROOT, self.path)
)
return ""
date = property(_date)

Expand Down Expand Up @@ -96,9 +97,9 @@ def _path_relative_directory(self):
"""
Path relative to initial directory.
"""
directory_re = re.compile(r'^({0})'.format((fb_settings.DIRECTORY)))
directory_re = re.compile(r'^({0})'.format(fb_settings.DIRECTORY))
value = directory_re.sub('', self.path)
return u"{0}".format(value)
return value
path_relative_directory = property(_path_relative_directory)

def _url_relative(self):
Expand All @@ -109,7 +110,7 @@ def _url_full(self):
"""
Full URL including MEDIA_URL.
"""
return (url_join(fb_settings.MEDIA_URL, self.url_rel))
return url_join(fb_settings.MEDIA_URL, self.url_rel)
url_full = property(_url_full)

def _url_save(self):
Expand All @@ -127,28 +128,35 @@ def _url_thumbnail(self):
Thumbnail URL.
"""
if self.filetype == "Image":
return u"{0}".format(url_join(fb_settings.MEDIA_URL, get_version_path(self.path, ADMIN_THUMBNAIL)))
return "{0}".format(
url_join(
fb_settings.MEDIA_URL,
get_version_path(self.path, ADMIN_THUMBNAIL)
)
)
else:
return ""
url_thumbnail = property(_url_thumbnail)

def url_admin(self):
if self.filetype_checked == "Folder":
directory_re = re.compile(r'^({0})'.format((fb_settings.DIRECTORY)))
directory_re = re.compile(r'^({0})'.format(fb_settings.DIRECTORY))
value = directory_re.sub('', self.path)
return u"{0}".format(value)
return "{0}".format(value)
else:
return u"{0}".format(url_join(fb_settings.MEDIA_URL, self.path))
return "{0}".format(url_join(fb_settings.MEDIA_URL, self.path))

def _dimensions(self):
"""
Image Dimensions.
"""
if self.filetype == 'Image':
try:
im = Image.open(os.path.join(fb_settings.MEDIA_ROOT, self.path))
im = Image.open(
os.path.join(fb_settings.MEDIA_ROOT, self.path)
)
return im.size
except:
except IOError:
pass
else:
return False
Expand Down Expand Up @@ -195,12 +203,10 @@ def _is_empty(self):
is_empty = property(_is_empty)

def __repr__(self):
return (self.url_save)
return self.url_save

def __str__(self):
return (self.url_save)
return self.url_save

def __unicode__(self):
return (self.url_save)


return self.url_save
2 changes: 1 addition & 1 deletion filebrowser/conf.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@

from filebrowser import settings


class FileBrowserSettings(object):
"""
Proxy for file browser settings defined at module level
Expand Down
5 changes: 1 addition & 4 deletions filebrowser/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ def decorator(request, *args, **kwargs):
session_data = engine.SessionStore(request.POST.get('session_key'))
user_id = session_data['_auth_user_id']
# will return 404 if the session ID does not resolve to a valid user
User = get_user_model()
request.user = get_object_or_404(User, pk=user_id)
request.user = get_object_or_404(get_user_model(), pk=user_id)
return function(request, *args, **kwargs)
return decorator


74 changes: 34 additions & 40 deletions filebrowser/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,19 @@
import os

# django imports
from django.db import models
from django import forms
from django.forms.widgets import Input
from django.db.models.fields import Field, CharField
from django.db.models.fields import Field
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _

# filebrowser imports
from filebrowser.settings import *
from filebrowser.settings import (
URL_FILEBROWSER_MEDIA, ADMIN_THUMBNAIL, DEBUG, EXTENSIONS, MEDIA_ROOT,
DIRECTORY
)
from filebrowser.base import FileObject
from filebrowser.conf import fb_settings
from filebrowser.functions import url_to_path


def _template():
if fb_settings.SUIT_TEMPLATE:
path = 'suit/'
else:
path = 'filebrowser/'

return path
from filebrowser.functions import url_to_path, _template


class FileBrowseWidget(Input):
Expand All @@ -37,17 +29,19 @@ def __init__(self, attrs=None):
self.directory = attrs.get('directory', '')
self.extensions = attrs.get('extensions', '')
self.format = attrs.get('format', '')
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
super(FileBrowseWidget, self).__init__(attrs)
# if field have a directory - create it
dir_path = os.path.join(MEDIA_ROOT, DIRECTORY, self.directory)
if not os.path.exists(dir_path):
os.makedirs(dir_path)

def render(self, name, value, attrs=None):
if value is None:
value = ""
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
final_attrs[
'search_icon'] = URL_FILEBROWSER_MEDIA + 'img/filebrowser_icon_show.gif'
final_attrs['search_icon'] = os.path.join(
URL_FILEBROWSER_MEDIA, 'img/filebrowser_icon_show.gif'
)
final_attrs['directory'] = self.directory
final_attrs['extensions'] = self.extensions
final_attrs['format'] = self.format
Expand All @@ -63,8 +57,6 @@ def render(self, name, value, attrs=None):


class FileBrowseFormField(forms.CharField):
widget = FileBrowseWidget

default_error_messages = {
'extension': _(
u'Extension %(ext)s is not allowed. Only %(allowed)s is allowed.'),
Expand All @@ -76,17 +68,23 @@ def __init__(self, max_length=None, min_length=None,
self.max_length, self.min_length = max_length, min_length
self.directory = directory
self.extensions = extensions
if format:
self.format = format or ''
self.extensions = extensions or EXTENSIONS.get(format)
self.format = format or ''
self.extensions = extensions or EXTENSIONS.get(format)

attrs = {
"directory": self.directory,
"extensions": self.extensions,
"format": self.format
}
self.widget = FileBrowseWidget(attrs)
super(FileBrowseFormField, self).__init__(*args, **kwargs)

def clean(self, value):
value = super(FileBrowseFormField, self).clean(value)
if value == '':
return value
file_extension = os.path.splitext(value)[1].lower()
if self.extensions and not file_extension in self.extensions:
if self.extensions and file_extension not in self.extensions:
raise forms.ValidationError(
self.error_messages['extension'] % {'ext': file_extension,
'allowed': ", ".join(
Expand All @@ -99,6 +97,7 @@ def __init__(self, *args, **kwargs):
self.directory = kwargs.pop('directory', '')
self.extensions = kwargs.pop('extensions', '')
self.format = kwargs.pop('format', '')
kwargs['max_length'] = kwargs.get('max_length', 200)
super(FileBrowseField, self).__init__(*args, **kwargs)

def from_db_value(self, value, expression, connection, context):
Expand All @@ -116,17 +115,20 @@ def get_db_prep_value(self, value, connection, prepared=False):
return None
return str(value)

def get_manipulator_field_objs(self):
return [oldforms.TextField]
# FIXME: recheck or need it
# @staticmethod
# def get_manipulator_field_objs():
# return [oldforms.TextField]

def get_internal_type(self):
return "CharField"

def formfield(self, **kwargs):
attrs = {}
attrs["directory"] = self.directory
attrs["extensions"] = self.extensions
attrs["format"] = self.format
attrs = {
"directory": self.directory,
"extensions": self.extensions,
"format": self.format
}
defaults = {
'form_class': FileBrowseFormField,
'widget': FileBrowseWidget(attrs=attrs),
Expand All @@ -136,11 +138,3 @@ def formfield(self, **kwargs):
}
defaults.update(kwargs)
return super(FileBrowseField, self).formfield(**defaults)


try:
from south.modelsinspector import add_introspection_rules

add_introspection_rules([], ["^filebrowser\.fields\.FileBrowseField"])
except:
pass
Loading

0 comments on commit 0f30d23

Please sign in to comment.