def addTags(obj, tags):
    """Adds tags from a supplied list to an object of type Profile or Post.
    Returns nothing.
    
    Creates a new Tag object if tag is new to the system.
    Will not create duplicates but will add to interest of pre-existing Tag objects.
    """
    passed = ""
    for tag in tags:
        if len(tag) < System.maxTag:
            cleanTag = ' '.join(tag.split())
            if Tag.objects.filter(name=cleanTag).count():
                t = Tag.objects.filter(name=cleanTag.lower()).order_by('?')[0]
                t.interest += 1
                t.save()
            else:
                t = Tag(name=cleanTag.lower(), interest=1)
                t.save()
            if isinstance(obj, Post):
                obj.post_profile.tags.add(t)  
                obj.post_profile.save()  
            obj.tags.add(t)
            passed += cleanTag + ', '
    obj.save()
    return passed[:-2]
Пример #2
0
def update_comment_tags(request, comment_id, tags):
    comment = get_object_or_404(models.Comment, pk=comment_id)
    if request.user.is_staff or request.user == comment.author:
        new_tags = set(tags)
        original = comment.tags.smembers()

        # tags to remove
        for t in (original - new_tags):
            Tag(t).untag_comment(comment)
            comment.tags.srem(t)

        # tags to add
        for t in (new_tags - original):
            Tag(t).tag_comment(comment)
            comment.tags.sadd(t)

        comment.details.force()
        ret_tags = []
        for t in comment.tags.smembers():
            ret_tags += [{
                'name': t,
                'url': Tag(t).get_absolute_url(),
            }]

        return {'tags': ret_tags}

    else:
        raise ServiceError("Permission denied")
Пример #3
0
 def test_create_tag(self):
     count_tags = Tag.objects.count()
     tag = Tag(name='Linux-по-русски')
     tag.full_clean()
     tag.save()
     self.assertEqual(Tag.objects.count(), count_tags + 1)
     self.assertEqual(tag.name, 'Linux-по-русски')
Пример #4
0
def update(tagsstr):
  tags_strlist = tagsstr_to_taglist(tagsstr)
  tags = list(Tag.objects.filter(text__in=tags_strlist))
  existing_strlist = map(lambda tag: tag.text, tags)
  for tag_str in set(tags_strlist).difference(set(existing_strlist)):
    # TODO howto save in one query?
    tag = Tag()
    tag.text = tag_str
    tag.save()
    tags.append(tag)
  return tags
Пример #5
0
def update(tagsstr):
    tags_strlist = tagsstr_to_taglist(tagsstr)
    tags = list(Tag.objects.filter(text__in=tags_strlist))
    existing_strlist = map(lambda tag: tag.text, tags)
    for tag_str in set(tags_strlist).difference(set(existing_strlist)):
        # TODO howto save in one query?
        tag = Tag()
        tag.text = tag_str
        tag.save()
        tags.append(tag)
    return tags
def setupOpen(pop):

    #SETUP ABANDONED PROFILES
    if pop > 1:
        populate(pop)
    #profiles = Profile.objects.all()
    #for p in profiles:
    #    makeFriends(p)
    
    #SETUP TAGS
    for t in initialTags():
        d = Tag(name=t)
        d.save()
        
    #MAKE RANGER
    ranger = Profile(
        fname='Ranger',
        lname='Lyman',
        gender=Gender.female,
        age=30,
        location='Indianapolis, Indiana',
        last_login=timezone.now(),
        species=Species.system,
        img_number=1,
        energy=1983,
        visible=True
    )
    ranger.save()
    rangerPost = "Thank you for visiting the openspace wilderness. I am here to assist you as well as post occasional updates and additional info about the park. Have fun exploring, and be careful out there in the wilds."
    makeTaggedPost(ranger, rangerPost, 'protected')
    
    #SEED Visitor
    makeAnonymous()
    
    #SEED PREY PROFILES
    for p in initialPreyProfiles():
        newProfile = Profile(
            fname=p['fname'],
            lname=p['lname'],
            gender=p['gender'],
            age=p['age'],
            location=p['location'],
            last_login=timezone.now(),
            species=Species.forager,
            energy=System.energy,
            visible=False
        )
        newProfile.save()
        assignImages(newProfile)
        makeBirthPost(newProfile)
Пример #7
0
def _get_tagged_from_redis(viewer, nav):
    comments = Comment.browse_objects

    if nav.sort == 'hot':
        ids = _get_hot_slice_by_threads(Tag(nav.tag).popular, nav.slice)
        comments = comments.exclude(reply_content__id=None)

    elif nav.sort == 'top':
        # this is so gross
        ids = nav.get_top_data(Tag(nav.tag))[nav.slice]
    else:
        ids = Tag(nav.tag).images_only[nav.slice]

    # Remove user-hidden comments.
    ids = remove_hidden_comment_ids(viewer, ids)

    return comments.in_bulk_list(ids)
Пример #8
0
    def handle(self, *args, **options):
        today = datetime.date.today()

        categories = [Category.ALL] + list(Category.objects.all())

        for category in categories:
            category.merge_top_scores(today)

        for tag in all_tags.smembers():
            Tag(tag).merge_top_scores(today)
Пример #9
0
 def create(self):
     data = self.validated_data
     source_data = {
         "source": data.pop("source", None),
         "source_ref": data.pop("source_ref", None),
     }
     if all(source_data.values()):
         ts = self.create_source(source_data)
     else:
         ts = None
     return Tag(**data, source=ts)
Пример #10
0
def followed_tags_context(request):
    following = []

    if request.user.is_authenticated():
        following = request.user.redis.followed_tags.zrevrange(
            0, knobs.FOLLOWED_TAGS_SHOWN)

    tag_channels = []
    for tag in following:
        tag_channels.append(Tag(tag).updates_channel.sync())

    return {
        'followed_tags': following,
        'tag_channels': tag_channels,
    }
Пример #11
0
    def forwards(self, orm):
        "Write your forwards methods here."

        count = 0

        for c in orm.Comment.objects.all():
            if c.visibility in [Visibility.PUBLIC, Visibility.CURATED] and c.reply_content is not None:
                tags = RedisSet("comment:{}:tags".format(c.id)).smembers()
                for tag in tags:
                    t = Tag(tag)
                    t.images_only.bump(c.id, score=c.timestamp)

            count += 1
            if count % 10000 == 0:
                print count
Пример #12
0
    def handle(self, *args, **kwargs):
        self.stdout.write('Start...')

        path = kwargs.get('path')
        if not path:
            raise CommandError('Path is required')

        with open(path, 'r',
                  encoding=settings.MIGRATE_FILE_ENCODING) as csvfile:
            reader = csv.reader(csvfile)

            tags = []
            for row in reader:

                tags.append(Tag(name=row[7], ext_id=row[0]))
        Tag.objects.bulk_create(tags, batch_size=100)
        self.stdout.write('End...')
Пример #13
0
    def forwards(self, orm):
        "Write your forwards methods here."

        count = 0

        for c in orm.Comment.objects.all():
            if c.category is not None:
                cname = c.category.name
                tags = RedisSet("comment:{}:tags".format(c.id))
                if tags.scard() == 0:
                    tags.sadd(cname)

                Tag(cname).tag_comment(c, c.timestamp)


            count += 1
            if count % 10000 == 0:
                print count
Пример #14
0
def front_comments_view(request, sort, category=None, tag=None, homepage=False, **kwargs):
    # category here should always be a first-class Category object.
    if not isinstance(category, CategoryMixin) and tag is None:
        raise Http404()

    user = request.user

    show_pins = request.user.is_authenticated()

    if not request.user.is_authenticated() and sort == 'hot' and category == Category.ALL:
        sort_type = request.GET.get('hot_sort_type', 'order_by_time_plus_log_stickers_and_replies')
        if sort_type != 'control':
            kwargs['hot_sort_type'] = sort_type

    kwargs['offset'] = request.GET.get('offset', 0)

    nav = browse.Navigation.load_json_or_404(
        kwargs,
        sort=sort,
        category=category,
        tag=tag,
        mobile=request.is_mobile,
    )

    front_data = {
        'tiles':          browse.get_browse_tiles(request.user, nav),
        'render_options': tile_render_options(sort, show_pins),
        'viewer_is_following_tag': tag and Tag(tag).user_is_following(request.user)
    }

    #TODO delete once we've resolved the missing small_image issue.
    for tile in front_data['tiles']:
        if hasattr(tile, 'check_for_small_image'):
            tile.check_for_small_image(request)

    # Overrides the default nav category that gets set in a context processor.
    if category is not None:
        request.nav_category = category

    if tag is not None:
        request.nav_tag = tag
        popular_tag_link = "/x/{}".format(tag)
        latest_tag_link = "/x/{}/new".format(tag)
        best_tag_link = "/x/{}/best".format(tag)
    else:
        popular_tag_link = "/x/everything"
        latest_tag_link = "/x/everything/new"
        best_tag_link = "/x/everything/best"

    timeperiods = []
    if sort =='top' and category is not None:
        timeperiods = top_timeperiod_urls(category.name)
        active_period_url = top_url(category.name, kwargs.get('year'), kwargs.get('month'), kwargs.get('day'))

    sort_types = []
    if category is not None:
        if sort in ["active", "new"]:
            sort_types.extend([
                ('active threads', '/x/%s/active' % category.name),
                ('new posts', '/x/%s/new' % category.name)
            ])
            active_sort_url = '/x/%s/%s' % (category.name, sort)

    nav_data = nav.dump_json()

    front_data.update(locals())

    if request.is_mobile:
        return r2r_jinja("mobile/browse.html", front_data)

    return r2r_jinja("comment/explore.html", front_data)
Пример #15
0
 def tags(self):
     return [Tag(tag) for tag in self._d['tags']]