def user_notification_timeline(request, user_id): # todo high don't allow others to see the notifications of another user by changing the url (same with tips) # TODO high more button to load the next activities # I use the low level client (stream_client) instead of the high level feedmanager of the stream django app # without specific reason so I can use the feedmanager instead get_activities_num = 80 per_page = 12 user_notification_feed = stream_client.feed(FeedNames.notification, user_id) # it seems that first the activities are collected and then they are marked as seen. This way I can # check if an activity is currently seen or not activities = user_notification_feed.get(limit=get_activities_num, mark_seen=True, mark_read=True)['results'] # next_activities = user_notification_feed.get(limit=get_activities_num, id_lt=activities[-1]['id'])['results'] enricher = Enrich( fields=['actor', 'object', 'bet_event', 'total_bet', 'event']) enriched_activities = enricher.enrich_aggregated_activities(activities) paginator = Paginator(enriched_activities, per_page) enriched_activities = zakanda.utils.paginate(request, paginator, enriched_activities) context = { 'enriched_activities': enriched_activities, 'not_started': games.models.Event.not_started } return TemplateResponse(request, 'feeds/timeline.html', context)
def get(self, request, *args, **kwargs): if request.GET.get('partial') == 'activities': # activities try: project = self.get_object() enricher = Enrich(( 'actor', 'target', )) feed = feed_manager.get_challenge_feed(challenge_id=project.pk) activities = feed.get(limit=6)['results'] enriched = enricher.enrich_activities(activities) return render(request, 'projects/_activities.html', {'activities': enriched}) except Exception: return HttpResponse() if request.GET.get('partial') == 'completed': # current user status data = {'completed': False} try: user = request.user if not user.is_authenticated(): raise Exception('not authenticated') project = self.get_object() user_project = UserProject.objects.get(project=project, user=request.user) data['complete'] = user_project.is_complete() except Exception: pass return JsonResponse(data) return super().get(request, *args, **kwargs)
def user_timeline(request, user_pk): get_activities_num = 80 per_page = 15 enricher = Enrich( fields=['actor', 'object', 'bet_event', 'total_bet', 'event']) logger.debug("getting timeline feed...") user_timeline = stream_client.feed(FeedNames.timeline, user_pk) # we collect a number of activities and then we can filter or paginate them as we want activities = user_timeline.get(limit=get_activities_num)['results'] # next_activities = user_timeline.get(limit=50, id_lt=activities[-1]['id'])['results'] # enriched activities is a list of stream_django.enrich.EnrichedActivity instances (they have __getitem__, __iter__) enriched_activities = enricher.enrich_activities(activities) # # add_isopen_to_tb_enriched_activities(enriched_activities) paginator = Paginator(enriched_activities, per_page) enriched_activities = zakanda.utils.paginate(request, paginator, enriched_activities) # enriched_activities_2 = enricher.enrich_activities(next_activities) enriched_activities_2 = None # # add_isopen_to_tb_enriched_activities(enriched_activities_2) context = { 'enriched_activities': enriched_activities, 'enriched_activities_2': enriched_activities_2, 'not_started': games.models.Event.not_started } return TemplateResponse(request, 'feeds/timeline.html', context)
def profile_feed(request, username=None): enricher = Enrich() user = User.objects.get(username=username) feed = feed_manager.get_user_feed(user.id) activities = feed.get(limit=25)['results'] enricher.enrich_activities(activities) context = {'activities': activities} return render(request, 'tweets.html', context)
def hashtag(request, hashtag): enricher = Enrich() feed = feed_manager.get_feed('hashtag', hashtag) activities = feed.get(limit=25)['results'] enricher.enrich_activities(activities) context = { 'activities': activities } return render(request, 'hashtag.html', context)
def notifications(request): user = request.user notification_feed = feed_manager.get_notification_feed(user.id) notification_stats = notification_feed.get(limit=10, mark_seen=True) enricher = Enrich() notifications = enricher.enrich_aggregated_activities( notification_stats['results']) return render(request, 'activity/aggregated/report.html', {'notifications': notifications})
def get(self, request): if request.GET.get('partial') == 'activities': try: enricher = Enrich(('actor', 'object', 'target')) feed = feed_manager.get_global_challenge_feed() activities = feed.get(limit=10)['results'] enriched = enricher.enrich_aggregated_activities(activities) return render(request, 'base/_activities.html', {'activities': enriched}) except Exception as e: return HttpResponse() return super().get(request)
def get(self, request): user = self.request.user if request.GET.get('partial') == 'notifications': try: enricher = Enrich(('actor', 'object', 'target',)) feed = feed_manager.get_notification_feed(user.id) activities = feed.get(limit=10)['results'] enriched = enricher.enrich_aggregated_activities(activities) except Exception: enriched = [] finally: return render(request, 'account/_notifications_card_content.html', {'notifications': enriched}) return super().get(request)
def Home(request): enricher = Enrich() feeds = feed_manager.get_news_feeds(request.user.id) activities = feeds.get('flat').get()['results'] activities = enricher.enrich_activities(activities) hashtags = Hashtag.objects.order_by('-occurrences') SelectedAthlete = get_object_or_404(Athlete, id=request.user.athlete.id) TotalAthletes = Athlete.objects.count() contextdata = { 'activities': activities, 'login_user': request.user, 'hashtags': hashtags, 'TotalAthletes': TotalAthletes } return render(request, 'index.html', contextdata)
def get(self, request, cityslug, format=None): ''' enricher = Enrich() flat_feed = feed_manager.get_news_feed(cityslug)['flat'] activities = feed.get(limit=25)['results'] enriched_activities = enricher.enrich_activities(activities) ''' ''' UserEventsQuerySet = UserEvent.objects.filter(city__slug = cityslug).order_by('-created_at')[:3600] serialized = UserEventSerializer(UserEventsQuerySet, many=True) return Response(serialized.data) ''' enricher = Enrich() feed = feed_manager.get_feed('cityevents', cityslug) activities = feed.get(limit=25)['results'] enriched_activities = enricher.enrich_activities(activities) serialized = UserEventSerializer(enriched_activities, many=True) return Response(serialized.data)
def user_aggregated_timeline(request, user_pk): get_activities_num = 80 per_page = 15 user_aggr_timeline = stream_client.feed(FeedNames.timeline_aggregated, user_pk) activities = user_aggr_timeline.get(limit=get_activities_num)['results'] # logger.debug("activities: %s", activities['activities']) enricher = Enrich( fields=['actor', 'object', 'bet_event', 'total_bet', 'event']) enriched_activities = enricher.enrich_aggregated_activities(activities) paginator = Paginator(enriched_activities, per_page) enriched_activities = zakanda.utils.paginate(request, paginator, enriched_activities) feeds.utils.print_enriched_aggr_activities(enriched_activities) context = { 'enriched_activities': enriched_activities, 'not_started': games.models.Event.not_started } return TemplateResponse(request, 'feeds/timeline.html', context)
def get(self, request): user = self.request.user if request.GET.get("partial") == "notifications": try: enricher = Enrich( ( "actor", "object", "target", ) ) feed = feed_manager.get_notification_feed(user.id) activities = feed.get(limit=10)["results"] enriched = enricher.enrich_aggregated_activities(activities) except Exception: enriched = [] finally: return render( request, "account/_notifications_card_content.html", {"notifications": enriched}, ) return super().get(request)
from django.views.generic.edit import CreateView from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import authenticate, login as auth_login from django.contrib.auth.models import User from stream_django.enrich import Enrich from stream_django.feed_manager import feed_manager from stream_twitter.forms import FollowForm from stream_twitter.models import Follow from stream_twitter.models import Tweet, Hashtag from pytutorial import settings import random enricher = Enrich() class TimelineView(CreateView): model = Tweet fields = ['text'] success_url = "/timeline/" def form_valid(self, form): form.instance.user = self.request.user return super(TimelineView, self).form_valid(form) def get(self, request): feeds = feed_manager.get_news_feeds(request.user.id) activities = feeds.get('timeline').get()['results'] activities = enricher.enrich_activities(activities) hashtags = Hashtag.objects.order_by('-occurrences') context = { 'activities': activities,
def setUp(self): feed_manager.enable_model_tracking() self.User = get_user_model() self.bogus = self.User.objects.create() self.enricher = Enrich()
class PinTest(TestCase): def setUp(self): feed_manager.enable_model_tracking() self.User = get_user_model() self.bogus = self.User.objects.create() self.enricher = Enrich() def register_post_api(self): httpretty.register_uri(httpretty.POST, api_url, body='{}', status=200, content_type='application/json') def register_delete_api(self): httpretty.register_uri(httpretty.DELETE, api_url, body='{}', status=200, content_type='application/json') @httpretty.activate def test_create(self): self.register_post_api() pin = models.Pin.objects.create(author=self.bogus) last_req = httpretty.last_request() req_body = last_req.parsed_body self.assertEqual(req_body['foreign_id'], 'test_app.Pin:%s' % pin.id) self.assertEqual(req_body['object'], 'test_app.Pin:%s' % pin.id) self.assertEqual(req_body['verb'], 'pin') self.assertEqual(req_body['actor'], 'auth.User:%s' % self.bogus.id) @httpretty.activate def test_delete(self): self.register_post_api() self.register_delete_api() pin = models.Pin.objects.create(author=self.bogus) pin.delete() last_req = httpretty.last_request() self.assertEqual(last_req.method, httpretty.DELETE) @httpretty.activate def test_enrich_instance(self): self.register_post_api() pin = models.Pin.objects.create(author=self.bogus) pin.save() activity = pin.create_activity() enriched_data = self.enricher.enrich_activities([activity]) # check object field self.assertEqual(enriched_data[0]['object'].id, pin.id) self.assertIsInstance(enriched_data[0]['object'], models.Pin) # check actor field self.assertEqual(enriched_data[0]['actor'].id, pin.author_id) self.assertIsInstance(enriched_data[0]['actor'], self.User) @httpretty.activate def test_enrich_data_with_missing_reference(self): self.register_post_api() self.register_delete_api() pin = models.Pin.objects.create(author=self.bogus) pin.save() activity = pin.create_activity() pin.delete() # make sure missing data is correctly tracked enriched_data = self.enricher.enrich_activities([activity]) self.assertFalse(enriched_data[0].enriched) self.assertIn('object', enriched_data[0].not_enriched_data) self.assertDictContainsSubset(dict(object=activity['object']), enriched_data[0].not_enriched_data) self.assertEqual(activity['object'], enriched_data[0]['object']) def test_disabled_tracking(self): feed_manager.disable_model_tracking() pin = models.Pin.objects.create(author=self.bogus) pin.save() pin.delete()
class PinTest(TestCase): def setUp(self): feed_manager.enable_model_tracking() self.User = get_user_model() self.bogus = self.User.objects.create() self.enricher = Enrich() def register_post_api(self): httpretty.register_uri( httpretty.POST, api_url, body="{}", status=200, content_type="application/json", ) def register_delete_api(self): httpretty.register_uri( httpretty.DELETE, api_url, body="{}", status=200, content_type="application/json", ) @httpretty.activate def test_create(self): self.register_post_api() pin = models.Pin.objects.create(author=self.bogus) last_req = httpretty.last_request() req_body = last_req.parsed_body self.assertEqual(req_body["foreign_id"], "test_app.Pin:%s" % pin.id) self.assertEqual(req_body["object"], "test_app.Pin:%s" % pin.id) self.assertEqual(req_body["verb"], "pin") self.assertEqual(req_body["actor"], "auth.User:%s" % self.bogus.id) @httpretty.activate def test_delete(self): self.register_post_api() self.register_delete_api() pin = models.Pin.objects.create(author=self.bogus) pin.delete() last_req = httpretty.last_request() self.assertEqual(last_req.method, httpretty.DELETE) @httpretty.activate def test_enrich_instance(self): self.register_post_api() pin = models.Pin.objects.create(author=self.bogus) pin.save() activity = pin.create_activity() enriched_data = self.enricher.enrich_activities([activity]) # check object field self.assertEqual(enriched_data[0]["object"].id, pin.id) self.assertIsInstance(enriched_data[0]["object"], models.Pin) # check actor field self.assertEqual(enriched_data[0]["actor"].id, pin.author_id) self.assertIsInstance(enriched_data[0]["actor"], self.User) @httpretty.activate def test_enrich_data_with_missing_reference(self): self.register_post_api() self.register_delete_api() pin = models.Pin.objects.create(author=self.bogus) pin.save() activity = pin.create_activity() pin.delete() # make sure missing data is correctly tracked enriched_data = self.enricher.enrich_activities([activity]) self.assertFalse(enriched_data[0].enriched) self.assertIn("object", enriched_data[0].not_enriched_data) activity_obj = set(dict(object=activity["object"]).items()) enriched_obj = set(enriched_data[0].not_enriched_data.items()) assert activity_obj.issubset(enriched_obj) self.assertEqual(activity["object"], enriched_data[0]["object"]) def test_disabled_tracking(self): feed_manager.disable_model_tracking() pin = models.Pin.objects.create(author=self.bogus) pin.save() pin.delete()
def CityCommunityPostPage(request, cityslug): contextdata = {} SelectedCity = get_object_or_404(City, slug = cityslug) SelectedAthlete = get_object_or_404(Athlete, id=request.user.athlete.id) if request.method == 'POST' and request.is_ajax(): form = CommunityPostForm(request.POST) if form.is_valid(): user = request.user body = form.cleaned_data['body'] communitypost = CommunityPost(user=user, body=body, city=SelectedCity) communitypost.save() contextdata = { 'CommunityPost': communitypost } html = render_to_string('communitypost.html', contextdata, context_instance = RequestContext(request)) return JsonResponse({'html': html}) else: msg="AJAX post invalid" contextdata = {'form': form} return render(request, 'communitylocation/citypostpage.html', contextdata) if request.method == 'GET' and request.is_ajax(): if request.GET.get('postid'): if request.GET.get('verifiedathleteslug'): postid = request.GET['postid'] verifiedathleteslug = request.GET['verifiedathleteslug'] SelectedAthlete = get_object_or_404(Athlete, slug=verifiedathleteslug) Comments = Comment.objects.filter(user__username = SelectedAthlete.user.username).filter(object_pk = postid).order_by('submit_date') contextdata = { 'comment_list': Comments, 'postid': postid } commentshtml = render_to_string("comments/list.html", contextdata, context_instance = RequestContext(request)) return JsonResponse({'commentshtml': commentshtml}) else: postid = request.GET['postid'] Comments = Comment.objects.filter(object_pk = postid).order_by('submit_date') contextdata = { 'comment_list': Comments, 'postid': postid } commentshtml = render_to_string("comments/list.html", contextdata, context_instance = RequestContext(request)) return JsonResponse({'commentshtml': commentshtml}) if request.GET.get('postidreq'): postidreq = request.GET['postidreq'] SelectedPost = CommunityPost.objects.get(id = postidreq) SelectedPost.delete() return JsonResponse({'postID': postidreq}) if request.GET.get('commentidreq'): commentidreq = request.GET['commentidreq'] comment = get_object_or_404(comments.get_model(), pk=commentidreq, site__pk=settings.SITE_ID) perform_delete(request, comment) return JsonResponse({'commentID': commentidreq}) else: form = CommunityPostForm() enricher = Enrich() feed = feed_manager.get_feed('citypost', SelectedCity.name.replace(" ", "_")) activities = feed.get(limit=25)['results'] enricher.enrich_activities(activities) contextdata = { 'City': SelectedCity, 'form': form, 'activities': activities } return render(request, 'communitylocation/citypostpage.html', contextdata)