Ejemplo n.º 1
0
def edit_message(request, pk):
    message = get_object_or_404(Message, pk=pk)
    thread = message.thread

    if not request.user.write_perm(obj=message):
        return HttpResponse("You may not edit this message.", status=403)

    if request.method == "POST":
        form = MessageForm(request.POST)

        if form.is_valid():
            message.text = form.cleaned_data["content"]
            message.save()

            actions.follow(request.user, thread, actor_only=False)
            action.send(request.user, verb="a édité", action_object=message, target=thread)

            return HttpResponseRedirect(reverse("thread_show", args=[thread.id]) + "#message-" + str(message.id))
    else:
        form = MessageForm({"content": message.text})

    return render(
        request,
        "telepathy/edit_message.html",
        {"form": form, "thread": thread, "edited_message": message, "edit": True},
    )
Ejemplo n.º 2
0
Archivo: trip.py Proyecto: wjdp/xSACdb
 def save(self, **kwargs):
     if not self.pk:
         # If new ensure the owner follows their trip
         super(Trip, self).save(**kwargs)
         follow(self.owner.user, self, actor_only=False)
     else:
         super(Trip, self).save(**kwargs)
Ejemplo n.º 3
0
def update_editor_follows(  # noqa: C901
    instance, action, reverse, model, pk_set, **_
):  # noqa: C901

    if action not in ["post_add", "pre_remove", "pre_clear"]:
        # nothing to do for the other actions
        return

    if reverse:
        groups = [instance]
        if pk_set is None:
            users = instance.user_set.all()
        else:
            users = model.objects.filter(pk__in=pk_set).all()
    else:
        if pk_set is None:
            groups = instance.groups.all()
        else:
            groups = model.objects.filter(pk__in=pk_set).all()
        users = [instance]

    follow_objects = []
    for group in groups:
        if hasattr(group, "editors_of_algorithm"):
            follow_objects.append(group.editors_of_algorithm)
        elif hasattr(group, "editors_of_archive"):
            follow_objects.append(group.editors_of_archive)
        elif hasattr(group, "editors_of_readerstudy"):
            follow_objects.append(group.editors_of_readerstudy)
        elif hasattr(group, "admins_of_challenge"):
            # NOTE: only admins of a challenge should follow a challenge
            # and its phases
            follow_objects.append(group.admins_of_challenge)
            for phase in group.admins_of_challenge.phase_set.all():
                follow_objects.append(phase)

    for user in users:
        for obj in follow_objects:
            if action == "post_add" and obj._meta.model_name != "algorithm":
                follow(
                    user=user, obj=obj, actor_only=False, send_action=False,
                )
                # only new admins of a challenge get notified
                if obj._meta.model_name == "challenge":
                    Notification.send(
                        type=NotificationType.NotificationTypeChoices.NEW_ADMIN,
                        message="added as admin for",
                        action_object=user,
                        target=obj,
                    )
            elif action == "post_add" and obj._meta.model_name == "algorithm":
                follow(
                    user=user,
                    obj=obj,
                    actor_only=False,
                    flag="access_request",
                    send_action=False,
                )
            elif action == "pre_remove" or action == "pre_clear":
                unfollow(user=user, obj=obj, send_action=False)
Ejemplo n.º 4
0
    def setUp(self):
        settings.DEBUG = True
        self.group = Group.objects.get_or_create(name="CoolGroup")[0]
        self.user1 = User.objects.get_or_create(username="******")[0]
        self.user1.set_password("admin")
        self.user1.is_superuser = self.user1.is_active = self.user1.is_staff = True
        self.user1.save()
        self.user2 = User.objects.get_or_create(username="******")[0]

        # User1 joins group
        self.user1.groups.add(self.group)
        action.send(self.user1, verb="joined", target=self.group)

        # User1 follows User2
        follow(self.user1, self.user2)

        # User2 joins group
        self.user2.groups.add(self.group)
        action.send(self.user2, verb="joined", target=self.group)

        # User2 follows group
        follow(self.user2, self.group)

        # User1 comments on group
        # Use a site object here and predict the "__unicode__ method output"
        action.send(self.user1, verb="commented on", target=self.group)
        self.comment = Site.objects.create(domain="admin: Sweet Group!...")

        # Group responds to comment
        action.send(self.group, verb="responded to", target=self.comment)
Ejemplo n.º 5
0
    def test_correct_fields(self):
        follower = UserFactory()
        followed = UserFactory()
        q = QuestionFactory(creator=followed)
        # The above might make follows, which this test isn't about. Clear them out.
        Follow.objects.all().delete()
        follow(follower, followed)

        # Make a new action for the above. This should trigger notifications
        action.send(followed, verb='asked', action_object=q)
        act = Action.objects.order_by('-id')[0]
        notification = Notification.objects.get(action=act)

        serializer = api.NotificationSerializer(instance=notification)

        eq_(serializer.data['is_read'], False)
        eq_(serializer.data['actor'], {
            'type': 'user',
            'username': followed.username,
            'display_name': followed.profile.name,
            'avatar': profile_avatar(followed),
        })
        eq_(serializer.data['verb'], 'asked')
        eq_(serializer.data['action_object']['type'], 'question')
        eq_(serializer.data['action_object']['id'], q.id)
        eq_(serializer.data['target'], None)
        # Check that the serialized data is in the correct format. If it is
        # not, this will throw an exception.
        datetime.strptime(serializer.data['timestamp'], '%Y-%m-%dT%H:%M:%SZ')
Ejemplo n.º 6
0
def test_follow_view_permissions(client):
    user1 = UserFactory()
    user2 = UserFactory()
    f = ForumFactory(type=Forum.FORUM_POST)
    follow(user1, f)

    response = get_view_for_user(
        viewname="notifications:follow-list",
        client=client,
        method=client.get,
        user=user2,
    )
    assert response.status_code == 200
    assert (str(Follow.objects.get().follow_object)
            not in response.rendered_content)

    # user1 cannot see user2 notifications
    response = get_view_for_user(
        viewname="notifications:follow-list",
        client=client,
        method=client.get,
        user=user1,
    )
    assert response.status_code == 200
    assert str(Follow.objects.get().follow_object) in response.rendered_content
Ejemplo n.º 7
0
def followObject(request, content_type_id, object_id):
	ctype = get_object_or_404(ContentType, pk=content_type_id)
	object = get_object_or_404(ctype.model_class(), pk=object_id)
	
	Follow.objects.get_or_create(request.user, object)
	actions.follow(request.user, object, send_action=False, actor_only=False)
	return HttpResponse(simplejson.dumps(dict(success=True)))
Ejemplo n.º 8
0
 def test_following(self):
     follow(self.user, self.user1)
     url = self.get_url_args(self.user, 'following')
     response = self.client.get(url)
     self.assertEqual(response.status_code, 200)
     related_users = len(response.context['related_users'])
     self.assertEqual(related_users, self.user.follow_set.all().count())
Ejemplo n.º 9
0
def dispatcher(sender, instance, created, **kwargs):
  """
  Generic post_save handler. Dispatch a document_ready signal.
  If receiver need to update the instance, they just need to put the property `_dirty`
  """
  if getattr(instance, '_dispatched', None) is None:
    instance._dispatched = True
  else:
    logger.debug('document@post_save  {pk:%s} dispatching already dispatched. Skipping.' % instance.pk)
    # done already.
    return

  logger.debug('document@post_save  {pk:%s} dispatching @document_ready...' % instance.pk)

  document_ready.send(sender=sender, instance=instance, created=created)

  if getattr(instance, '_dirty', None) is not None:
    logger.debug('document@post_save  {pk:%s} dirty instance. Need to call instance.save()..' % instance.pk)
    instance.save()
  else:
    logger.debug('document@post_save  {pk:%s} no need to save the instance again.' % instance.pk)
  if created:
    follow(instance.owner, instance)

  from miller.tasks import document_update_search_vectors

  try:
    document_update_search_vectors.delay(instance.pk)
  except Exception as e:
    logger.exception(e)
    def test_email_preference(self):
        follow(self.user1, self.group, actor_only=False)

        models.ActionNotificationPreference.objects.create(
            action_verb='gyred and gimbled in',
            is_should_email=True
        )

        action.send(
            self.user2,
            verb='gyred and gimbled in',
            target=self.group
        )
        action.send(
            self.user2,
            verb='gimbled and gyred in',
            target=self.group
        )
        action_notification_1 = models.ActionNotification.objects.get(action__verb='gyred and gimbled in')
        action_notification_2 = models.ActionNotification.objects.get(action__verb='gimbled and gyred in')

        # Has a preference, should be true
        self.assertEquals(action_notification_1.is_should_email, True)

        # Has no preference, should be false by default
        self.assertEquals(action_notification_2.is_should_email, False)
Ejemplo n.º 11
0
def follow_group(request, pk):
    """
    Creates the follow relationship between ``request.user`` and the ``Group``
    """
    group = get_object_or_404(Group, id=pk)

    # Check user is not member of the group
    if not group.members.filter(id=request.user.id).exists():
        actions.follow(request.user, group, send_action=True)
        notify.send(
            request.user,
            recipient=group.creator,
            verb=u'has followed your Group',
            level='success')
        request.user.userprofile.follow_groups.add(group)
        messages.success(
            request,
            'Successed, you are now following this Group.')
    else:
        actions.follow(request.user, group, send_action=False)
        messages.success(
            request,
            'You are the member of this Group and automatically become the follower.')

    return redirect('groups:groups-detail', pk)
Ejemplo n.º 12
0
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()
Ejemplo n.º 13
0
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 })
Ejemplo n.º 14
0
def add_follower(request, pk):
    """ Add user to locations followers. """
    location = get_object_or_404(Location, pk=pk)
    user = request.user
    location.users.add(user)
    if user != location.creator:
        notify(user,
            location.creator,
            verb=_(u"joined to your location"),
            key="follower",
            action_target=location
        )
    try:
        location.save()
        follow(user, location, actor_only=False)
        response = {
            'success': True,
            'message': _('You follow this location'),
        }
    except:
        response = {
            'success': False,
            'message': _('Something, somewhere went terribly wrong'),
        }
    return HttpResponse(json.dumps(response))
Ejemplo n.º 15
0
 def form_valid(self, form):
     image = form.cleaned_data.get('picture', False)
     self.validate_image(image)
     obj = form.save(commit=False)
     action.send(self.request.user, verb=' a modifié ', action_object=obj)
     follow(self.request.user, obj, actor_only=False)
     return super().form_valid(form)
Ejemplo n.º 16
0
def on_created_comment(sender, instance: dillo.models.comments.Comment,
                       created, **kwargs):
    """Assign tags to a comment by parsing the content."""
    if not created:
        return
    # Extract tags and mentions from text and assign them to the Comment
    tags, mentions = extract_tags_and_mentions(instance.content)
    instance.tags.set(*tags)
    for mentioned_user in mentions:
        log.debug('Mentioning user %s in Comment %i' %
                  (mentioned_user, instance.id))
        dillo.models.mixins.Mentions.objects.create(
            user=mentioned_user,
            content_object=instance,
        )
        # TODO(fsiddi) Generate activity about mention

    # Generate activity about comment creation
    log.debug('Generating activity about comment creation')
    verb = 'commented'
    if instance.parent_comment:
        verb = 'replied'
    action.send(instance.user,
                verb=verb,
                action_object=instance,
                target=instance.entity)
    log.debug('Set user %s as follower of own comment %i' %
              (instance.user, instance.id))
    follow(instance.user, instance, actor_only=False)
Ejemplo n.º 17
0
def test_notification_sent_on_new_post(kind):
    u1 = UserFactory()
    u2 = UserFactory()
    f = ForumFactory(type=Forum.FORUM_POST)
    follow(user=u2, obj=f)
    t = TopicFactory(forum=f, poster=u1, type=kind)
    PostFactory(topic=t, poster=u2)

    notifications = Notification.objects.all()
    topic_string = format_html('<a href="{}">{}</a>', t.get_absolute_url(), t)
    forum_string = format_html('<a href="{}">{}</a>', f.get_absolute_url(), f)
    assert len(notifications) == 2
    assert (
        notifications[1]
        .print_notification(user=u1)
        .startswith(f"{user_profile_link(u2)} replied to {topic_string}")
    )

    if kind == Topic.TOPIC_ANNOUNCE:
        assert (
            notifications[0]
            .print_notification(user=u2)
            .startswith(
                f"{user_profile_link(t.poster)} announced {topic_string} in {forum_string}"
            )
        )
    else:
        assert (
            notifications[0]
            .print_notification(user=u2)
            .startswith(
                f"{user_profile_link(t.poster)} posted {topic_string} in {forum_string}"
            )
        )
Ejemplo n.º 18
0
 def test_paginator_out_of_range(self):
     # if page# is > max, then show last page
     follow(self.user, self.user1)
     url = self.get_url_args(self.user, 'following')
     response = self.client.get(url, {'page': '9999'})
     related_users = response.context['related_users']
     self.assertEqual(len(related_users), self.user.follow_set.all().count())
Ejemplo n.º 19
0
    def test_correct_fields(self):
        follower = profile()
        followed = profile()
        q = question(creator=followed.user, save=True)
        # The above might make follows, which this test isn't about. Clear them out.
        Follow.objects.all().delete()
        follow(follower.user, followed.user)

        # Make a new action for the above. This should trigger notifications
        action.send(followed.user, verb='asked', action_object=q)
        act = Action.objects.order_by('-id')[0]
        notification = Notification.objects.get(action=act)

        serializer = api.NotificationSerializer(instance=notification)

        eq_(serializer.data['is_read'], False)
        eq_(serializer.data['actor'], {
            'type': 'user',
            'username': followed.user.username,
            'display_name': followed.name,
            'avatar': profile_avatar(followed.user),
        })
        eq_(serializer.data['verb'], 'asked')
        eq_(serializer.data['action_object']['type'], 'question')
        eq_(serializer.data['action_object']['id'], q.id)
        eq_(serializer.data['target'], None)
        eq_(type(serializer.data['timestamp']), datetime)
Ejemplo n.º 20
0
def test_follow_deletion_through_api(client):
    user1 = UserFactory()
    user2 = UserFactory()
    f = ForumFactory(type=Forum.FORUM_POST)
    follow(user1, f)

    assert len(Follow.objects.all()) == 1

    # users can only delete their own follows
    response = get_view_for_user(
        viewname="api:follow-detail",
        client=client,
        method=client.delete,
        reverse_kwargs={"pk": Follow.objects.get().pk},
        content_type="application/json",
        user=user2,
    )
    assert response.status_code == 404

    response = get_view_for_user(
        viewname="api:follow-detail",
        client=client,
        method=client.delete,
        reverse_kwargs={"pk": Follow.objects.get().pk},
        content_type="application/json",
        user=user1,
    )
    assert response.status_code == 204
    assert len(Follow.objects.all()) == 0
Ejemplo n.º 21
0
def getOrCreateConversation(nom1, nom2):
    try:
        convers = Conversation.objects.get(
            slug=get_slug_from_names(nom1, nom2))
    except Conversation.DoesNotExist:
        profil_1 = Profil.objects.get(username=nom1)
        profil_2 = Profil.objects.get(username=nom2)
        convers = Conversation.objects.create(profil1=profil_1,
                                              profil2=profil_2)

        conversations = Conversation.objects.filter(
            Q(profil2=profil_1) | Q(profil1=profil_1))
        for conv in conversations:
            if conv in following(profil_1):
                actions.follow(profil_1, convers)
                break

        conversations = Conversation.objects.filter(
            Q(profil2=profil_2) | Q(profil1=profil_2))
        for conv in conversations:
            if conv in following(profil_2):
                actions.follow(profil_2, convers)
                break

    return convers
Ejemplo n.º 22
0
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()
Ejemplo n.º 23
0
    def test_correct_fields(self):
        follower = UserFactory()
        followed = UserFactory()
        q = QuestionFactory(creator=followed)
        # The above might make follows, which this test isn't about. Clear them out.
        Follow.objects.all().delete()
        follow(follower, followed)

        # Make a new action for the above. This should trigger notifications
        action.send(followed, verb="asked", action_object=q)
        act = Action.objects.order_by("-id")[0]
        notification = Notification.objects.get(action=act)

        serializer = api.NotificationSerializer(instance=notification)

        eq_(serializer.data["is_read"], False)
        eq_(
            serializer.data["actor"],
            {
                "type": "user",
                "username": followed.username,
                "display_name": followed.profile.name,
                "avatar": profile_avatar(followed),
            },
        )
        eq_(serializer.data["verb"], "asked")
        eq_(serializer.data["action_object"]["type"], "question")
        eq_(serializer.data["action_object"]["id"], q.id)
        eq_(serializer.data["target"], None)
        # Check that the serialized data is in the correct format. If it is
        # not, this will throw an exception.
        datetime.strptime(serializer.data["timestamp"], "%Y-%m-%dT%H:%M:%SZ")
Ejemplo n.º 24
0
 def add_members(self, members, actor):
     """Add a list of members to trip"""
     if not self.can_add(actor):
         raise PermissionDenied
     # Currently we're not doing anything with member 'state' so we set that here to full approval.
     with DoAction() as action, reversion.create_revision():
         members_to_add = set(members) - set(self.members.all())
         new_members = []
         for member in members_to_add:
             # Add relationship
             tm = TripMember.objects.create(
                 trip=self,
                 member=member,
                 state=TripMember.STATE_ACCEPTED,
             )
             new_members.append(tm)
             # Newly added member should follow trip
             actions.follow(member.user, self, actor_only=False)
             # Send action
         if len(new_members) > 0:
             action.set(actor=actor,
                        verb='added',
                        action_object=list(members_to_add),
                        target=self,
                        style='trip-attendee-add')
     return new_members
Ejemplo n.º 25
0
def choose_people_to_follow(request):
    """
	Step 2 of welcome wizard- presents newly registered user some suggested people to follow.
	Users to follow are selected either from:
		1) Category model's recommended_users_to_follow field
		2) At random from users with at least 40 pins 
		3) At random from all users with pins in selected categories
	"""
    #how many users should we show per category
    USERS_PER_CATEGORY = 4
    USER_PREFERRED_NUMBER_OF_PINS = 40

    selected_categories = Category.objects.filter(
        pk__in=request.session['selected_categories'])

    for c in selected_categories:
        c.users_to_follow = c.suggest_users_to_follow(
            USERS_PER_CATEGORY, USER_PREFERRED_NUMBER_OF_PINS)

    if request.method == "POST":
        if len(request.POST['selected_users']) > 0:
            users_list = request.POST['selected_users'].split(',')
            users_qs = User.objects.filter(pk__in=users_list)
            for u in users_qs:
                follow(request.user, u)

        return redirect('create_initial_boards')
    return direct_to_template(request, "pins/welcome/step_2.html", locals())
Ejemplo n.º 26
0
def new_thread(request, course_slug=None, document_id=None):
    if document_id is not None:
        document = get_object_or_404(Document, id=document_id)
        course = document.course
    else:
        course = get_object_or_404(Course, slug=course_slug)
        document = None

    if request.method == "POST":
        form = NewThreadForm(request.POST)

        if form.is_valid():
            name = form.cleaned_data["name"]
            content = form.cleaned_data["content"]

            thread = Thread.objects.create(user=request.user, name=name, course=course, document=document)
            message = Message.objects.create(user=request.user, thread=thread, text=content)

            placement = {}
            for opt, typecast in Thread.PLACEMENT_OPTS.items():
                if opt in request.POST:
                    placement[opt] = typecast(request.POST[opt])
            if len(placement) > 0:
                thread.placement = json.dumps(placement)
                thread.save()

            actions.follow(request.user, thread, actor_only=False)
            action.send(request.user, verb="a posté", action_object=thread, target=course, markdown=message.text)

            return HttpResponseRedirect(reverse("thread_show", args=[thread.id]) + "#message-" + str(message.id))
    else:
        form = NewThreadForm()

    return render(request, "telepathy/new_thread.html", {"form": form, "course": course})
Ejemplo n.º 27
0
 def save(self, **kwargs):
     if not self.pk:
         # If new ensure the owner follows their trip
         super(Trip, self).save(**kwargs)
         follow(self.owner.user, self, actor_only=False)
     else:
         super(Trip, self).save(**kwargs)
Ejemplo n.º 28
0
def advisors_form(request, advisor_pk=None):
    curr_coordinator = Coordinator.objects.get(user=request.user)

    advisor = None
    if advisor_pk:
        advisor = Advisor.objects.get(pk=advisor_pk)

    if request.method == 'POST':
        form = AdvisorForm(request.POST, instance=advisor, coor=curr_coordinator)
        if form.is_valid():
            if type(advisor) == Advisor:
                form.save()
            else:
                f = form.save(commit=False)
                f.school = curr_coordinator.school
                # Create user in django auth
                advisor_email = form.cleaned_data['email']
                try:
                    new_advisor = User.objects\
                        .create_user(advisor_email, advisor_email)
                except IntegrityError:
                    new_advisor = User.objects.get(email=advisor_email)
                new_advisor.user_permissions.add(ADVISOR_PERM)
                f.user = new_advisor
                f.save()
                form.save()
                curr_coordinator.advisors.add(f)
                follow(request.user, f)
                follow(new_advisor, curr_coordinator)
            return HttpResponseRedirect('/coordinator')
    else:
        form = AdvisorForm(instance=advisor, coor=curr_coordinator)
    return render(request, 'journal/advisor_registration.html',
                  {'form': form, 'coordinator': curr_coordinator})
Ejemplo n.º 29
0
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))
Ejemplo n.º 30
0
    def save(self, *args, **kwargs):
        agora = super(CreateAgoraForm, self).save(commit=False)
        agora.create_name(self.request.user)
        agora.creator = self.request.user
        agora.url = self.request.build_absolute_uri(
            reverse("agora-view", kwargs=dict(username=agora.creator.username, agoraname=agora.name))
        )

        # we need to save before add members
        agora.save()

        agora.members.add(self.request.user)
        agora.admins.add(self.request.user)

        action.send(
            self.request.user,
            verb="created",
            action_object=agora,
            ipaddr=self.request.META.get("REMOTE_ADDR"),
            geolocation=json.dumps(geolocate_ip(self.request.META.get("REMOTE_ADDR"))),
        )

        follow(self.request.user, agora, actor_only=False, request=self.request)

        return agora
Ejemplo n.º 31
0
    def save(self, *args, **kwargs):
        adding = self._state.adding

        super().save(*args, **kwargs)

        if adding:
            self.set_default_interfaces()
            self.assign_permissions()
            for admin in self.challenge.get_admins():
                if not is_following(admin, self):
                    follow(
                        user=admin,
                        obj=self,
                        actor_only=False,
                        send_action=False,
                    )

        if self.public != self._orig_public:
            on_commit(
                assign_evaluation_permissions.signature(
                    kwargs={"phase_pks": [self.pk]}
                ).apply_async
            )
            on_commit(
                assign_submission_permissions.signature(
                    kwargs={"phase_pk": self.pk}
                ).apply_async
            )

        on_commit(
            lambda: calculate_ranks.apply_async(kwargs={"phase_pk": self.pk})
        )
Ejemplo n.º 32
0
def handler(sender, instance, created, raw, **kwargs):
    if created and not raw:
        follow(instance.author.user, instance, actor_only=False, send_action=False)
    if instance.published and (created or instance.published != instance.__original_published) and not raw:
        d = instance.description + ('\nСтоимость: ' + str(instance.price)) if instance.price else ''
        action.send(instance.author.user, verb='опубликовал', action_object=instance, description=d)
    instance.__original_published = instance.published
Ejemplo n.º 33
0
def add_follower(request, pk):
    """ Add user to locations followers. """
    location = get_object_or_404(Location, pk=pk)
    user = request.user
    location.users.add(user)
    if user != location.creator:
        notify(user,
            location.creator,
            verb=_(u"joined to your location"),
            key="follower",
            action_target=location
        )
    try:
        location.save()
        follow(user, location, actor_only = False)
        response = {
            'success': True,
            'message': _('You follow this location'),
        }
    except:
        response = {
            'success': False,
            'message': _('Something, somewhere went terribly wrong'),
        }
    return HttpResponse(json.dumps(response))
Ejemplo n.º 34
0
 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, }))
Ejemplo n.º 35
0
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())
Ejemplo n.º 36
0
    def form_valid(self, form):
        obj = form.save()

        # Fill in additional many 2 many fields and author entry
        obj.participants.add(obj.creator)
        obj.authors_group.authors.add(obj.creator.author)
        obj.save()

        # Start following for author - this way he will be noticed about
        # activities related to this project.
        follow(obj.creator, obj, actor_only=False, send_action=False)

        # Change project's idea status, if there is some related object
        if obj.idea is not None:
            obj.idea.status = 4
            obj.idea.save()

        # Create markers for map view
        try:
            for m in json.loads(self.request.POST.get('markers')):
                marker = MapPointer.objects.create(
                    content_type=ContentType.objects.get_for_model(
                        SocialProject),
                    object_pk=obj.pk,
                    latitude=m['lat'],
                    longitude=m['lng'])
        except Exception:
            # FIXME: silent fail, should be a flash message
            pass

        return super(CreateProjectView, self).form_valid(form)
Ejemplo n.º 37
0
def _post_and_answer_mention_detected(user_from, user_to, target):
    action.send(user_from,
                action_object=user_to,
                target=target,
                verb=settings.MENTION_VERB)

    follow(user_to, target)
Ejemplo n.º 38
0
    def test_correct_fields(self):
        follower = profile()
        followed = profile()
        q = question(creator=followed.user, save=True)
        # The above might make follows, which this test isn't about. Clear them out.
        Follow.objects.all().delete()
        follow(follower.user, followed.user)

        # Make a new action for the above. This should trigger notifications
        action.send(followed.user, verb='asked', action_object=q)
        act = Action.objects.order_by('-id')[0]
        notification = Notification.objects.get(action=act)

        serializer = api.NotificationSerializer(instance=notification)

        eq_(serializer.data['is_read'], False)
        eq_(
            serializer.data['actor'], {
                'type': 'user',
                'username': followed.user.username,
                'display_name': followed.name,
                'avatar': profile_avatar(followed.user),
            })
        eq_(serializer.data['verb'], 'asked')
        eq_(serializer.data['action_object']['type'], 'question')
        eq_(serializer.data['action_object']['id'], q.id)
        eq_(serializer.data['target'], None)
        # Check that the serialized data is in the correct format. If it is
        # not, this will throw an exception.
        datetime.strptime(serializer.data['timestamp'], '%Y-%m-%dT%H:%M:%SZ')
Ejemplo n.º 39
0
    def form_valid(self, form):
        obj = form.save()

        # Fill in additional many 2 many fields and author entry
        obj.participants.add(obj.creator)
        obj.authors_group.authors.add(obj.creator.author)
        obj.save()

        # Start following for author - this way he will be noticed about
        # activities related to this project.
        follow(obj.creator, obj, actor_only=False, send_action=False)

        # Change project's idea status, if there is some related object
        if obj.idea is not None:
            obj.idea.status = 4
            obj.idea.save()

        # Create markers for map view
        try:
            for m in json.loads(self.request.POST.get('markers')):
                marker = MapPointer.objects.create(
                    content_type=ContentType.objects.get_for_model(
                        SocialProject),
                    object_pk=obj.pk,
                    latitude=m['lat'],
                    longitude=m['lng'])
        except Exception:
            # FIXME: silent fail, should be a flash message
            pass

        return super(CreateProjectView, self).form_valid(form)
Ejemplo n.º 40
0
 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,
                 }))
Ejemplo n.º 41
0
    def save(self, *args, **kwargs):
        agora = super(CreateAgoraForm, self).save(commit=False)
        agora.create_name(self.request.user)
        agora.creator = self.request.user
        agora.url = self.request.build_absolute_uri(
            reverse('agora-view',
                    kwargs=dict(username=agora.creator.username,
                                agoraname=agora.name)))

        # we need to save before add members
        agora.save()

        agora.members.add(self.request.user)
        agora.admins.add(self.request.user)

        action.send(self.request.user,
                    verb='created',
                    action_object=agora,
                    ipaddr=self.request.META.get('REMOTE_ADDR'),
                    geolocation=json.dumps(
                        geolocate_ip(self.request.META.get('REMOTE_ADDR'))))

        follow(self.request.user,
               agora,
               actor_only=False,
               request=self.request)

        return agora
Ejemplo n.º 42
0
 def post(self, request, location_slug=None, slug=None, task_id=None):
     task = get_object_or_404(Task, pk=task_id)
     if task.participants.filter(pk=request.user.pk).exists():
         task.participants.remove(request.user)
         message = _("You are no longer in this task")
     else:
         task.participants.add(request.user)
         if not task.group.project.participants.filter(
                 pk=request.user.pk).exists():
             task.group.project.participants.add(request.user)
             task.group.project.authors_group.authors.add(
                 request.user.author)
             joined_to_project(request.user, task.group.project)
             follow(request.user, task.group.project, actor_only=False)
         else:
             joined_to_task(request.user, task)
         message = _("You have joined this task")
     if request.is_ajax():
         context = {
             'success': True,
             'message': message,
         }
         return HttpResponse(context, content_type="application/json")
     return redirect(
         reverse('locations:task_details',
                 kwargs={
                     'location_slug': location_slug,
                     'slug': task.group.project.slug,
                     'task_id': task.pk,
                 }))
Ejemplo n.º 43
0
def submit_page(request):
    if request.method == 'POST' and 'submit-tune' in request.POST:
        tune = Tune(author=request.user)
        tune_form = TuneForm(request.POST, instance=tune)
        tune_attribution_form = TuneAttributionForm(request.POST)
        if tune_form.is_valid() and tune_attribution_form.is_valid():
            tune_form.save()
            tune_attribution = TuneAttribution(tune=tune)  # tune now has pk
            tune_attribution_form = TuneAttributionForm(
                request.POST, instance=tune_attribution)
            tune_attribution_form.save()
            action.send(request.user, verb='submitted', action_object=tune)
            actions.follow(request.user,
                           tune,
                           actor_only=False,
                           send_action=False)
            return redirect(tune.get_absolute_url())
    else:
        tune_form = TuneForm()
        tune_attribution_form = TuneAttributionForm()

    if request.method == 'POST' and 'submit-recording' in request.POST:
        recording_form = RecordingForm(request.POST)
        if recording_form.is_valid():
            recording = Recording.objects.create(
                title=recording_form.cleaned_data['title'],
                body=recording_form.cleaned_data['body'],
                date=recording_form.cleaned_data['date'],
                video=recording_form.cleaned_data['url'],
                author=request.user,
            )
            action.send(request.user,
                        verb='submitted',
                        action_object=recording)
            #TODO: actions.follow tune when UI for tunes in recording
            return redirect(recording.get_absolute_url())
    else:
        recording_form = RecordingForm()

    if request.method == 'POST' and 'submit-event' in request.POST:
        event_form = EventForm(request.POST)
        if event_form.is_valid():
            event = Event.objects.create(
                title=event_form.cleaned_data['title'],
                body=event_form.cleaned_data['body'],
                date=event_form.cleaned_data['date'],
                author=request.user,
            )
            action.send(request.user, verb='submitted', action_object=event)
            return redirect(event.get_absolute_url())
    else:
        event_form = EventForm()

    return render(
        request, 'archiver/submit.html', {
            'tune_form': tune_form,
            'tune_attribution_form': tune_attribution_form,
            'recording_form': recording_form,
            'event_form': event_form,
        })
Ejemplo n.º 44
0
def follow_unfollow(request,
                    content_type_id,
                    object_id,
                    flag=None,
                    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
Ejemplo n.º 45
0
 def post(self, request, location_slug=None, slug=None, task_id=None):
     task = get_object_or_404(Task, pk=task_id)
     if task.participants.filter(pk=request.user.pk).exists():
         task.participants.remove(request.user)
         message = _("You are no longer in this task")
     else:
         task.participants.add(request.user)
         if not task.group.project.participants.filter(
             pk=request.user.pk).exists():
             task.group.project.participants.add(request.user)
             task.group.project.authors_group.authors.add(
                 request.user.author)
             joined_to_project(request.user,
                                               task.group.project)
             follow(request.user, task.group.project, actor_only=False)
         else:
             joined_to_task(request.user, task)
         message = _("You have joined this task")
     if request.is_ajax():
         context = {'success': True, 'message': message, }
         return HttpResponse(context, content_type="application/json")
     return redirect(reverse('locations:task_details',
                             kwargs={
                                 'location_slug': location_slug,
                                 'slug': task.group.project.slug,
                                 'task_id': task.pk,
                             }))
Ejemplo n.º 46
0
def edit_message(request, pk):
    message = get_object_or_404(Message, pk=pk)
    thread = message.thread

    if not request.user.write_perm(obj=message):
        return HttpResponse('You may not edit this message.', status=403)

    if request.method == 'POST':
        form = MessageForm(request.POST)

        if form.is_valid():
            message.text = form.cleaned_data['content']
            message.save()

            actions.follow(request.user, thread, actor_only=False)
            action.send(request.user, verb="a édité", action_object=message, target=thread)

            return HttpResponseRedirect(reverse('thread_show', args=[thread.id]) + "#message-" + str(message.id))
    else:
        form = MessageForm({'content': message.text})

    return render(request, 'telepathy/edit_message.html', {
        'form': form,
        'thread': thread,
        'edited_message': message,
        'edit': True,
    })
Ejemplo n.º 47
0
    def test_doesnt_generate_duplicate_follow_records(self):
        g = Group.objects.get_or_create(name='DupGroup')[0]
        s = self.User.objects.get_or_create(username='******')[0]

        f1 = follow(s, g)
        self.assertTrue(f1 is not None, "Should have received a new follow "
                        "record")
        self.assertTrue(isinstance(f1, Follow), "Returns a Follow object")

        follows = Follow.objects.filter(user=s,
                                        object_id=g.pk,
                                        content_type=self.group_ct)
        self.assertEqual(1, follows.count(),
                         "Should only have 1 follow record here")

        f2 = follow(s, g)
        follows = Follow.objects.filter(user=s,
                                        object_id=g.pk,
                                        content_type=self.group_ct)
        self.assertEqual(1, follows.count(),
                         "Should still only have 1 follow record here")
        self.assertTrue(f2 is not None, "Should have received a Follow object")
        self.assertTrue(isinstance(f2, Follow), "Returns a Follow object")
        self.assertEqual(
            f1, f2, "Should have received the same Follow "
            "object that I first submitted")
Ejemplo n.º 48
0
def edit_message(request, pk):
    message = get_object_or_404(Message, pk=pk)
    thread = message.thread

    if not request.user.write_perm(obj=message):
        return HttpResponse('You may not edit this message.', status=403)

    if request.method == 'POST':
        form = MessageForm(request.POST)

        if form.is_valid():
            message.text = form.cleaned_data['content']
            message.save()

            actions.follow(request.user, thread, actor_only=False)
            action.send(request.user,
                        verb="a édité",
                        action_object=message,
                        target=thread)

            return HttpResponseRedirect(
                reverse('thread_show', args=[thread.id]) + "#message-" +
                str(message.id))
    else:
        form = MessageForm({'content': message.text})

    return render(request, 'telepathy/edit_message.html', {
        'form': form,
        'thread': thread,
        'edited_message': message,
        'edit': True,
    })
Ejemplo n.º 49
0
    def test_correct_fields(self):
        follower = profile()
        followed = profile()
        q = question(creator=followed.user, save=True)
        # The above might make follows, which this test isn't about. Clear them out.
        Follow.objects.all().delete()
        follow(follower.user, followed.user)

        # Make a new action for the above. This should trigger notifications
        action.send(followed.user, verb='asked', action_object=q)
        act = Action.objects.order_by('-id')[0]
        notification = Notification.objects.get(action=act)

        serializer = api.NotificationSerializer(instance=notification)

        eq_(serializer.data['is_read'], False)
        eq_(
            serializer.data['actor'], {
                'type': 'user',
                'username': followed.user.username,
                'display_name': followed.name
            })
        eq_(serializer.data['verb'], 'asked')
        eq_(serializer.data['action_object'], {
            'type': 'question',
            'id': q.id,
        })
        eq_(serializer.data['target'], None)
        eq_(type(serializer.data['timestamp']), datetime)
Ejemplo n.º 50
0
 def test_followed_user_is_not_suggested(self):
     followed_user = UserFactory()
     follow(self.user, followed_user)
     response = self.client.get(reverse('profile-my-suggestions'))
     self.assertIsInstance(response.data, list)
     ids = [_['id'] for _ in response.data]
     self.assertNotIn(str(followed_user.profile.id), ids)
Ejemplo n.º 51
0
 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))
Ejemplo n.º 52
0
    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, })
Ejemplo n.º 53
0
def choose_people_to_follow(request):
	"""
	Step 2 of welcome wizard- presents newly registered user some suggested people to follow.
	Users to follow are selected either from:
		1) Category model's recommended_users_to_follow field
		2) At random from users with at least 40 pins 
		3) At random from all users with pins in selected categories
	"""
	#how many users should we show per category
	USERS_PER_CATEGORY = 4
	USER_PREFERRED_NUMBER_OF_PINS = 40

	selected_categories = Category.objects.filter(pk__in=request.session['selected_categories'])

	for c in selected_categories:
		c.users_to_follow = c.suggest_users_to_follow(USERS_PER_CATEGORY, USER_PREFERRED_NUMBER_OF_PINS)

	if request.method=="POST":
		if len(request.POST['selected_users'])>0:
			users_list = request.POST['selected_users'].split(',')
			users_qs = User.objects.filter(pk__in=users_list)
			for u in users_qs:
				follow(request.user, u)

		return redirect('create_initial_boards')
	return direct_to_template(request, "pins/welcome/step_2.html", locals())
Ejemplo n.º 54
0
    def setUp(self):
        super(ActivityTestCase, self).setUp()
        self.group = Group.objects.create(name='CoolGroup')
        self.user1 = User.objects.get_or_create(username='******')[0]
        self.user1.set_password('admin')
        self.user1.is_superuser = self.user1.is_staff = True
        self.user1.save()
        self.user2 = User.objects.get_or_create(username='******')[0]

        # User1 joins group
        self.user1.groups.add(self.group)
        action.send(self.user1, verb='joined', target=self.group)

        # User1 follows User2
        follow(self.user1, self.user2)

        # User2 joins group
        self.user2.groups.add(self.group)
        action.send(self.user2, verb='joined', target=self.group)

        # User2 follows group
        follow(self.user2, self.group)

        # User1 comments on group
        # Use a site object here and predict the "__unicode__ method output"
        action.send(self.user1, verb='commented on', target=self.group)
        self.comment = Site.objects.create(
            domain="admin: Sweet Group!...")

        # Group responds to comment
        action.send(self.group, verb='responded to', target=self.comment)
Ejemplo n.º 55
0
    def accept_invitation(self, request, pk):
        user = self.get_object()

        relationships = Relationship.objects.filter(initiator=user,
                                                    recipient=request.user)
        if not relationships.only_awaiting().exists():
            return Response({'detail': 'You cannot accept this invitation'},
                            status=status.HTTP_400_BAD_REQUEST)

        relationship = relationships.get()
        relationship.status = Relationship.STATUS_ACCEPTED
        relationship.save()

        invitation_messages = Message.objects.filter(
            sender=user, recipient=request.user, type=Message.TYPE_INVITATION)
        if invitation_messages.exists():
            invitation_message = invitation_messages.first()
            Message.objects.create(sender=request.user,
                                   recipient=user,
                                   parent=invitation_message,
                                   type=Message.TYPE_INVITATION_RESPONSE,
                                   is_read=True)
            invitation_message.is_read = True
            invitation_message.save()

        action.send(request.user,
                    verb=VERB_ESTABLISHED_FRIENDSHIP,
                    target=user)
        follow(request.user, user, actor_only=False)
        follow(user, request.user, actor_only=False)

        return Response(None, status=status.HTTP_200_OK)
Ejemplo n.º 56
0
 def setUp(self):
     agency = AgencyFactory()
     self.owner = UserFactory()
     self.follower = UserFactory()
     self.request = FOIARequestFactory(user=self.owner, agency=agency)
     follow(self.follower, self.request)
     self.action = new_action(agency, 'completed', target=self.request)
Ejemplo n.º 57
0
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]))
Ejemplo n.º 58
0
 def form_valid(self, form):
     obj = form.save(commit=False)
     obj.creator = self.request.user
     obj.save()
     form.save_m2m()
     obj.users.add(self.request.user)
     follow(self.request.user, obj)
     return super(OrganizationCreateView, self).form_valid(form)
Ejemplo n.º 59
0
    def create_relationship(self, user, me):
        """Start following the user if exists and is not the logged in user."""
        if user.pk is me.pk:
            return HttpBadRequest("A user can't follow itself.")

        me.relationships.add(user)
        # Follow activity stream
        actions.follow(me, user)