Exemple #1
0
    def generate_slug(self):
        """
        Generate a unique slug for this object.

        This one does not *force* slugs, but usually it will probably result
        in a niceish one.

        The end *result* of the algorithm will result in these resolutions for
        these situations:
         - If we have a slug, make sure it's clean and sanitized, and if it's
           unique, we'll use that.
         - If we have a title, slugify it, and if it's unique, we'll use that.
         - If we can't get any sort of thing that looks like it'll be a useful
           slug out of a title or an existing slug, bail, and don't set the
           slug at all.  Don't try to create something just because.  Make
           sure we have a reasonable basis for a slug first.
         - If we have a reasonable basis for a slug (either based on existing
           slug or slugified title) but it's not unique, first try appending
           the entry's id, if that exists
         - If that doesn't result in something unique, tack on some randomly
           generated bits until it's unique.  That'll be a little bit of junk,
           but at least it has the basis of a nice slug.
        """
        #Is already a slug assigned? Check if it is valid
        if self.slug:
            self.slug = slugify(self.slug)

        # otherwise, try to use the title.
        elif self.title:
            # assign slug based on title
            self.slug = slugify(self.title)

        # We don't want any empty string slugs
        if self.slug == u"":
            self.slug = None

        # Do we have anything at this point?
        # If not, we're not going to get a slug
        # so just return... we're not going to force one.
        if not self.slug:
            return  # giving up!

        # Otherwise, let's see if this is unique.
        if self.check_slug_used(self.slug):
            # It looks like it's being used... lame.

            # Can we just append the object's id to the end?
            if self.id:
                slug_with_id = u"%s-%s" % (self.slug, self.id)
                if not self.check_slug_used(slug_with_id):
                    self.slug = slug_with_id
                    return  # success!

            # okay, still no success;
            # let's whack junk on there till it's unique.
            self.slug += '-' + uuid.uuid4().hex[:4]
            # keep going if necessary!
            while self.check_slug_used(self.slug):
                self.slug += uuid.uuid4().hex[:4]
Exemple #2
0
    def generate_slug(self):
        """
        Generate a unique slug for this object.

        This one does not *force* slugs, but usually it will probably result
        in a niceish one.

        The end *result* of the algorithm will result in these resolutions for
        these situations:
         - If we have a slug, make sure it's clean and sanitized, and if it's
           unique, we'll use that.
         - If we have a title, slugify it, and if it's unique, we'll use that.
         - If we can't get any sort of thing that looks like it'll be a useful
           slug out of a title or an existing slug, bail, and don't set the
           slug at all.  Don't try to create something just because.  Make
           sure we have a reasonable basis for a slug first.
         - If we have a reasonable basis for a slug (either based on existing
           slug or slugified title) but it's not unique, first try appending
           the entry's id, if that exists
         - If that doesn't result in something unique, tack on some randomly
           generated bits until it's unique.  That'll be a little bit of junk,
           but at least it has the basis of a nice slug.
        """
        #Is already a slug assigned? Check if it is valid
        if self.slug:
            self.slug = slugify(self.slug)

        # otherwise, try to use the title.
        elif self.title:
            # assign slug based on title
            self.slug = slugify(self.title)

        # We don't want any empty string slugs
        if self.slug == u"":
            self.slug = None

        # Do we have anything at this point?
        # If not, we're not going to get a slug
        # so just return... we're not going to force one.
        if not self.slug:
            return  # giving up!

        # Otherwise, let's see if this is unique.
        if self.check_slug_used(self.slug):
            # It looks like it's being used... lame.

            # Can we just append the object's id to the end?
            if self.id:
                slug_with_id = u"%s-%s" % (self.slug, self.id)
                if not self.check_slug_used(slug_with_id):
                    self.slug = slug_with_id
                    return  # success!

            # okay, still no success;
            # let's whack junk on there till it's unique.
            self.slug += '-' + uuid.uuid4().hex[:4]
            # keep going if necessary!
            while self.check_slug_used(self.slug):
                self.slug += uuid.uuid4().hex[:4]
def test_slugify():
    assert url.slugify(u'a walk in the park') == u'a-walk-in-the-park'
    assert url.slugify(u'A Walk in the Park') == u'a-walk-in-the-park'
    assert url.slugify(u'a  walk in the park') == u'a-walk-in-the-park'
    assert url.slugify(u'a walk in-the-park') == u'a-walk-in-the-park'
    assert url.slugify(u'a w@lk in the park?') == u'a-w-lk-in-the-park'
    assert url.slugify(u'a walk in the par\u0107') == u'a-walk-in-the-parc'
    assert url.slugify(u'\u00E0\u0042\u00E7\u010F\u00EB\u0066') == u'abcdef'
    # Russian
    assert url.slugify(u'\u043f\u0440\u043e\u0433\u0443\u043b\u043a\u0430 '
            u'\u0432 \u043f\u0430\u0440\u043a\u0435') == u'progulka-v-parke'
    # Korean
    assert (url.slugify(u'\uacf5\uc6d0\uc5d0\uc11c \uc0b0\ucc45') ==
            u'gongweoneseo-sancaeg')
Exemple #4
0
def test_slugify():
    assert url.slugify('a walk in the park') == 'a-walk-in-the-park'
    assert url.slugify('A Walk in the Park') == 'a-walk-in-the-park'
    assert url.slugify('a  walk in the park') == 'a-walk-in-the-park'
    assert url.slugify('a walk in-the-park') == 'a-walk-in-the-park'
    assert url.slugify('a w@lk in the park?') == 'a-w-lk-in-the-park'
    assert url.slugify('a walk in the par\u0107') == 'a-walk-in-the-parc'
    assert url.slugify('\u00E0\u0042\u00E7\u010F\u00EB\u0066') == 'abcdef'
    # Russian
    assert url.slugify('\u043f\u0440\u043e\u0433\u0443\u043b\u043a\u0430 '
            '\u0432 \u043f\u0430\u0440\u043a\u0435') == 'progulka-v-parke'
    # Korean
    assert (url.slugify('\uacf5\uc6d0\uc5d0\uc11c \uc0b0\ucc45') ==
            'gongweoneseo-sancaeg')
Exemple #5
0
def test_slugify():
    assert url.slugify('a walk in the park') == 'a-walk-in-the-park'
    assert url.slugify('A Walk in the Park') == 'a-walk-in-the-park'
    assert url.slugify('a  walk in the park') == 'a-walk-in-the-park'
    assert url.slugify('a walk in-the-park') == 'a-walk-in-the-park'
    assert url.slugify('a w@lk in the park?') == 'a-w-lk-in-the-park'
    assert url.slugify(u'a walk in the par\u0107') == 'a-walk-in-the-parc'
    assert url.slugify(u'\u00E0\u0042\u00E7\u010F\u00EB\u0066') == 'abcdef'
def test_slugify():
    assert url.slugify(u'a walk in the park') == u'a-walk-in-the-park'
    assert url.slugify(u'A Walk in the Park') == u'a-walk-in-the-park'
    assert url.slugify(u'a  walk in the park') == u'a-walk-in-the-park'
    assert url.slugify(u'a walk in-the-park') == u'a-walk-in-the-park'
    assert url.slugify(u'a w@lk in the park?') == u'a-w-lk-in-the-park'
    assert url.slugify(u'a walk in the par\u0107') == u'a-walk-in-the-parc'
    assert url.slugify(u'\u00E0\u0042\u00E7\u010F\u00EB\u0066') == u'abcdef'
Exemple #7
0
    def generate_slug(self):
        # import this here due to a cyclic import issue
        # (db.models -> db.mixin -> db.util -> db.models)
        from mediagoblin.db.util import check_media_slug_used

        self.slug = slugify(self.title)

        duplicate = check_media_slug_used(mg_globals.database, self.uploader, self.slug, self.id)

        if duplicate:
            if self.id is not None:
                self.slug = u"%s-%s" % (self.id, self.slug)
            else:
                self.slug = None
Exemple #8
0
def edit_media(request, media):
    if not may_edit_media(request, media):
        raise Forbidden("User may not edit this media")

    defaults = dict(
        title=media.title,
        slug=media.slug,
        description=media.description,
        tags=media_tags_as_string(media.tags),
        license=media.license)

    form = forms.EditForm(
        request.form,
        **defaults)

    if request.method == 'POST' and form.validate():
        # Make sure there isn't already a MediaEntry with such a slug
        # and userid.
        slug = slugify(form.slug.data)
        slug_used = check_media_slug_used(media.uploader, slug, media.id)

        if slug_used:
            form.slug.errors.append(
                _(u'An entry with that slug already exists for this user.'))
        else:
            media.title = form.title.data
            media.description = form.description.data
            media.tags = convert_to_tag_list_of_dicts(
                                   form.tags.data)

            media.license = unicode(form.license.data) or None
            media.slug = slug
            media.save()

            return redirect_obj(request, media)

    if request.user.has_privilege(u'admin') \
            and media.uploader != request.user.id \
            and request.method != 'POST':
        messages.add_message(
            request, messages.WARNING,
            _("You are editing another user's media. Proceed with caution."))

    return render_to_response(
        request,
        'mediagoblin/edit/edit.html',
        {'media': media,
         'form': form})
Exemple #9
0
def edit_media(request, media):
    # If media is not processed, return NotFound.
    if not media.state == 'processed':
        return render_404(request)

    if not may_edit_media(request, media):
        raise Forbidden("User may not edit this media")

    defaults = dict(title=media.title,
                    slug=media.slug,
                    description=media.description,
                    tags=media_tags_as_string(media.tags),
                    license=media.license)

    form = forms.EditForm(request.method == 'POST' and request.form or None,
                          **defaults)

    if request.method == 'POST' and form.validate():
        # Make sure there isn't already a MediaEntry with such a slug
        # and userid.
        slug = slugify(form.slug.data)
        slug_used = check_media_slug_used(media.actor, slug, media.id)

        if slug_used:
            form.slug.errors.append(
                _('An entry with that slug already exists for this user.'))
        else:
            media.title = form.title.data
            media.description = form.description.data
            media.tags = convert_to_tag_list_of_dicts(form.tags.data)

            media.license = str(form.license.data) or None
            media.slug = slug
            media.save()

            return redirect_obj(request, media)

    if request.user.has_privilege('admin') \
            and media.actor != request.user.id \
            and request.method != 'POST':
        messages.add_message(
            request, messages.WARNING,
            _("You are editing another user's media. Proceed with caution."))

    return render_to_response(request, 'mediagoblin/edit/edit.html', {
        'media': media,
        'form': form
    })
Exemple #10
0
def convert_to_tag_list_of_dicts(tag_string):
    """
    Filter input from incoming string containing user tags,

    Strips trailing, leading, and internal whitespace, and also converts
    the "tags" text into an array of tags
    """
    slug_to_name = collections.OrderedDict()
    if tag_string:

        # Strip out internal, trailing, and leading whitespace
        stripped_tag_string = ' '.join(tag_string.strip().split())

        # Split the tag string into a list of tags
        for tag in stripped_tag_string.split(','):
            tag = tag.strip()
            # Ignore empty tags or duplicate slugs
            if tag:
                slug_to_name[url.slugify(tag)] = tag
    return [{'name': v, 'slug': k} for (k, v) in slug_to_name.items()]
Exemple #11
0
def convert_to_tag_list_of_dicts(tag_string):
    """
    Filter input from incoming string containing user tags,

    Strips trailing, leading, and internal whitespace, and also converts
    the "tags" text into an array of tags
    """
    taglist = []
    if tag_string:

        # Strip out internal, trailing, and leading whitespace
        stripped_tag_string = u' '.join(tag_string.strip().split())

        # Split the tag string into a list of tags
        for tag in stripped_tag_string.split(','):
            tag = tag.strip()
            # Ignore empty or duplicate tags
            if tag and tag not in [t['name'] for t in taglist]:
                taglist.append({'name': tag, 'slug': url.slugify(tag)})
    return taglist
Exemple #12
0
def convert_to_tag_list_of_dicts(tag_string):
    """
    Filter input from incoming string containing user tags,

    Strips trailing, leading, and internal whitespace, and also converts
    the "tags" text into an array of tags
    """
    slug_to_name = collections.OrderedDict()
    if tag_string:

        # Strip out internal, trailing, and leading whitespace
        stripped_tag_string = u' '.join(tag_string.strip().split())

        # Split the tag string into a list of tags
        for tag in stripped_tag_string.split(','):
            tag = tag.strip()
            # Ignore empty tags or duplicate slugs
            if tag:
                slug_to_name[url.slugify(tag)] = tag
    return [{'name': v, 'slug': k} for (k,v) in slug_to_name.items()]
Exemple #13
0
def convert_to_tag_list_of_dicts(tag_string):
    """
    Filter input from incoming string containing user tags,

    Strips trailing, leading, and internal whitespace, and also converts
    the "tags" text into an array of tags
    """
    taglist = []
    if tag_string:

        # Strip out internal, trailing, and leading whitespace
        stripped_tag_string = u' '.join(tag_string.strip().split())

        # Split the tag string into a list of tags
        for tag in stripped_tag_string.split(','):
            tag = tag.strip()
            # Ignore empty or duplicate tags
            if tag and tag not in [t['name'] for t in taglist]:
                taglist.append({'name': tag,
                                'slug': url.slugify(tag)})
    return taglist