Example #1
0
    def test_mapstory_actor_streams(self):
        action_list = get_actions_for_model('MapStory')
        initial_count = len(action_list)

        test_utils.create_mapstory(self.user, "Action Mapstory Test")
        final_count = len(action_list)

        # Action count should increase by one
        self.assertTrue(initial_count + 1, final_count)

        stream = actor_stream(self.user)
        self.assertEqual(len(stream), 1)
        self.assertEqual(self.user.id, stream[0].actor.id)

        test_utils.create_mapstory(self.user, "Action Mapstory Test 2")
        stream = actor_stream(self.user)
        self.assertEqual(len(stream), 2)

        # Create another actor and stream
        self.create_user('testactor', 'testactor1232432', is_superuser=False)
        other_user = get_user_model().objects.filter(username='******')[0]
        test_utils.create_mapstory(other_user, "Action Mapstory Test 3")
        other_stream = actor_stream(other_user)
        self.assertEqual(len(other_stream), 1)

        # The other actor's stream should not change
        same_stream = actor_stream(self.user)
        self.assertEqual(len(same_stream), 2)

        c = Collection.objects.create(name='default')
        icon = Icon.objects.create(collection=c, name='icon', owner=self.user)
        same_stream = actor_stream(self.user)
        self.assertEqual(len(same_stream), 3)
Example #2
0
    def test_icon_upload_streams(self):
        initial_count = len(actor_stream(self.user))

        c = Collection.objects.create(name='default')
        icon = Icon.objects.create(collection=c, name='icon', owner=self.user)

        final_count = len(actor_stream(self.user))
        self.assertEqual(initial_count + 1, final_count)
Example #3
0
    def test_user_actions_stream(self):
        # Register the things
        registry.register(Layer)
        registry.register(Comment)
        registry.register(Profile)

        # Should be empty
        actions = actor_stream(self.user)
        self.assertEqual(actions.count(), 0)

        # Create an action and check for updates.
        action.send(self.user, verb='reached level 10')
        admin_actions = actor_stream(self.user)
        self.assertEqual(admin_actions.count(), 1)
Example #4
0
 def get_queryset(self):
     stream_type = self.request.QUERY_PARAMS.get('type')
     try:
         content_type = int(self.request.QUERY_PARAMS.get('ct'))
         object_id = int(self.request.QUERY_PARAMS.get('pk'))
     except (TypeError, ValueError):
         return super(ActivityViewSet, self).get_queryset()
     ct = ContentType.objects.get(pk=content_type)
     self.request_object = ct.get_object_for_this_type(pk=object_id)
     if stream_type == 'actor':
         qs = actor_stream(self.request_object)
     elif stream_type == 'target':
         qs = target_stream(self.request_object)
     elif stream_type == 'ngo':
         qs = Action.objects.ngostream(self.request_object)
     elif stream_type == 'location':
         qs = Action.objects.location(self.request_object)
     else:
         qs = Action.objects.mystream(self.request_object)
     content_filter = self.content_filter()
     if content_filter is not None:
         qs = qs.filter(Q(action_object_content_type__pk=content_filter) |
                        Q(target_content_type__pk=content_filter))
     date_filter = self.date_filter()
     if date_filter is not None:
         qs = qs.filter(timestamp__gte=date_filter)
     return qs
Example #5
0
def profile_page(request, username):
	user = get_object_or_404(User, username=username)
	profile_info = get_object_or_404(UserProfile, user=user)
	awarded_list = Awarded.objects.filter(user=profile_info, earned=True)
	courses_created = Course.objects.filter(leader=user)
	activity = actor_stream(user)
	return render_to_response('profile_page.html', {'profile_info':profile_info, 'awarded_list':awarded_list, 'courses_created':courses_created, 'activity':activity[:15]}, context_instance=RequestContext(request))
Example #6
0
def get_actions_for_actor(actor):
    """
    Returns a list of actions for the given actor
    :param actor: (User) The action actor
    :return: (Action[]) An array of acstream Actions
    """
    return actor_stream(actor)
 def test_user4(self):
     self.assertSetEqual(actor_stream(self.user4), [
         'Four started blacklisting Three %s ago' % self.timesince,
         'Four started liking admin %s ago' % self.timesince,
         'Four started watching NiceGroup %s ago' % self.timesince,
         'Four started liking NiceGroup %s ago' % self.timesince,
     ])
Example #8
0
def user_settings(request):
    if request.method == 'POST':
        form = SettingsForm(request.POST, request.FILES)

        if form.is_valid():
            im = Image.open(request.FILES['profile_pic'])
            im = ImageOps.fit(im, (120, 120), Image.ANTIALIAS)

            if not os.path.exists(os.path.join(settings.MEDIA_ROOT, "profile")):
                os.makedirs(os.path.join(settings.MEDIA_ROOT, "profile"))

            im.save(os.path.join(settings.MEDIA_ROOT, "profile/{}.png".format(request.user.netid)))
            request.user.photo = "png"
            request.user.save()

            messages.success(request, 'Votre profil a été mis à jour.')

            return render(request, "users/settings.html", {'form': SettingsForm()})
    else:
        form = SettingsForm()

    return render(request, 'users/settings.html', {
        'form': form,
        'stream': actor_stream(request.user),
    })
Example #9
0
def actstream_actor_subset(request, content_type_id, object_id, sIndex, lIndex):
    """
    ``Actor`` focused activity stream for actor defined by ``content_type_id``,
    ``object_id``.
    """
    ctype = get_object_or_404(ContentType, pk=content_type_id)
    actor = get_object_or_404(ctype.model_class(), pk=object_id)
 
    activity_queryset = models.actor_stream(actor).order_by('-timestamp') 

    s = (int)(""+sIndex)
    l = (int)(""+lIndex)

    if s == 0 and 'batched_actor_actions' in request.session:
        del request.session['batched_actor_actions']

    activities = activity_queryset[s:l]
    if len(activities) == 0 and s != 0:
        ret_data = {
            'html': 'None',
            'more': False,
            'success': True
        }
        return HttpResponse(simplejson.dumps(ret_data), mimetype="application/json")

    batched_actions = merge_actor_actions_subset_op(request, activity_queryset, s, l)
    merged_batch_actions = request.session.get('batched_actor_actions',  dict())
    merged_batch_actions.update(batched_actions)
    request.session['batched_actor_actions'] = merged_batch_actions

    batched_ids = []
    for k, v in merged_batch_actions.items():
        batched_ids += v

    current_batched_ids = [ activity.id for activity in activities if activity.id not in batched_ids ]

    if len(current_batched_ids) == 0 and len(activities) > 0:
        ret_data = {
            'html': 'None',
            'more':True,
            'success': True
        }
        return HttpResponse(simplejson.dumps(ret_data), mimetype="application/json")

    context = RequestContext(request)
    context.update({
            'action_list': activities,
            'actor': actor,
            'ctype': ctype,
            'timeline': "true",
            'batched_actions':merged_batch_actions
        })

    ret_data = {
        'html': render_to_string(('actstream/actor_feed.html', 'activity/actor_feed.html'), context_instance=context).strip(),
        'success': True,
        'more':True
    }
    return HttpResponse(simplejson.dumps(ret_data), mimetype="application/json")
 def test_actor(self):
     response = self.get('actstream_actor', self.user_ct.pk, self.user2.pk)
     self.assertTemplateUsed(response, 'actstream/actor.html')
     self.assertTemplateUsed(response, 'base.html')
     self.assertEqual(response.context['ctype'], self.user_ct)
     self.assertEqual(response.context['actor'], self.user2)
     self.assertQSEqual(response.context['action_list'],
                        models.actor_stream(self.user2))
 def test_tag_activity_stream(self):
     output = render('''{% activity_stream 'actor' user as='mystream' %}
     {% for action in mystream %}
         {{ action }}
     {% endfor %}
     ''', user=self.user1)
     self.assertAllIn([str(action) for action in actor_stream(self.user1)],
                      output)
    def test_registration(self):
        instance = Unregistered.objects.create(name='fubar')
        self.assertRaises(ImproperlyConfigured, actor_stream, instance)
        register(Unregistered)
        self.assertEqual(actor_stream(instance).count(), 0)

        self.assertRaises(RuntimeError, model_stream, Abstract)
        self.assertRaises(ImproperlyConfigured, register, Abstract)
        unregister(Unregistered)
 def get_context_data(self, **kwargs):
     print self.object
     actionstream = actor_stream(self.object.user)
     print actionstream
     context = {
         'actstream': actionstream
     }
     context.update(kwargs)
     return super(UserProfileDetailView, self).get_context_data(**context)
def actor(request, content_type_id, object_id):
    """
    ``Actor`` focused activity stream for actor defined by ``content_type_id``, ``object_id``
    """
    ctype = get_object_or_404(ContentType, pk=content_type_id)
    actor = get_object_or_404(ctype.model_class(), pk=object_id)    
    return render_to_response('activity/actor.html', {
        'action_list': actor_stream(actor), 'actor':actor,'ctype':ctype
    }, context_instance=RequestContext(request))
Example #15
0
def profile_actions(request, username):
    "Custom renderer for user profile activity stream"
    profile = get_object_or_404(Profile, user__username__iexact=username)
    user = profile.user
    return render(request, "accounts/account_profile_actions.html", {
        'user': user,
        'profile': profile,
        'actions': models.actor_stream(user),
    })
def user(request, username):
    """
    ``User`` focused activity stream. (Eg: Profile page twitter.com/justquick)
    """
    user = get_object_or_404(User, username=username, is_active=True)
    return render_to_response('activity/actor.html', {
        'ctype': ContentType.objects.get_for_model(User),
        'actor':user,'action_list':actor_stream(user)
    }, context_instance=RequestContext(request))
 def test_user1(self):
     self.assertEqual(
         map(unicode, actor_stream(self.user1)),
         [
             u"admin commented on CoolGroup 0 minutes ago",
             u"admin started following Two 0 minutes ago",
             u"admin joined CoolGroup 0 minutes ago",
         ],
     )
Example #18
0
    def get_context_data(self, **kwargs):
        ctx = super(ProfileDetail, self).get_context_data(**kwargs)
        ctx['diary_entries'] = DiaryEntry.objects.filter(author=self.object).order_by('-date')
        ctx['favorites'] = Favorite.objects.filter(user=self.object).order_by('-created_on')
        ctx['threads_all'] = Thread.ordered(Thread.objects.inbox(self.request.user))
        ctx['threads_unread'] = Thread.ordered(Thread.objects.unread(self.request.user))
        ctx['action_list'] = actor_stream(ctx['profile'])

        return ctx
Example #19
0
def profile(request, user_id):
    if int(user_id) == 0:
        raise Http404  # mkay, no Anonymous profile
    user = get_object_or_404(User.objects.select_related(), pk=user_id)
    user_actions = actor_stream(user)[:10]
    badges = BadgeAward.objects.filter(user=user).order_by("-awarded_at")[:10]

    messages.info(request, "Please enable Javascript.", extra_tags="javascript")

    return {"profile_user": user, "user_actions": user_actions, "badges": badges}
Example #20
0
def profile(request, user_id):
    if int(user_id) == 0:
        raise Http404  # mkay, no Anonymous profile
    user = get_object_or_404(User.objects.select_related(), pk=user_id)
    user_actions = actor_stream(user)[:10]
    badges = BadgeAward.objects.filter(user=user).order_by("-awarded_at")[:10]

    messages.info(request, "Please enable Javascript.", extra_tags="javascript")

    return {"profile_user": user, "user_actions": user_actions, "badges": badges}
Example #21
0
    def get_context_data(self, **kwargs):

        # Call the base implementation first to get a context
        context = super(UserDetailView, self).get_context_data(**kwargs)
        user = User.objects.get(id=self.kwargs['pk'])
        context['noun'] = user
        context['available_verbs'] = None
        context['posts'] = user.profile.get_visible_posts(self.request.user)
        context['stream'] = actor_stream(user)
        return context
Example #22
0
def user(request, username):
    """
    ``User`` focused activity stream. (Eg: Profile page twitter.com/justquick)
    """
    user = get_object_or_404(User, username=username, is_active=True)
    return render_to_response('activity/actor.html', {
        'ctype': ContentType.objects.get_for_model(User),
        'actor': user,
        'action_list': actor_stream(user)
    },
                              context_instance=RequestContext(request))
Example #23
0
    def test_delete_node_utf8(self):
        nh = self.create_node(u'æøå-ftw', 'site', meta='Location')
        node = nh.get_node()

        self.assertEqual(u'æøå-ftw', nh.node_name)
        self.assertEqual(u'æøå-ftw', node.data.get('name'))

        helpers.delete_node(self.user, nh.handle_id)
        activities = actor_stream(self.user)
        self.assertEqual(1, len(activities))
        self.assertEqual(u'Site æøå-ftw', activities[0].data.get('noclook', {}).get('object_name'))
def actor(request, content_type_id, object_id):
    """
    ``Actor`` focused activity stream for actor defined by ``content_type_id``,
    ``object_id``.
    """
    ctype = get_object_or_404(ContentType, pk=content_type_id)
    instance = get_object_or_404(ctype.model_class(), pk=object_id)
    return render(request, 'actstream/actor.html', context={
        'action_list': models.actor_stream(instance), 'actor': instance,
        'ctype': ctype
    })
Example #25
0
def get_profile(request, profile_name):
    user = get_object_or_404(User, username=profile_name)
    user_d = user_to_dict(get_object_or_404(User, username=profile_name))
    user_d["following"] = following(user)
    user_d["followers"] = followers(user)
    user_d["actions"] = [dict(verb=x.verb,
                              object=x.action_object and user_to_dict(x.action_object),
                              when=int(x.timestamp.strftime("%s")) * 1000,
                              data=x.data)
                         for x in actor_stream(user)[:3]]
    return user_d
def actor(request, content_type_id, object_id):
    """
    ``Actor`` focused activity stream for actor defined by ``content_type_id``,
    ``object_id``.
    """
    ctype = get_object_or_404(ContentType, pk=content_type_id)
    actor = get_object_or_404(ctype.model_class(), pk=object_id)
    return render_to_response(('actstream/actor.html', 'activity/actor.html'), {
        'action_list': models.actor_stream(actor), 'actor': actor,
        'ctype': ctype
    }, context_instance=RequestContext(request))
Example #27
0
def profile_actions(request, username):
    "Custom renderer for user profile activity stream"
    profile = get_object_or_404(Profile, user__username__iexact=username)
    if profile.user.username != username:
        return redirect(profile, permanent=True)
    user = profile.user
    return render(request, "accounts/account_profile_actions.html", {
        'user': user,
        'profile': profile,
        'actions': models.actor_stream(user),
    })
def actor(request, content_type_id, object_id):
    """
    ``Actor`` focused activity stream for actor defined by ``content_type_id``,
    ``object_id``.
    """
    ctype = get_object_or_404(ContentType, pk=content_type_id)
    instance = get_object_or_404(ctype.model_class(), pk=object_id)
    return render_to_response(
        "actstream/actor.html",
        {"action_list": models.actor_stream(instance), "actor": instance, "ctype": ctype},
        context_instance=RequestContext(request),
    )
Example #29
0
def user_timeline(request, username):
    user = User.objects.select_related('profile').get(username=username)
    user_actions = []

    if is_following(request.user, user) or not user.profile.private:
        user_actions = actor_stream(user)

    context = {
        'user': user,
        'activities': user_actions,
    }
    return render(request, 'timeline.html', context)
Example #30
0
    def get_context_data(self, **kwargs):
        ctx = super(ProfileDetail, self).get_context_data(**kwargs)
        ctx['diary_entries'] = DiaryEntry.objects.filter(
            author=self.object).order_by('-date')
        ctx['favorites'] = Favorite.objects.filter(
            user=self.object).order_by('-created_on')
        ctx['threads_all'] = Thread.ordered(Thread.objects.inbox(self.object))
        ctx['threads_unread'] = Thread.ordered(
            Thread.objects.unread(self.object))
        ctx['action_list'] = actor_stream(ctx['profile'])

        return ctx
Example #31
0
def actor(request, content_type_id, object_id):
    """
    ``Actor`` focused activity stream for actor defined by ``content_type_id``,
    ``object_id``.
    """
    ctype = get_object_or_404(ContentType, pk=content_type_id)
    instance = get_object_or_404(ctype.model_class(), pk=object_id)
    return render(
        request, 'actstream/actor.html', {
            'action_list': models.actor_stream(instance),
            'actor': instance,
            'ctype': ctype
        })
Example #32
0
    def test_custom_delete_actstream(self):

        c = Client()
        c.login(username='******', password='******')
        user = auth.get_user(c)

        dt = DummyType.objects.get(pk=1)

        response = c.delete('/rest/dummyType/%d' % dt.id)
        self.assertEquals(response.status_code, 204, response.content)

        action = actor_stream(user)[0]
        self.assertEquals(action.actor, user)
        self.assertEquals(action.verb, 'delete')
Example #33
0
    def test_custom_put_actstream(self):
        data = dict(name='Alter dummy type')

        c = Client()
        c.login(username='******', password='******')
        user = auth.get_user(c)

        response = c.put('/rest/dummyType/1', json.dumps(data),
                            content_type='application/json', follow=True)

        action = actor_stream(user)[0]
        self.assertEquals(action.actor, user)
        self.assertEquals(action.verb, 'update')
        self.assertEquals(action.target.pk, 1)
Example #34
0
    def test_custom_post_actstream(self):
        data = dict(name='New dummy type')

        c = Client()
        c.login(username='******', password='******')
        user = auth.get_user(c)

        response = c.post('/rest/dummyType', json.dumps(data),
                            content_type='application/json', follow=True)
        data = json.loads(response.content)['result']

        action = actor_stream(user)[0]
        self.assertEquals(action.actor, user)
        self.assertEquals(action.verb, 'create')
        self.assertEquals(action.target.pk, data['id'])
Example #35
0
def userprofile_detail(request, userprofile_id):
    profile = get_object_or_404(UserProfile, pk=userprofile_id)
    activities = actor_stream(profile.user)
    paginator = Paginator(activities, 50, allow_empty_first_page=True)  # Show 50 activities per page
    page = request.GET.get('page')
    try:
        activities = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        activities = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        activities = paginator.page(paginator.num_pages)
    return render(request, 'userprofile/userprofile_detail.html',
                  {'profile': profile, 'activities': activities})
Example #36
0
    def get_context_data(self, **kwargs):
        ctx = super(ProfileDetail, self).get_context_data(**kwargs)
        ctx['diary_entries'] = DiaryEntry.objects.filter(author=self.object).order_by('-date')
        ctx['favorites'] = Favorite.objects.filter(user=self.object).order_by('-created_on')
        ctx['threads_all'] = Thread.ordered(Thread.objects.inbox(self.object))
        ctx['threads_unread'] = Thread.ordered(Thread.objects.unread(self.object))
        ctx['action_list'] = actor_stream(ctx['profile'])
        # need to render the form
        ctx['form'] = UploadFileForm()
        notice_settings = []
        for notice in NoticeType.objects.filter(label__in=PROFILE_NOTICE_SETTINGS):
            notice_settings.append(NoticeSetting.for_user(self.object, notice, NOTICE_MEDIA[0][0]))
        ctx['notice_settings'] = notice_settings

        return ctx
Example #37
0
    def get_context_data(self, **kwargs):
        is_current = self.request.user == self.profile_user

        ctx = {
            "is_current": is_current,
            "profile_user": self.profile_user,
        }

        if is_current:
            ctx.update({"activity_stream": user_stream(self.profile_user)})
        else:
            ctx.update({"activity_stream": actor_stream(self.profile_user)})

        ctx.update(super(ProfileDetailView, self).get_context_data(**kwargs))

        return ctx
Example #38
0
    def get_context_data(self, **kwargs):
        ctx = super(ProfileDetail, self).get_context_data(**kwargs)
        ctx['diary_entries'] = DiaryEntry.objects.filter(author=self.object).order_by('-date')
        ctx['favorites'] = Favorite.objects.filter(user=self.object).order_by('-created_on')
        ctx['icons'] = Icon.objects.filter(owner=self.object)
        ctx['threads_all'] = Thread.ordered(Thread.objects.inbox(self.object))
        ctx['threads_unread'] = Thread.ordered(Thread.objects.unread(self.object))
        ctx['action_list'] = actor_stream(ctx['profile'])
        # need to render the form
        ctx['form'] = UploadFileForm()
        notice_settings = []
        for notice in NoticeType.objects.filter(label__in=PROFILE_NOTICE_SETTINGS):
            notice_settings.append(NoticeSetting.for_user(self.object, notice, NOTICE_MEDIA[0][0]))
        ctx['notice_settings'] = notice_settings

        return ctx
Example #39
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        posts = self.object.post_set.all().order_by('-created')[:10]
        replies = self.object.reply_comments.all().order_by(
            '-submit_date')[:10]

        actions = actor_stream(self.object)

        if self.object != self.request.user:
            actions = actions.exclude(verb__startswith='un')

        context.update({
            'post_list': posts,
            'reply_list': replies,
            'action_list': actions[:20],
        })
        return context
Example #40
0
    def get_context_data(self, **kwargs):
        '''
		here we are getting all the feeds associated with an individual user and if the actor is the user
		then we will display it on the profile page else it will be displayed in the feeds page.
		'''
        context = super(UserProfileDetailView, self).get_context_data(**kwargs)
        # here we get the user profile object which we will use to pass to the actor_stream()
        # and generate the profile stream

        profile = self.get_object()
        # passing the actor_stream as a context var
        context['user_feeds'] = actor_stream(profile)
        # getting the user followers and user followee based on the user
        context['followers'] = self.get_user_followers()
        context['followees'] = self.get_user_followee()
        context['follower_count'] = self.get_follower_count()
        return context
Example #41
0
    def test_delete_actstream(self):
        data = dict(name='My dummy one more',
                    dummy_type={'id': 1})

        c = Client()
        c.login(username='******', password='******')
        user = auth.get_user(c)

        response = c.post('/rest/dummy', json.dumps(data),
                            content_type='application/json', follow=True)
        content = json.loads(response.content)['result']
        id = content['id']
        response = c.delete('/rest/dummy/%d' % id)

        action = actor_stream(user)[0]
        self.assertEquals(action.actor, user)
        self.assertEquals(action.verb, 'apagou')
        self.assertEquals(action.description, 'Dummy object')
Example #42
0
    def get_context_data(self, **kwargs):
        ctx = super(ProfileDetail, self).get_context_data(**kwargs)
        ctx['journal_entries'] = JournalEntry.objects.filter(
            author=self.object).order_by('-date')
        ctx['journal_entries_total'] = JournalEntry.objects.filter(
            author=self.object).count()
        ctx['journal_entries_published'] = JournalEntry.objects.filter(
            author=self.object, publish=True).count()
        ctx['favorites'] = Favorite.objects.filter(
            user=self.object).order_by('-created_on')
        ctx['icons'] = Icon.objects.filter(owner=self.object)
        ctx['action_list'] = actor_stream(ctx['profile'])
        # need to render the form
        ctx['form'] = UploadFileForm()
        ctx['interests'] = json.dumps(
            self.object.mapstoryprofile.interests_slug_list())

        return ctx
Example #43
0
    def get_context_data(self, **kwargs):
        ctx = super(ProfileDetail, self).get_context_data(**kwargs)
        ctx['journal_entries'] = JournalEntry.objects.filter(
            author=self.object).order_by('-date')
        ctx['journal_entries_total'] = JournalEntry.objects.filter(
            author=self.object).count()
        ctx['journal_entries_published'] = JournalEntry.objects.filter(
            author=self.object, publish=True).count()
        ctx['favorites'] = Favorite.objects.filter(
            user=self.object).order_by('-created_on')
        ctx['icons'] = Icon.objects.filter(owner=self.object)
        ctx['action_list'] = actor_stream(ctx['profile'])
        # need to render the form
        ctx['form'] = UploadFileForm()
        ctx['interests'] = json.dumps(
            self.object.mapstoryprofile.interests_slug_list())

        return ctx
Example #44
0
 def get_queryset(self):
     stream_type = self.request.QUERY_PARAMS.get('type')
     try:
         content_type = int(self.request.QUERY_PARAMS.get('ct'))
         object_id = int(self.request.QUERY_PARAMS.get('pk'))
     except (TypeError, ValueError):
         return super(ActivityViewSet, self).get_queryset()
     ct = ContentType.objects.get(pk=content_type)
     self.request_object = ct.get_object_for_this_type(pk=object_id)
     if stream_type == 'actor':
         return actor_stream(self.request_object)
     elif stream_type == 'target':
         return target_stream(self.request_object)
     elif stream_type == 'ngo':
         return Action.objects.ngostream(self.request_object)
     elif stream_type == 'location':
         return Action.objects.location(self.request_object)
     else:
         return Action.objects.mystream(self.request_object)
Example #45
0
    def obj_get_list(self, request=None, **kwargs):
        user = kwargs.pop('user', None)
        a_map = kwargs.pop('map', None)


        if user:
            object_list = actor_stream(user)
        elif a_map:
            object_list = ActivityManager().related_to_map(a_map)
        else:
            object_list = user_stream(request.user)

        if request.GET.has_key('since'):
            since = dateutil.parser.parse(request.GET['since'])
            base_object_list = object_list.filter(timestamp__gte=since)
        else:
            base_object_list = object_list

        return self.apply_authorization_limits(request, base_object_list)
Example #46
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        articles = self.object.a_author.all().defer('content')[:10]
        pictures = self.object.p_author.all()[:10]

        if self.request.user.is_authenticated:
            actions = actor_stream(self.object)[:20]
            user = User.objects.get(nickname=self.request.user)
            try:
                user.followers.get(follow_object=self.object.id)
                is_follow = True
            except:
                is_follow = False
        else:
            actions = {}
            is_follow = False

        context.update({
            'article_list': articles,
            'picture_list': pictures,
            'action_list': actions,
            'is_follow': is_follow,
        })
        return context
Example #47
0
def profile_activity(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    return {"profile_user": user, "actions": actor_stream(user)}
Example #48
0
def profile_activity(request, user_id):
    user = get_object_or_404(User, pk=user_id)
    return {
        'profile_user': user,
        'actions': actor_stream(user),
    }
Example #49
0
def actor_actions(actor, request):
    object_list = [_steroid_action(action) for action in actor_stream(actor)]
    paginator = Paginator(object_list, per_page=10)
    page = cyclope.utils.get_page(paginator, request)
    return page
Example #50
0
    def get_context_data(self, **kwargs):
        context = super(ProfileDetailView, self).get_context_data(**kwargs)

        section_menu = self.get_section_menu(object=self.object, section=self.section)

        ###############################################################
        # generic context, needed for all sections
        ###############################################################
        context.update({
            'section': self.section,
            'section_menu': section_menu,
            'section_template': self.get_section_template(),
        })

        ###############################################################
        # section specific context
        ###############################################################
        if self.section == 'playlists':
            playlist_qs = self.object.user.playlists.exclude(type='basket').order_by('-created')
            playlist_qs = playlist_qs.select_related(
                'user',
            ).prefetch_related(
                'items',
                'emissions',
            )
            context.update({
                'playlists': playlist_qs,
            })

        if self.section == 'uploads':
            release_qs = Release.objects.filter(
                creator=self.object.user
            ).select_related(
                'label',
                'release_country',
                'creator',
                'creator__profile',
            ).prefetch_related(
                'media',
                'media__artist',
                'media__license',
                'extra_artists',
                'album_artists',
            ).order_by('-created')

            media_qs = Media.objects.filter(
                creator=self.object.user
            ).select_related(
                'release',
                'artist',
            ).prefetch_related(
                'media_artists',
                'extra_artists',
            ).order_by('-created')

            context.update({
                'uploads': {
                    'releases': release_qs,
                    'media': media_qs,
                },
            })

        if self.section == 'votes':
            vote_qs = self.object.user.votes.order_by('-created').prefetch_related('content_object')

            upvotes = [v for v in vote_qs if v.vote > 0]
            downvotes = [v for v in vote_qs if v.vote < 0]

            context.update({
                'upvotes': upvotes,
                'downvotes': downvotes,
            })

        if self.section == 'activities':
            activity_qs = actor_stream(self.object.user).select_related(
                # 'actor_content_type',
                # 'target_content_type',
                # 'action_object_content_type',
            ).prefetch_related(
                'actor',
                'target',
                'action_object',
            ).order_by('-pk')

            # activity_qs = Action.objects.filter(
            #     actor_content_type__id=3,
            #     actor_object_id=self.object.user.pk
            # ).order_by('-pk')

            context.update({
                'activities': activity_qs,
            })


        return context
Example #51
0
 def test_user2(self):
     self.assertEqual(map(unicode, actor_stream(self.user2)), [
         u'Two started following CoolGroup 0 minutes ago',
         u'Two joined CoolGroup 0 minutes ago'
     ])
Example #52
0
    def get_context_data(self, **kwargs):
        # get the user for this profile page
        user = get_r_object_or_404(self.request.user,
                                   get_user_model(),
                                   username=self.kwargs.get("username"))
        # get the actor stream for the requested user profil
        item_list = cache.get('activity_items_actor_' + user.username)
        if not item_list:
            item_list = actor_stream(user)
            cache.set('activity_items_actor_' + user.username, item_list,
                      60 * 60 * 24 * 31)

        # filter out actions with targets the requesting user is not part of
        self.item_list = check_activity_permissions(self.request.user,
                                                    item_list)

        # get this user
        selfuser = get_r_object_or_404(self.request.user,
                                       get_user_model(),
                                       username=self.request.user.username)
        sharedprojects = Project.objects.filter(developer=user).filter(
            developer=selfuser)
        sharedissues = Issue.objects.filter(assignee=user).filter(
            assignee=selfuser)

        # create the context
        context = super(ShowProfilePageView, self).get_context_data(**kwargs)
        context['sharedprojects'] = sharedprojects
        context['sharedissues'] = sharedissues
        context['nocollapse'] = self.request.session.get('nocollapse', '')
        if context['nocollapse'] != '':
            del self.request.session['nocollapse']

        # add data for notifications

        prefs = {}
        try:
            prefs = json.loads(user.get_preference('notify_mail'))
        except (TypeError, json.JSONDecodeError):
            pass

        # there shall be an entry for every project the user is member of
        for uproj in user.get_projects():
            if uproj.name_short not in prefs:
                prefs[uproj.name_short] = []

        context['notify_mail'] = prefs

        notitypes = []

        for t in Notitype.NOTI_TYPES:
            notitypes.append([t[0], t[1]])

        context['possible_notis'] = notitypes

        # add data for activity chart type
        if self.request.GET.get('data') is not None:
            self.request.user.set_preference('activity_chart_type',
                                             self.request.GET.get('data'))
        data = self.request.user.get_preference('activity_chart_type',
                                                default="timelog")
        context['chart_type'] = data

        return context
Example #53
0
def profile_page(request, username):
    try:
        u = User.objects.get(username=username)
    except ObjectDoesNotExist:
        raise Http404('Requested user not found')

    try:
        us = user.objects.get(username=username)
    except ObjectDoesNotExist:
        raise Http404('Requested user not found!')

    if User.is_authenticated:
        a_user = request.user.username
        if (a_user == username):
            follow = 0
        else:
            follow = 1

    if request.POST.get('click'):
        if User.is_authenticated:
            a_user = request.user.username
        a_u = user.objects.get(username=a_user)
        f = a_u.following_set.create(fn_username=username)
        f.save()
    '''variable declarations for user table'''
    username = us.username
    first_name = us.first_name
    last_name = us.last_name
    gender = us.gender
    dob = us.dob
    native_l = us.native_l
    state = us.state
    country = us.country
    email = us.email
    phone = us.phone
    '''variable declarations for friends table'''
    friends = us.friends_set.all()
    '''variable declarations for status table'''
    status = us.status_set.all()
    '''variable declarations for questions table'''
    questions = us.questions_set.all()
    '''variable declarations for answers table'''
    answers = us.answers_set.all()
    '''variable declarations for books table'''
    books = us.books_set.all()
    '''variable declarations for sites table'''
    sites = us.sites_set.all()
    '''variable declarations for status table'''

    if len(status) == 0:
        length = 0
    else:
        s = us.status_set.all()
        length = len(status) - 1
        status = s[length].status_text
    '''variable declaration for personal actor stream'''
    personal_stream = actor_stream(us)

    form = Ask_questionForm(request.POST)
    if request.method == 'POST' and form.is_valid():
        q = us.questions_set.create(
            q_title=form.cleaned_data['q_title'],
            q_desc=form.cleaned_data['q_desc'],
        )
        q.save()
        action.send(us, verb='asked a question', action_object=q)
        return HttpResponseRedirect('/user/' + str(username) + '/')

    else:
        form = Ask_questionForm()

    variables = RequestContext(
        request, {
            'first_name': first_name,
            'last_name': last_name,
            'gender': gender,
            'dob': dob,
            'native_l': native_l,
            'state': state,
            'country': country,
            'email': email,
            'phone': phone,
            'friends': friends,
            'status': status,
            'questions': questions,
            'answers': answers,
            'books': books,
            'sites': sites,
            'personal_stream': personal_stream,
            'follow': follow,
        })

    return render_to_response('profile_page.html', variables)
Example #54
0
 def test_group(self):
     self.assertSetEqual(actor_stream(self.group), [
         'CoolGroup responded to admin: Sweet Group!... '
         '%s ago' % self.timesince
     ])
Example #55
0
 def test_user2(self):
     self.assertSetEqual(actor_stream(self.user2), [
         'Two started following CoolGroup %s ago' % self.timesince,
         'Two joined CoolGroup %s ago' % self.timesince,
     ])
Example #56
0
 def get_queryset(self):
     return actor_stream(
         get_object_or_404(User, username=self.kwargs.get('username')))
Example #57
0
 def test_user1(self):
     self.assertEqual(map(unicode, actor_stream(self.user1)), [
         u'admin commented on CoolGroup 0 minutes ago',
         u'admin started following Two 0 minutes ago',
         u'admin joined CoolGroup 0 minutes ago'
     ])
Example #58
0
    def test_layer_activity(self):
        """
        Tests the activity functionality when a layer is saved.
        """

        # A new activity should be created for each Layer.
        self.assertEqual(Action.objects.all().count(), Layer.objects.all().count())

        action = Action.objects.all()[0]
        layer = action.action_object

        # The activity should read:
        # layer.owner (actor) 'uploaded' (verb) layer (object)
        self.assertEqual(action.actor, action.action_object.owner)
        self.assertEqual(action.data.get('raw_action'), 'created')
        self.assertEqual(action.data.get('object_name'), layer.name)
        self.assertTrue(isinstance(action.action_object, Layer))
        self.assertIsNone(action.target)

        # Test the  activity_item template tag
        template_tag = activity_item(Action.objects.all()[0])

        self.assertEqual(template_tag.get('username'), action.actor.username)
        self.assertEqual(template_tag.get('object_name'), layer.name)
        self.assertEqual(template_tag.get('actor'), action.actor)
        self.assertEqual(template_tag.get('verb'), _('uploaded'))
        self.assertEqual(template_tag.get('action'), action)
        self.assertEqual(template_tag.get('activity_class'), 'upload')

        layer_name = layer.name
        layer.delete()

        # <user> deleted <object_name>
        action = Action.objects.all()[0]

        self.assertEqual(action.data.get('raw_action'), 'deleted')
        self.assertEqual(action.data.get('object_name'), layer_name)

        # objects are literally deleted so no action object or target should be related to a delete action.
        self.assertIsNone(action.action_object)
        self.assertIsNone(action.target)

        # Test the activity_item template tag
        action = Action.objects.all()[0]
        template_tag = activity_item(action)

        # Make sure the 'delete' class is returned
        self.assertEqual(template_tag.get('activity_class'), 'delete')

        # The layer's name should be returned
        self.assertEqual(template_tag.get('object_name'), layer_name)
        self.assertEqual(template_tag.get('verb'), _('deleted'))

        content_type = ContentType.objects.get_for_model(Layer)
        layer = Layer.objects.all()[0]
        comment = Comment(author=self.user,
                          content_type=content_type,
                          object_id=layer.id,
                          comment="This is a cool layer.")
        comment.save()

        action = Action.objects.all()[0]

        self.assertEqual(action.actor, self.user)
        self.assertEqual(action.data.get('raw_action'), 'created')
        self.assertEqual(action.action_object, comment)
        self.assertEqual(action.target, layer)

        template_tag = activity_item(action)

        # <user> added a comment on <target>
        self.assertEqual(template_tag.get('verb'), _('added a comment'))
        self.assertEqual(template_tag.get('activity_class'), 'comment')
        self.assertEqual(template_tag.get('target'), action.target)
        self.assertEqual(template_tag.get('preposition'), _('on'))
        self.assertIsNone(template_tag.get('object'))
        self.assertEqual(template_tag.get('target'), layer)

        # Pre-fecthing actstream breaks the actor stream
        self.assertIn(action, actor_stream(self.user))
Example #59
0
 def test_group(self):
     self.assertEqual(
         map(unicode, actor_stream(self.group)),
         [u'CoolGroup responded to admin: Sweet Group!... 0 minutes ago'])
Example #60
0
 def get_queryset(self):
     return actor_stream(self.request.user)