# Path: adminfiles/settings.py
# JQUERY_URL = getattr(settings, 'JQUERY_URL',
#                      'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js')
#     JQUERY_URL = posixpath.join(settings.STATIC_URL, JQUERY_URL)
# ADMINFILES_UPLOAD_TO = getattr(settings, 'ADMINFILES_UPLOAD_TO', 'adminfiles')
# ADMINFILES_THUMB_ORDER = getattr(settings, 'ADMINFILES_THUMB_ORDER',
#                                  ('-upload_date',))
# ADMINFILES_USE_SIGNALS = getattr(settings, 'ADMINFILES_USE_SIGNALS', False)
# ADMINFILES_REF_START = getattr(settings, 'ADMINFILES_REF_START', '<<<')
# ADMINFILES_REF_END = getattr(settings, 'ADMINFILES_REF_END', '>>>')
# ADMINFILES_STRING_IF_NOT_FOUND = getattr(settings,
#                                          'ADMINFILES_STRING_IF_NOT_FOUND',
#                                          u'')
# ADMINFILES_INSERT_LINKS = getattr(
#     settings,
#     'ADMINFILES_INSERT_LINKS',
#     {'': [(_('Insert Link'), {})],
#      'image': [(_('Insert'), {}),
#                (_('Insert (align left)'), {'class': 'left'}),
#                (_('Insert (align right)'), {'class': 'right'})]
#      },
#     )
# ADMINFILES_STDICON_SET = getattr(settings, 'ADMINFILES_STDICON_SET', None)
# ADMINFILES_BROWSER_VIEWS = getattr(settings, 'ADMINFILES_BROWSER_VIEWS',
#                                    ['adminfiles.views.AllView',
#                                     'adminfiles.views.ImagesView',
#                                     'adminfiles.views.AudioView',
#                                     'adminfiles.views.FilesView',
#                                     'adminfiles.views.FlickrView',
#                                     'adminfiles.views.YouTubeView',
#                                     'adminfiles.views.VimeoView'])
# 
# Path: adminfiles/models.py
# class FileUpload(models.Model):
#     upload_date = models.DateTimeField(_('upload date'), auto_now_add=True)
#     upload = models.FileField(_('file'), upload_to=settings.ADMINFILES_UPLOAD_TO)
#     title = models.CharField(_('title'), max_length=100)
#     slug = models.SlugField(_('slug'), max_length=100, unique=True)
#     description = models.CharField(_('description'), blank=True, max_length=200)
#     content_type = models.CharField(editable=False, max_length=100)
#     sub_type = models.CharField(editable=False, max_length=100)
# 
#     if TagField:
#         tags = TagField(_('tags'))
#     
#     class Meta:
#         ordering = ['upload_date', 'title']
#         verbose_name = _('file upload')
#         verbose_name_plural = _('file uploads')
# 
#     def __unicode__(self):
#         return self.title
# 
#     def mime_type(self):
#         return '%s/%s' % (self.content_type, self.sub_type)
#     mime_type.short_description = _('mime type')
# 
#     def type_slug(self):
#         return slugify(self.sub_type)
# 
#     def is_image(self):
#         return self.content_type == 'image'
# 
#     def _get_dimensions(self):
#         try:
#             return self._dimensions_cache
#         except AttributeError:
#             if self.is_image():
#                 self._dimensions_cache = get_image_dimensions(self.upload.path)
#             else:
#                 self._dimensions_cache = (None, None)
#         return self._dimensions_cache
#     
#     def width(self):
#         return self._get_dimensions()[0]
#     
#     def height(self):
#         return self._get_dimensions()[1]
#     
#     def save(self, *args, **kwargs):
#         try:
#             uri = self.upload.path
#         except NotImplementedError:
#             uri = self.upload.url
#         (mime_type, encoding) = mimetypes.guess_type(uri)
#         try:
#             [self.content_type, self.sub_type] = mime_type.split('/')
#         except:
#             self.content_type = 'text'
#             self.sub_type = 'plain'
#         super(FileUpload, self).save()
# 
#     def insert_links(self):
#         links = []
#         for key in [self.mime_type(), self.content_type, '']:
#             if key in settings.ADMINFILES_INSERT_LINKS:
#                 links = settings.ADMINFILES_INSERT_LINKS[key]
#                 break
#         for link in links:
#             ref = self.slug
#             opts = ':'.join(['%s=%s' % (k,v) for k,v in link[1].items()])
#             if opts:
#                 ref += ':' + opts
#             yield {'desc': link[0],
#                    'ref': ref}
# 
#     def mime_image(self):
#         if not settings.ADMINFILES_STDICON_SET:
#             return None
#         return ('http://www.stdicon.com/%s/%s?size=64'
#                 % (settings.ADMINFILES_STDICON_SET, self.mime_type()))


import re
from adminfiles import settings
from adminfiles.models import FileUpload


# Upload references look like: <<< upload-slug : key=val : key2=val2 >>>
# Spaces are optional, key-val opts are optional, can be any number
# extra indirection is for testability
def _get_upload_re():
    return re.compile(r'%s\s*([\w-]+)((\s*:\s*\w+\s*=\s*.+?)*)\s*%s'
                      % (re.escape(settings.ADMINFILES_REF_START),
                         re.escape(settings.ADMINFILES_REF_END)))
UPLOAD_RE = _get_upload_re()

def get_uploads(text):
    """
    Return a generator yielding uploads referenced in the given text.

    """
    uploads = []
    for match in UPLOAD_RE.finditer(text):
        try:
            upload = FileUpload.objects.get(slug=match.group(1))

# Path: adminfiles/settings.py
# JQUERY_URL = getattr(settings, 'JQUERY_URL',
#                      'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js')
#     JQUERY_URL = posixpath.join(settings.STATIC_URL, JQUERY_URL)
# ADMINFILES_UPLOAD_TO = getattr(settings, 'ADMINFILES_UPLOAD_TO', 'adminfiles')
# ADMINFILES_THUMB_ORDER = getattr(settings, 'ADMINFILES_THUMB_ORDER',
#                                  ('-upload_date',))
# ADMINFILES_USE_SIGNALS = getattr(settings, 'ADMINFILES_USE_SIGNALS', False)
# ADMINFILES_REF_START = getattr(settings, 'ADMINFILES_REF_START', '<<<')
# ADMINFILES_REF_END = getattr(settings, 'ADMINFILES_REF_END', '>>>')
# ADMINFILES_STRING_IF_NOT_FOUND = getattr(settings,
#                                          'ADMINFILES_STRING_IF_NOT_FOUND',
#                                          u'')
# ADMINFILES_INSERT_LINKS = getattr(
#     settings,
#     'ADMINFILES_INSERT_LINKS',
#     {'': [(_('Insert Link'), {})],
#      'image': [(_('Insert'), {}),
#                (_('Insert (align left)'), {'class': 'left'}),
#                (_('Insert (align right)'), {'class': 'right'})]
#      },
#     )
# ADMINFILES_STDICON_SET = getattr(settings, 'ADMINFILES_STDICON_SET', None)
# ADMINFILES_BROWSER_VIEWS = getattr(settings, 'ADMINFILES_BROWSER_VIEWS',
#                                    ['adminfiles.views.AllView',
#                                     'adminfiles.views.ImagesView',
#                                     'adminfiles.views.AudioView',
#                                     'adminfiles.views.FilesView',
#                                     'adminfiles.views.FlickrView',
#                                     'adminfiles.views.YouTubeView',
#                                     'adminfiles.views.VimeoView'])
# 
# Path: adminfiles/models.py
# class FileUpload(models.Model):
#     upload_date = models.DateTimeField(_('upload date'), auto_now_add=True)
#     upload = models.FileField(_('file'), upload_to=settings.ADMINFILES_UPLOAD_TO)
#     title = models.CharField(_('title'), max_length=100)
#     slug = models.SlugField(_('slug'), max_length=100, unique=True)
#     description = models.CharField(_('description'), blank=True, max_length=200)
#     content_type = models.CharField(editable=False, max_length=100)
#     sub_type = models.CharField(editable=False, max_length=100)
# 
#     if TagField:
#         tags = TagField(_('tags'))
#     
#     class Meta:
#         ordering = ['upload_date', 'title']
#         verbose_name = _('file upload')
#         verbose_name_plural = _('file uploads')
# 
#     def __unicode__(self):
#         return self.title
# 
#     def mime_type(self):
#         return '%s/%s' % (self.content_type, self.sub_type)
#     mime_type.short_description = _('mime type')
# 
#     def type_slug(self):
#         return slugify(self.sub_type)
# 
#     def is_image(self):
#         return self.content_type == 'image'
# 
#     def _get_dimensions(self):
#         try:
#             return self._dimensions_cache
#         except AttributeError:
#             if self.is_image():
#                 self._dimensions_cache = get_image_dimensions(self.upload.path)
#             else:
#                 self._dimensions_cache = (None, None)
#         return self._dimensions_cache
#     
#     def width(self):
#         return self._get_dimensions()[0]
#     
#     def height(self):
#         return self._get_dimensions()[1]
#     
#     def save(self, *args, **kwargs):
#         try:
#             uri = self.upload.path
#         except NotImplementedError:
#             uri = self.upload.url
#         (mime_type, encoding) = mimetypes.guess_type(uri)
#         try:
#             [self.content_type, self.sub_type] = mime_type.split('/')
#         except:
#             self.content_type = 'text'
#             self.sub_type = 'plain'
#         super(FileUpload, self).save()
# 
#     def insert_links(self):
#         links = []
#         for key in [self.mime_type(), self.content_type, '']:
#             if key in settings.ADMINFILES_INSERT_LINKS:
#                 links = settings.ADMINFILES_INSERT_LINKS[key]
#                 break
#         for link in links:
#             ref = self.slug
#             opts = ':'.join(['%s=%s' % (k,v) for k,v in link[1].items()])
#             if opts:
#                 ref += ':' + opts
#             yield {'desc': link[0],
#                    'ref': ref}
# 
#     def mime_image(self):
#         if not settings.ADMINFILES_STDICON_SET:
#             return None
#         return ('http://www.stdicon.com/%s/%s?size=64'
#                 % (settings.ADMINFILES_STDICON_SET, self.mime_type()))


# Path: adminfiles/parse.py
import re
from adminfiles import settings
from adminfiles.models import FileUpload



# Upload references look like: <<< upload-slug : key=val : key2=val2 >>>
# Spaces are optional, key-val opts are optional, can be any number
# extra indirection is for testability
def _get_upload_re():
    return re.compile(r'%s\s*([\w-]+)((\s*:\s*\w+\s*=\s*.+?)*)\s*%s'
                      % (re.escape(settings.ADMINFILES_REF_START),
                         re.escape(settings.ADMINFILES_REF_END)))
UPLOAD_RE = _get_upload_re()

def get_uploads(text):
    """
    Return a generator yielding uploads referenced in the given text.

    """
    uploads = []
    for match in UPLOAD_RE.finditer(text):
        try:
            upload = FileUpload.objects.get(slug=match.group(1))

        except FileUpload.DoesNotExist: