def test_stream(self): self.assertSetEqual(user_stream(self.user1), [ 'Two started following CoolGroup 0 minutes ago', 'Two joined CoolGroup 0 minutes ago', ]) self.assertSetEqual(user_stream(self.user2), ['CoolGroup responded to admin: Sweet Group!... 0 minutes ago'])
def get(self, request): from actstream.models import user_stream user_stream(request.user, with_user_activity=True) serializer = ShortUserSerializer(request.user) return Response(serializer.data)
def activity(request): if request.is_ajax(): queryset = models.user_stream(request.user) paginator = Paginator(queryset, 10) page = request.GET.get('page') try: action_list = paginator.page(page) except PageNotAnInteger: raise Http404 except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. action_list = paginator.page(paginator.num_pages) return render_to_response('actstream/update_list.html',{ 'action_list': action_list, }) else: queryset = models.user_stream(request.user) paginator = Paginator(queryset, 10) try: action_list = paginator.page(1) except PageNotAnInteger: raise Http404 except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. action_list = paginator.page(paginator.num_pages) return render(request, 'actstream/update.html', { 'ctype': ContentType.objects.get_for_model(User), 'actor': request.user, 'action_list': action_list, 'following': models.following(request.user), 'followers': models.followers(request.user), 'recommends': recommendations.recommendRecipeForUser(request.user.id, 10) })
def test_users_can_see_other_users_activity_in_their_feeds_on_the_model_side(self): u = UserFactory() follow(u, self.profile_to_follow.user) ds = DivesiteFactory(owner=self.profile_to_follow.user) self.assertEqual(len(user_stream(u)), 1) a = user_stream(u)[0] self.assertEqual(a.actor_object_id, str(self.profile_to_follow.user.id))
def user(request, id): loggedinUser = request.user player = User.objects.get(pk=id) if player == loggedinUser: return redirect('/profile') print user_stream(request.user) games_created = Game.objects.filter(creator=player) games_played = player.game_set.all().filter(timeStart__lt=datetime.datetime.now()).order_by('-timeStart'); upcoming_games = player.game_set.all().filter(timeStart__gte=datetime.datetime.now()).order_by('timeStart'); player_connected_to_instagram = False if InstagramInfo.objects.filter(user=player).count(): player_connected_to_instagram = True following_people = following(request.user) is_following = player in following_people return render(request, 'user.html', { 'player':player, 'games_played':games_played, 'games_created':games_created, 'upcoming_games': upcoming_games, 'loggedinUser':loggedinUser, 'player_connected_to_instagram': player_connected_to_instagram, 'is_following' : is_following })
def test_stream(self): self.assertSetEqual(user_stream(self.user1), [ 'Two started following CoolGroup %s ago' % self.timesince, 'Two joined CoolGroup %s ago' % self.timesince, ]) self.assertSetEqual(user_stream(self.user2), ['CoolGroup responded to admin: ' 'Sweet Group!... %s ago' % self.timesince])
def test_stream(self): self.assertEqual( map(unicode, user_stream(self.user1)), [u"Two started following CoolGroup 0 minutes ago", u"Two joined CoolGroup 0 minutes ago"], ) self.assertEqual( map(unicode, user_stream(self.user2)), [u"CoolGroup responded to admin: Sweet Group!... 0 minutes ago"] )
def test_empty_follow_stream(self): unfollow(self.user1, self.user2) self.assertFalse(user_stream(self.user1)) self.assertSetEqual( user_stream(self.user3, with_user_activity=True), ['Three liked actstream %s ago' % self.timesince] )
def test_stream(self): self.assertEqual(map(unicode, user_stream(self.user1)), [ u'Two started following CoolGroup 0 minutes ago', u'Two joined CoolGroup 0 minutes ago' ]) self.assertEqual( map(unicode, user_stream(self.user2)), [u'CoolGroup responded to admin: Sweet Group!... 0 minutes ago'])
def test_follow_unfollow_tag(self): """Following a tag should show a post.""" from actstream.actions import follow, unfollow from actstream.models import user_stream from taggit.models import Tag # Lookup the 'hogwarts' Tag hogwarts_tag = Tag.objects.get(name='hogwarts') # Follow it with the current user follow(self.user_harry, hogwarts_tag, actor_only=False) # Ensure that user_harry has one item in the stream self.assertEqual(1, len(user_stream(self.user_harry))) # Ensure that unfollowing the tag clears the user_stream unfollow(self.user_harry, hogwarts_tag) self.assertEqual(0, len(user_stream(self.user_harry)))
def user_activities(request,user_pk): """ Display all of his activities """ my_activity = user_stream(User.objects.get(pk=user_pk)) print my_activity cur_user = User.objects.get(pk=user_pk) print cur_user.first_name activity_set = [] for that_action in my_activity: target = that_action.target actor_url = "#" actor_url = "/home/user/"+str(that_action.actor.id) if isinstance(that_action.target,User): target_url = "/home/user/"+str(that_action.target.id ) if isinstance(that_action.target,Content): if that_action.target.content_type == "MUSIC": target_url = "/upload/show_music/"+str(that_action.target.pk)+" " target = that_action.target.music.title else: if that_action.target.content_type == "LYRICS": target_url = "/upload/show_lyrics/"+str(that_action.target.pk) target = that_action.target.lyrics.lyrics_title activity_set.append({'actor':that_action.actor.first_name,'actor_url':actor_url, 'target':target,'target_url':target_url,"verb":that_action.verb, "timesince":that_action.timesince, "action_object":that_action.action_object}) ctx = { "activity_set": activity_set, 'cur_user':cur_user, } return render(request, "profile/user_activities.html", ctx)
def my_stream(request): """ Activities of the ones i follow """ my_activity = user_stream(request.user) print my_activity activity_set = [] for that_action in my_activity: target = that_action.target actor_url = "#" actor_url = "/home/user/"+str(that_action.actor.id) if isinstance(that_action.target,User): target_url = "/home/user/"+str(that_action.target.id ) if isinstance(that_action.target,Content): if that_action.target.content_type == "MUSIC": target_url = "/upload/show_music/"+str(that_action.target.pk)+" " target = that_action.target.music.title else: if that_action.target.content_type == "LYRICS": target_url = "/upload/show_lyrics/"+str(that_action.target.pk) target = that_action.target.lyrics.lyrics_title activity_set.append({'actor':that_action.actor.first_name, 'actor_url':actor_url, 'target':target,'target_url':target_url,"verb":that_action.verb, "timesince":that_action.timesince, "action_object":that_action.action_object}) ctx = { "activity_set": activity_set, } return render(request, "profile/home.html", ctx)
def feeds(request): userStream = user_stream(request.user, with_user_activity=True) context = { 'stream': userStream, 'notifications': Notification1.objects.all() } return render(request, 'feeds/action.html', context)
def index(request): if request.user.is_authenticated: following = request.user.following_courses() ndocs = max(5, len(following)) docs = Document.objects.filter( course__in=following).order_by("-created")[:ndocs] context = { 'search': SearchForm(), 'stream': user_stream(request.user).exclude(verb="started following")[:10], 'recent_docs': docs, 'faculties': Category.objects.get(level=0).children.all() } return render(request, "home.html", context) else: def floor(num, r=1): r = 10**r return int((num // r) * r) page_count = Document.objects.all().aggregate( Sum('pages'))['pages__sum'] context = { "login_url": NetidBackend.login_url(""), "debug": settings.DEBUG, "documents": floor(Document.objects.count()), "pages": floor(page_count, 2), "users": floor(User.objects.count()), "threads": floor(Thread.objects.count()), } return render(request, "index.html", context)
def dashboard(request): events = user_stream(request.user, with_user_activity=True) cbs = following(request.user, Clipboard) return render(request, "dropme/dashboard.html", { "events": events, "following_clipboards": cbs })
def test_stream_stale_follows(self): """ user_stream() / FollowManager.stream_for_user() should ignore Follow objects with stale actor references. """ self.user2.delete() self.assertEqual(list(user_stream(self.user1)), [])
def test_stream_stale_follows(self): """ user_stream() should ignore Follow objects with stale actor references. """ self.user2.delete() self.assertNotIn('Two', str(user_stream(self.user1)))
def test_user(self): response = self.get('actstream_user', self.user2.username) self.assertTemplateUsed(response, 'actstream/actor.html') self.assertEqual(response.context['ctype'], self.user_ct) self.assertEqual(response.context['actor'], self.user2) self.assertQSEqual(response.context['action_list'], models.user_stream(self.user2))
def index(request): if request.user.is_authenticated: following = request.user.following_courses() ndocs = max(5, len(following)) docs = Document.objects.filter(course__in=following).order_by("-created")[:ndocs] context = { 'search': SearchForm(), 'stream': user_stream(request.user).exclude(verb="started following")[:10], 'recent_docs': docs, 'faculties': Category.objects.get(level=0).children.all() } return render(request, "home.html", context) else: def floor(num, r=1): r = 10 ** r return int((num // r) * r) page_count = Document.objects.all().aggregate(Sum('pages'))['pages__sum'] context = { "login_url": NetidBackend.login_url(""), "debug": settings.DEBUG, "documents": floor(Document.objects.count()), "pages": floor(page_count, 2), "users": floor(User.objects.count()), "threads": floor(Thread.objects.count()), } return render(request, "index.html", context)
def get_queryset(self): """Returns listview's queryset.""" # use `actstream.user_stream` as the listview queryset usr_stream = user_stream(self.request.user).prefetch_related( 'actor', 'action_object') return usr_stream
def base(request): """ Provides basic variables used for all templates. """ context = dict() context['dnstorm_url'] = DNSTORM_URL # Links if not context.get('site_title', None): context['site_title'] = '%s | %s' % (get_option('site_title'), get_option('site_description')) context['site_url'] = get_option('site_url') context['login_form'] = AuthenticationForm() context['login_url'] = reverse( 'login') + '?next=' + request.build_absolute_uri( ) if 'next' not in request.GET else '' context['logout_url'] = reverse( 'logout') + '?next=' + request.build_absolute_uri( ) if 'next' not in request.GET else '' # Checks context['is_update'] = 'update' in request.resolver_match.url_name # Activity context['user_activity'] = user_stream( request.user, with_user_activity=True) if request.user.is_authenticated() else None context['user_activity_counter'] = get_option( 'user_%d_activity_counter' % request.user.id) if request.user.is_authenticated() else None return context
def test_user_stream_with_kwargs(self): """ Testing the user method of the ActionManager by passing additional filters in kwargs """ self.assertSetEqual(user_stream(self.user1, verb='joined'), [ 'Two joined CoolGroup %s ago' % self.timesince, ])
def notification_emails(): """ Send activity stream emails. """ logger.info(u"[{}]: Started notification emails".format(timezone.now())) for user in User.objects.filter(is_staff=False, is_superuser=False): logger.info(u"Sending message to user {}".format(user.email)) translation.activate(user.profile.lang) UserStreamMail().send(user.email, {'stream': user_stream(user)}) logger.info(u"[{}]: Finished notification emails".format(timezone.now()))
def stream(request): """ Index page for authenticated user's activity stream. (Eg: Your feed at github.com) """ return render_to_response('activity/actor.html', { 'ctype': ContentType.objects.get_for_model(request.user), 'actor':request.user,'action_list':user_stream(request.user) }, context_instance=RequestContext(request))
def timeline(request): actions = user_stream(request.user) try: selected_actions = actions[0:5] except IndexError: selected_actions = actions #import ipdb; ipdb.set_trace() return render(request, 'timeline.html', {'actions': selected_actions, 'username': request.user.username})
def get_context_data(self, **kwargs): context = super(UserActivityView, self).get_context_data(**kwargs) if len(following(self.request.user)) > 0: actstream = user_stream(self.request.user) context['blog'] = self.get_latest(actstream, 'blog') context['ideas'] = self.get_latest(actstream, 'ideas') context['topics'] = self.get_latest(actstream, 'topics') context['polls'] = self.get_latest(actstream, 'polls') return context
def feed_view(request): """ View to generate feeds for the current user. """ f = user_stream(request.user) f = f.filter(verb='posted') serializer = ActionSerializer(instance=f, many=True) return Response(serializer.data)
def user(request, username): """ ``User`` focused activity stream. (Eg: Profile page twitter.com/justquick) """ instance = get_object_or_404(User, **{'is_active': True, compat.username_field(): username}) return render_to_response('actstream/actor.html', { 'ctype': ContentType.objects.get_for_model(User), 'actor': instance, 'action_list': models.user_stream(instance) }, context_instance=RequestContext(request))
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(('actstream/actor.html', 'activity/actor.html'), { 'ctype': ContentType.objects.get_for_model(User), 'actor': user, 'action_list': models.user_stream(user) }, context_instance=RequestContext(request))
def stream(request): """ Index page for authenticated user's activity stream. (Eg: Your feed at github.com) """ return render_to_response(('actstream/actor.html', 'activity/actor.html'), { 'ctype': ContentType.objects.get_for_model(User), 'actor': request.user, 'action_list': models.user_stream(request.user) }, context_instance=RequestContext(request))
def test_addding_comment_send_notificatation_to_stream_owner(self): s = models.Stream.objects.get_user_stream(self.users[1]) si0 = self.G(models.StreamItem, root=s) c = self.G(models.ItemComment, subject=si0, user=self.users[0]) activity = actstream_models.user_stream(self.users[1]) self.assertEqual(activity[0].action_object, c) self.assertEqual(activity[0].target, s)
def advisor(request): advisor = Advisor.objects.get(user=request.user) students = advisor.students.all().order_by('last_name') for student in students: follow(request.user, student) follow(User.objects.get(email=student.user.email), advisor) return render(request, 'journal/advisor.html', {'feed': user_stream(request.user), 'students': students})
def update_activity_stream_for_user(user, actor=False): user = get_user_model().objects.get(username=user) if actor: item_list = actor_stream(user) cache.set('activity_items_actor_'+user.username, item_list, 60*60*24*31) else: item_list = check_activity_permissions(user, user_stream(user)) cache.set('activity_items_'+user.username, item_list, 60*60*24*31) return
def test_activity_stream_project(self): # send create event of a project signals.create.send(sender=Project, instance=self.project, user=self.user) create = user_stream(self.user).first() self.assertEqual(create.action_object, self.project) self.assertEqual(create.verb, ProjectHandler.createVerb) self.assertEqual(create.actor, self.user) # send modify event of a project signals.modify.send(sender=Project, instance=self.project, user=self.user, changed_data=None) modify = user_stream(self.user).first() self.assertEqual(modify.action_object, self.project) self.assertEqual(modify.verb, ProjectHandler.modifyVerb) self.assertEqual(modify.actor, self.user)
def test_commenting_creates_an_action(self): self.client.force_authenticate(self.u) data = { 'text': faker.text(), 'divesite': self.ds.id } response = self.client.post(reverse('divesitecomment-list'), data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) stream = user_stream(self.u, with_user_activity=True) self.assertEqual(len(stream), 1)
def notification_emails(): """ Send activity stream emails. """ users = User.objects.all() for user in users: stream = user_stream(user) email = UserStreamMail() translation.activate(user.profile.lang) return email.send(user.email, {'stream': stream})
def stream(request): """ Index page for authenticated user's activity stream. (Eg: Your feed at github.com) """ return render(request, 'actstream/actor.html', context={ 'ctype': ContentType.objects.get_for_model(User), 'actor': request.user, 'action_list': models.user_stream(request.user) })
def notifications(self): notifications = user_stream(obj=self.user) # Workaround for # https://github.com/justquick/django-activity-stream/issues/482 notifications = notifications.exclude( actor_content_type=ContentType.objects.get_for_model(self.user), actor_object_id=self.user.pk, ) return notifications
def action_context(self): ''' refactored method. This method filters the users actions by truncating the request.users action. It takes in the queryset from Action.objects.all() and returns all the actions that the other users made as a list. ''' actions = user_stream(self.request.user)[:4] return actions
def get_context_data(self, **kwargs): context = super(UserProfileDetailView, self).get_context_data(**kwargs) context['my_score'] = Points.objects.filter( user=self.object).aggregate(total_score=Sum('score')).values()[0] context['websites'] = Domain.objects.filter( issue__user=self.object).annotate( total=Count('issue')).order_by('-total') context['activities'] = user_stream(self.object, with_user_activity=True) context['profile_form'] = UserProfileForm() return context
def user_stream_page_filter(page_owner): me = HubUser.objects.get(user__username__iexact=page_owner.username) my_actions1 = user_stream(me) my_actions2 = user_stream(me.user) filtered_actions = [] if my_actions1.exists(): my_actions=my_actions1 else: my_actions=my_actions2 for a in my_actions: if a.actor == me.user or a.actor == me: filtered_actions.append(a) for a in my_actions: if a.target == me.user or a.target == me: filtered_actions.append(a) filtered_actions.sort(key=lambda x: x.timestamp, reverse=True) return filtered_actions
def profile_dashboard(request): """ Landing page for logged in users. Renders the activity stream of followed users. """ user = get_object_or_404(User, id=request.user.id) return render(request, "accounts/account_dashboard.html", { 'user': user, 'profile': user.get_profile(), 'actions': models.user_stream(user), })
def advisor(request): advisor = Advisor.objects.get(user=request.user) students = advisor.students.all().order_by('last_name') for student in students: follow(request.user, student) follow(User.objects.get(email=student.user.email), advisor) return render(request, 'journal/advisor.html', { 'feed': user_stream(request.user), 'students': students })
def test_connection_joined_group(self): group = Club.objects.create(user=self.notfriend, uni=self.uni, name='foo') # Student joins group (which auto-follows the group) ClubMember.objects.create(user=self.student, group=group) self.assertTrue(Follow.objects.is_following(self.student, group)) # Friend also joined group ClubMember.objects.create(user=self.friend, group=group) # Student gets activity activity = user_stream(self.student) self.assertTrue('Friend joined foo' in str(activity.first()))
def coordinator(request): coor = Coordinator.objects.get(user=request.user) students = coor.students.all().order_by('last_name') advisors = coor.advisors.all().order_by('first_name') if not following(request.user): for student in students: follow(request.user, student) follow(User.objects.get(email=student.user.email), coor) return render(request, 'journal/coordinator.html', {'feed': user_stream(request.user), 'students': students, 'coordinator': coor, 'advisors': advisors})
def load_activity(request, id, template_name='activity/actions.html'): """ loads the next batch of actions starting from the last action passed up, it uses the last action id since pagination might be off due to new activities generated in the meantime """ user = get_object_or_404(User,pk=id) last_action = int(request.GET.get("last_action")) actions = user_stream(user).filter(pk__lte=last_action)[0:20] return render_to_response(template_name,{ "actions": actions, }, context_instance=RequestContext(request))
def stream(request): """ Index page for authenticated user's activity stream. (Eg: Your feed at github.com) """ return render( request, 'actstream/actor.html', { 'ctype': ContentType.objects.get_for_model(User), 'actor': request.user, 'action_list': models.user_stream(request.user) })
def test_someone_commented_on_your_post(self): # Student makes a post (which auto-follows the post) post = Post.objects.create(user=self.student, uni=self.uni, feed_object='university', feed_object_id=self.uni.pk, title='foo') self.assertTrue(Follow.objects.is_following(self.student, post)) # Friend comments on the post Comment.objects.create(user=self.friend, post=post, text='bar') # Student gets activity activity = user_stream(self.student) self.assertTrue('Friend commented bar on foo' in str(activity.first()))
def test_connection_posted_in_marketplace(self): # Student connects to Friend (which auto-follow the friend) self.student.add_connection(self.friend) # Friend posts a marketplace item category = Category.objects.create(name='Test', module='marketplace') Item.objects.create(user=self.friend, title='foo', price='10.00', category=category) # Student gets activity activity = user_stream(self.student) self.assertTrue( 'Friend posted marketplace item foo' in str(activity.first()))