def relationship_handler(request, user, status_slug, add=True, template_name='relationships/confirm.html', success_template_name='relationships/success.html'): status = get_relationship_status_or_404(status_slug) is_symm = status_slug == status.symmetrical_slug if request.method == 'POST': if add: request.user.relationships.add(user, status, is_symm) actions.follow(request.user, user, actor_only=False) else: request.user.relationships.remove(user, status, is_symm) actions.unfollow(request.user, user) ctype = ContentType.objects.get_for_model(request.user) target_content_type = ContentType.objects.get_for_model(user) Action.objects.all().filter(actor_content_type=ctype, actor_object_id=request.user.id, verb=u'started following', target_content_type=target_content_type, target_object_id = user.id ).delete() if request.is_ajax(): return HttpResponse(json.dumps(dict(success=True, count=user.relationships.followers().count()))) if request.GET.get('next'): return HttpResponseRedirect(request.GET['next']) template_name = success_template_name return render_to_response(template_name, {'to_user': user, 'status': status, 'add': add}, context_instance=RequestContext(request))
def post(self, request): self.instance = self.get_object() instance_name = self.instance._meta.verbose_name.lower() if not self.instance in following(request.user): try: follow(request.user, self.instance, actor_only=False, send_action=False) msg = _(u"You are following this %s" % instance_name) is_follower = True except ImproperlyConfigured as e: return Response({'success': False, 'message': str(e)}) if instance_name == 'location': self.instance.users.add(request.user) else: unfollow(request.user, self.instance) msg = _(u"You are no longer following this %s" % instance_name) is_follower = False if instance_name == 'location': self.instance.users.remove(request.user) return Response( {'success': True, 'message': msg, 'following': is_follower, })
def move_location_contents(old_location, new_location): """ This method helps us move contents between locations, mainly, if we want to delete one location but save contents in other one. It takes two location instances as arguments and move content from first to second of them. """ content_sets = ['news_set', 'poll_set', 'idea_set', 'discussion_set', 'pictures', 'projects',] # Get all 'standard' contents from first location and move to second one for content_type in content_sets: for item in getattr(old_location, content_type).all(): item.location = new_location item.save() # Find all old location followers and make them follow new place for user in old_location.users.all(): unfollow(user, old_location) if not user in new_location.users.all(): follow(user, new_location) new_location.users.add(user) # Find all actions where old location acts as target and bind to new location. # This is not really good idea, but I hope it will be sufficient. actions = Action.objects.filter(target_object_id=old_location.pk, target_content_type=ContentType.objects.get_for_model(Location)) for action in actions: action.target_object_id = new_location.pk action.save()
def unfollowWish(request, wish_id): wishObject = get_object_or_404(BroadcastWish, pk=wish_id) ctype = ContentType.objects.get_for_model(wishObject) follow = Follow.objects.get_follows(wishObject).get(user=request.user) follow.delete() actions.unfollow(request.user, wishObject, send_action=False) return HttpResponse('ok')
def make_random_unfollows(max_users): print "make random unfollows" some_users = User.objects.all().order_by('?')[:random.randint(0, max_users)] for user in some_users: following_list = following(user, User) for u in following_list[:random.randint(0, len(following_list))]: unfollow(user, u)
def star_project(request, username, project): project = Project.retrieve(username, project, request.user) if is_following(request.user, project): unfollow(request.user, project) else: follow(request.user, project, actor_only=False) return HttpResponseRedirect(project.link())
def post(self, request, location_slug=None, slug=None): project = get_object_or_404(SocialProject, slug=slug) if project.participants.filter(pk=request.user.pk).exists(): project.participants.remove(request.user) project.authors_group.authors.remove(request.user.author) for group in project.taskgroup_set.all(): for task in group.task_set.all(): if task.participants.filter(pk=request.user.pk).exists(): task.participants.remove(request.user) message = _("You are no longer in this project") leaved_project(request.user, project) unfollow(request.user, project) else: project.participants.add(request.user) project.authors_group.authors.add(request.user.author) message = _("You have joined to this project") joined_to_project(request.user, project) follow(request.user, project, actor_only=False) if request.is_ajax(): context = {'success': True, 'message': message, } return HttpResponse(context, content_type="application/json") return redirect(reverse( 'locations:project_details', kwargs={'location_slug': location_slug, 'slug': project.slug, }))
def Company_Detail (request,pk = "", slug = ""): try: company = Company.objects.get(pk = pk) except Company.DoesNotExist: raise Http404 if request.method == "POST": if 'follow' in request.POST: follow_id = request.POST.get('follow', False) if follow_id: try: company_id = Company.objects.get(pk=follow_id) follow(request.user, company_id) #request.user.get_profile().applicant except Company.DoesNotExist: return render(request, 'company_detail.html', {'id': company,'follow':False }) else: unfollow_id = request.POST.get('unfollow', False) if unfollow_id: try: company_id = Company.objects.get(pk=unfollow_id) unfollow(request.user, company_id) #request.user.get_profile().applicant except Company.DoesNotExist: return render(request, 'company_detail.html', {'id': company,'follow':True }) if followers(company): print followers(company) return render(request, 'company_detail.html', {'id': company,'follow':False }) return render(request, 'company_detail.html', {'id': company,'follow':True })
def unfollowDeal(request, deal_id): dealObject = get_object_or_404(BroadcastDeal, pk=deal_id) ctype = ContentType.objects.get_for_model(dealObject) follow = Follow.objects.get_follows(dealObject).get(user=request.user) follow.delete() actions.unfollow(request.user, dealObject, send_action=False) return HttpResponse('ok')
def destroy_relationship(self, user, me): """Stop following the user if exists and is not the logged in user.""" if user.pk is me.pk: return HttpBadRequest("A user can't unfollow itself.") me.relationships.remove(user) # Unfollow ctivity stream actions.unfollow(me, user)
def create_relationship(self, user, me): """Start blocking the user if exists and is not the logged in user.""" if user.pk is me.pk: return HttpBadRequest("A user can't block itself.") me.relationships.add(user, status=RelationshipStatus.objects.blocking()) if actions.is_following(user, me): actions.unfollow(user, me)
def follow_user(request, username): user = get_object_or_404(User, username=username) if user != request.user: if is_following(request.user, user): unfollow(request.user, user) else: follow(request.user, user, actor_only=False) return HttpResponseRedirect(reverse("profile", args=[username]))
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 get_success_url(self): action.send(self.request.user, verb='aborted', target=self.object) actions.unfollow(self.request.user, self.object, send_action=False) notify.send( self.request.user, recipient=self.object.creator, verb=u'has aborted from your Group', level='success') return reverse("groups:groups-detail", kwargs={'pk': self.kwargs['pk']})
def remove_student(request, student_pk): student = get_object_or_404(Student, pk=student_pk) staff_check(request, student) stu = User.objects.get(email=student.user.email) try: unfollow(request.user, student) unfollow(stu, request.user) except: pass student.delete() return HttpResponseRedirect('/coordinator')
def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.DATA) if serializer.is_valid(): user = self.get_object() if not serializer.object['remove']: follow(request.user, user) else: unfollow(request.user, user) return Response({'follow': render(request, "blog/bits/follow.html", locals())}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, username, format=None): user_to_follow = get_object_or_404(User, username=username) following_list = following(request.user, User) if user_to_follow in following_list: unfollow(request.user, user_to_follow) data = {'message': 'User unfollowed successfully'} else: follow(request.user, user_to_follow) data = {'message': 'User followed successfully'} data['count'] = len(followers(user_to_follow)) return Response(data)
def follow_unfollow(request, content_type_id, object_id, do_follow=True): """ Creates or deletes the follow relationship between ``request.user`` and the 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) if do_follow: follow(request.user, actor) return respond(request, 201) # CREATED unfollow(request.user, actor) return respond(request, 204) # NO CONTENT
def UserPage(request, user): try: user_name = HubUser.objects.get(user__id=int(user)) except ValueError: user_name = HubUser.objects.get(user__username__iexact=user) stream = user_stream(user_name.user) github_request = urllib2.urlopen('https://api.github.com/users/%s' % (user_name.github)) json_data = json.loads(github_request.read()) github_login = json_data['login'] if 'email' in json_data: github_email = json_data['email'] else: github_email = '' try: visitor = HubUser.objects.get(user__username__iexact=request.user.username) except: visitor = None is_following = False if visitor != None: follow_list = following(visitor.user) if user_name in follow_list: is_following = True if (request.GET.get('follow_button')): if user_name in follow_list: unfollow(visitor.user, user_name) action.send(visitor, verb='unfollowed', target=user_name) HttpResponseRedirect(request.path) else: follow(visitor.user, user_name) HttpResponseRedirect(request.path) stream = user_stream_page_filter(user_name.user) if visitor != None: visitor = visitor.user repo_list = Project.objects.filter(owners=user_name) return render(request, 'user_page.html', {'user_name': user_name.user, 'github_username': github_login, 'github_email': github_email, 'stream' : stream, 'visitor' : visitor, 'is_following' : is_following, #above needs refractoring 'hubuser': user_name, 'repo_list': repo_list })
def unfollow(user, obj): """ Make a user unfollow an object """ from django.contrib.contenttypes.models import ContentType from actstream.models import Action try: actions.unfollow(user, obj) follow = Follow.objects.get_follows(obj).filter(user=user) follow.delete() ctype = ContentType.objects.get_for_model(user) target_content_type = ContentType.objects.get_for_model(obj) Action.objects.all().filter(actor_content_type=ctype, actor_object_id=user.id, verb=settings.FOLLOW_VERB, target_content_type=target_content_type, target_object_id = obj.id ).delete() return obj except Follow.DoesNotExist: pass
def post(self, request, **kwargs): user = request.user self.location = self._get_location() if self.location in following(user): unfollow(user, self.location) self.location.users.remove(user) msg = _(u"You stopped following") else: follow(user, self.location, actor_only=False, send_action=False) self.location.users.add(user) msg = _(u"You are following") return Response( {'following': self.location in following(user), 'message': msg, })
def user_followers_delete_handler(sender, instance, **kwargs): """ Make all users unfollow the user being deleted. N.B. Because django-activity-stream is using a GFK, these do not cascade delete. """ # Import act_models here. If imported at the top, this interferes with # appconf imports and breaks compressor configuration. # See https://github.com/jezdez/django_compressor/issues/333 from actstream import models as act_models followers = act_models.followers(instance) for follower in followers: unfollow(follower, instance)
def unfollow_user(request, username): """ Deletes the follow relationship between ``request.user`` and the ``user`` * Requires authentication. """ user = get_object_or_404(User, username=username) actions.unfollow(request.user, user, send_action=True) request.user.userprofile.follows.remove(user) messages.warning( request, 'Successed, you are not follow this user anymore.') return respond(request, 204) # NO CONTENT
def unfollow_elo(request, pk): """ Deletes the follow relationship between ``request.user`` and the ``ELO`` * Requires authentication. """ elo = get_object_or_404(ELO, id=pk) actions.unfollow(request.user, elo, send_action=False) request.user.userprofile.follow_elos.remove(elo) messages.warning( request, 'Successed, you are not follow this ELO anymore.') return redirect('elos:elos-detail', pk)
def post(self, request): target_user = None pk = request.DATA.get('pk', None) try: target_user = User.objects.get(pk=pk) except User.DoesNotExist: pass if target_user is None: raise Http404() if target_user in following(request.user): unfollow(request.user, target_user) else: follow(request.user, target_user, actor_only=True) return Response({'follow': target_user in following(request.user)})
def unfollow_user(request, user_pk): try: user_to_unfollow = User.objects.get(pk=user_pk) is_unfollowed = unfollow(request.user,user_to_unfollow) print is_unfollowed except Exception as E: print E.message return HttpResponse(json.dumps({"follow_status":"Not Following"}), content_type="application/json")
def follow_unfollow(request, content_type_id, object_id, flag, do_follow=True, actor_only=True): """ Creates or deletes the follow relationship between ``request.user`` and the 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) # If flag was omitted in url, None will pass to flag keyword argument flag = flag or '' if do_follow: actions.follow(request.user, instance, actor_only=actor_only, flag=flag) return respond(request, 201) # CREATED actions.unfollow(request.user, instance, flag=flag) return respond(request, 204) # NO CONTENT
def remove_follower(request, pk): """ Remove user from locations followers. """ location = get_object_or_404(Location, pk=pk) user = request.user location.users.remove(user) try: location.save() unfollow(user, location) response = { 'success': True, 'message': _('You stop following this location'), } except: response = { 'success': False, 'message': _('Something, somewhere went terribly wrong'), } return HttpResponse(json.dumps(response))
def follow_unfollow(request, content_type_id, object_id, do_follow=True, actor_only=True): """ Creates or deletes the follow relationship between ``request.user`` and the 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) if 'email_notification' in request.GET: flag_str = request.GET['email_notification'] email_notification = flag_str.lower() in ['true', 'yes', '1'] else: email_notification = False if do_follow: actions.follow(request.user, actor, actor_only=actor_only, email_notification=email_notification) return respond(request, 201) # CREATED actions.unfollow(request.user, actor) return respond(request, 204) # NO CONTENT
def unfollowObject(request, content_type_id, object_id): follow = None ctype = get_object_or_404(ContentType, pk=content_type_id) object = get_object_or_404(ctype.model_class(), pk=object_id) try: _follow = Follow.objects.get_follows(object) follow = _follow.get(user=request.user) except (MultipleObjectsReturned, Follow.DoesNotExist) as e: if isinstance(e, MultipleObjectsReturned): follow = _follow.filter(user=request.user)[0] pass else: follow = None pass if follow: follow.delete() actions.unfollow(request.user, object, send_action=False) return HttpResponse(simplejson.dumps(dict(success=True)))
def test_empty_follow_stream(self): unfollow(self.user1, self.user2) self.assert_(not user_stream(self.user1))
def test_evaluation_notifications(client, evaluation_image, submission_file, settings): # Override the celery settings settings.task_eager_propagates = (True, ) settings.task_always_eager = (True, ) # Try to upload a submission without a method in place with capture_on_commit_callbacks(execute=True): submission = SubmissionFactory( predictions_file__from_path=submission_file) # Missing should result in notification for admins of the challenge # There are 2 notifications here. The second is about admin addition to the # challenge, both notifications are for the admin. for notification in Notification.objects.all(): assert notification.user == submission.phase.challenge.creator assert "there is no valid evaluation method" in Notification.objects.filter( message="missing method").get().print_notification( user=submission.phase.challenge.creator) # Add method and upload a submission eval_container, sha256 = evaluation_image method = MethodFactory(image__from_path=eval_container, image_sha256=sha256, ready=True) # clear notifications for easier testing later Notification.objects.all().delete() # create submission and wait for it to be evaluated with capture_on_commit_callbacks() as callbacks: submission = SubmissionFactory( predictions_file__from_path=submission_file, phase=method.phase) recurse_callbacks(callbacks=callbacks) # creator of submission and admins of challenge should get notification # about successful submission recipients = list(submission.phase.challenge.get_admins()) recipients.append(submission.creator) assert Notification.objects.count() == len(recipients) for recipient in recipients: assert str(recipient) in str(Notification.objects.all()) result_string = format_html('<a href="{}">result</a>', submission.get_absolute_url()) submission_string = format_html('<a href="{}">submission</a>', submission.get_absolute_url()) challenge_string = format_html( '<a href="{}">{}</a>', submission.phase.challenge.get_absolute_url(), submission.phase.challenge.short_name, ) assert f"There is a new {result_string} for {challenge_string}" in Notification.objects.filter( user=recipients[0]).get().print_notification(user=recipients[0]) assert f"Your {submission_string} to {challenge_string} succeeded" in Notification.objects.filter( user=recipients[1]).get().print_notification(user=recipients[1]) Notification.objects.all().delete() # update evaluation status to failed evaluation = submission.evaluation_set.first() evaluation.update_status(status=evaluation.FAILURE) assert evaluation.status == evaluation.FAILURE # notifications for admin and creator of submission assert Notification.objects.count() == len(recipients) for recipient in recipients: assert str(recipient) in str(Notification.objects.all()) assert f"The {submission_string} from {user_profile_link(Notification.objects.filter(user=recipients[0]).get().actor)} to {challenge_string} failed" in Notification.objects.filter( user=recipients[0]).get().print_notification(user=recipients[0]) assert f"Your {submission_string} to {challenge_string} failed" in Notification.objects.filter( user=recipients[1]).get().print_notification(user=recipients[1]) # check that when admin unsubscribed from phase, they no longer # receive notifications about activity related to that phase Notification.objects.all().delete() unfollow(user=submission.phase.challenge.creator, obj=submission.phase) evaluation.update_status(status=evaluation.SUCCESS) assert str(submission.phase.challenge.creator) not in str( Notification.objects.all())
def relationship_pre_delete_actstream(instance, sender, **kwargs): unfollow(instance.from_user, instance.to_user)
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 remove_user(self, user_from): unfollow(user_from, self)
def deactivate(self): logger.info("deactivating subscription %s...", self) if self.active: self.active = False self.save() unfollow(self.user, self.service.bet_group)