def edit_participants(request, slug): project = get_object_or_404(Project, slug=slug) if request.method == 'POST': form = project_forms.ProjectAddParticipantForm(project, request.POST) if form.is_valid(): user = form.cleaned_data['user'] organizing = form.cleaned_data['organizer'] participation = Participation(project=project, user=user, organizing=organizing) participation.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass messages.success(request, _('Participant added.')) return http.HttpResponseRedirect( reverse('projects_edit_participants', kwargs=dict(slug=project.slug))) else: messages.error(request, _('There was an error adding the participant.')) else: form = project_forms.ProjectAddParticipantForm(project) return render_to_response('projects/project_edit_participants.html', { 'project': project, 'form': form, 'participations': project.participants().order_by('joined_on'), 'participants_tab': True, }, context_instance=RequestContext(request))
def accept_sign_up(request, slug, comment_id, as_organizer=False): page = get_object_or_404(Page, project__slug=slug, slug='sign-up') project = page.project answer = page.comments.get(pk=comment_id) organizing = project.organizers().filter(user=answer.author.user).exists() participating = project.participants().filter(user=answer.author.user).exists() if answer.reply_to or organizing or participating or request.method != 'POST': return HttpResponseForbidden(_("You can't see this page")) participation = Participation(project=project, user=answer.author, organizing=as_organizer) participation.save() new_rel = Relationship(source=answer.author, target_project=project) try: new_rel.save() except IntegrityError: pass accept_content = detail_description_content = render_to_string( "content/accept_sign_up_comment.html", {'as_organizer': as_organizer}) accept_comment = PageComment(content=accept_content, author = request.user.get_profile(), page = page, reply_to = answer, abs_reply_to = answer) accept_comment.save() if as_organizer: messages.success(request, _('Organizer added!')) else: messages.success(request, _('Participant added!')) return HttpResponseRedirect(answer.get_absolute_url())
def edit_participants(request, slug): project = get_object_or_404(Project, slug=slug) if request.method == 'POST': form = project_forms.ProjectAddParticipantForm(project, request.POST) if form.is_valid(): user = form.cleaned_data['user'] organizing = form.cleaned_data['organizer'] participation = Participation(project=project, user=user, organizing=organizing) participation.save() new_rel = Relationship(source=user, target_project=project) new_rel.deleted = False new_rel.save() messages.success(request, _('Participant added.')) return http.HttpResponseRedirect(reverse( 'projects_edit_participants', kwargs=dict(slug=project.slug))) else: messages.error(request, _('There was an error adding the participant.')) else: form = project_forms.ProjectAddParticipantForm(project) return render_to_response('projects/project_edit_participants.html', { 'project': project, 'form': form, 'participations': project.participants().order_by('joined_on'), 'participants_tab': True, }, context_instance=RequestContext(request))
def edit_participants(request, slug): project = get_object_or_404(Project, slug=slug) if request.method == 'POST': form = project_forms.ProjectAddParticipantForm(project, request.POST) if form.is_valid(): user = form.cleaned_data['user'] participation = Participation(project= project, user=user) participation.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass messages.success(request, _('Participant added.')) return http.HttpResponseRedirect( reverse('projects_edit_participants', kwargs=dict(slug=project.slug))) else: messages.error(request, _('There was an error adding the participant.')) else: form = project_forms.ProjectAddParticipantForm(project) return render_to_response('projects/project_edit_participants.html', { 'project': project, 'form': form, 'participations': project.participants(), }, context_instance=RequestContext(request))
def test_unidirectional_user_relationship(self): """Test a one way relationship between two users.""" # User 1 follows User 2 relationship = Relationship( source=self.user_one, target_user=self.user_two, ) relationship.save() self.assertEqual(self.user_one.following(), [self.user_two])
def test_no_new_follower_email_preference(self): """Test user is *not* emailed when they get a new follower when that user does *not* want to be emailed when they get a new follower.""" AccountPreferences(user=self.user_two, key='no_email_new_follower', value=1).save() relationship = Relationship( source=self.user_one, target_user=self.user_two, ) relationship.save() self.assertEquals(len(mail.outbox), 0)
def test_new_follower_email_preference(self): """Test user is emailed when they get a new follower when that user wants to be emailed when they get a new follower.""" relationship = Relationship( source=self.user_one, target_user=self.user_two, ) relationship.save() self.assertEquals(len(mail.outbox), 1) self.assertEquals(mail.outbox[0].to, [self.user_two.email,])
def create(request): user = request.user.get_profile() school = None if request.method == 'POST': form = project_forms.CreateProjectForm(request.POST) if form.is_valid(): project = form.save() act = Activity(actor=user, verb='http://activitystrea.ms/schema/1.0/post', project=project, target_project=project) act.save() participation = Participation(project= project, user=user, organizing=True) participation.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass detailed_description_content = render_to_string( "projects/detailed_description_initial_content.html", {}) detailed_description = Page(title=_('Full Description'), slug='full-description', content=detailed_description_content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up_content = render_to_string("projects/sign_up_initial_content.html", {}) sign_up = Page(title=_('Sign-Up'), slug='sign-up', content=sign_up_content, listed=False, editable=False, author_id=user.id, project_id=project.id) sign_up.save() project.sign_up_id = sign_up.id project.save() messages.success(request, _('The study group has been created.')) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, })) else: messages.error(request, _("There was a problem creating the study group.")) else: if 'school' in request.GET: try: school = School.objects.get(slug=request.GET['school']) form = project_forms.CreateProjectForm(initial={'school': school}) except School.DoesNotExist: return http.HttpResponseRedirect(reverse('projects_create')) else: form = project_forms.CreateProjectForm() return render_to_response('projects/project_edit_summary.html', { 'form': form, 'new_tab': True, 'school': school, }, context_instance=RequestContext(request))
def test_bidirectional_relationship(self): """Test symmetric relationship.""" Relationship(source=self.user_one, target_user=self.user_two).save() Relationship(source=self.user_two, target_user=self.user_one).save() rels_one = self.user_one.following() rels_two = self.user_two.following() self.assertTrue(self.user_one in rels_two) self.assertTrue(self.user_two not in rels_two) self.assertTrue(self.user_two in rels_one) self.assertTrue(self.user_one not in rels_one)
def test_no_new_follower_email_preference(self): """ Test user is *not* emailed when they get a new follower when that user does *not* want to be emailed when they get a new follower. """ set_notification_subscription(self.user_two, 'new-follower', False) relationship = Relationship( source=self.user_one, target_user=self.user_two, ) relationship.save() self.assertEquals(len(mail.outbox), 0)
def test_new_follower_email_preference(self): """ Test user is emailed when they get a new follower when that user wants to be emailed when they get a new follower. """ relationship = Relationship( source=self.user_one, target_user=self.user_two, ) relationship.save() self.assertEquals(len(mail.outbox), 1) self.assertEquals(mail.outbox[0].to, [ self.user_two.email, ])
def test_no_new_follower_email_preference(self): """ Test user is *not* emailed when they get a new follower when that user does *not* want to be emailed when they get a new follower. """ AccountPreferences(user=self.user_two, key='no_email_new_follower', value=1).save() relationship = Relationship( source=self.user_one, target_user=self.user_two, ) relationship.save() self.assertEquals(len(mail.outbox), 0)
def test_narcissistic_user(self): """Test that one cannot follow oneself.""" relationship = Relationship( source=self.user_one, target_user=self.user_one, ) self.assertRaises(ValidationError, relationship.save)
def add_follower(request, slug): project = get_object_or_404(Project, slug=slug) if request.method == 'POST' and 'username' in request.POST: username = request.POST['username'] user = UserProfile.objects.filter(username=username)[0] if not user: messages.error( request, _('Username %s does not exist' % username)) else: new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: messages.error( request, _('You are already following this course')) return HttpResponseRedirect(request.META['HTTP_REFERER'])
def test_activity_creation(self): """Test that an activity is created when a relationship is created.""" self.assertEqual(0, Activity.objects.count()) Relationship(source=self.user_one, target_user=self.user_two).save() activities = Activity.objects.all() self.assertEqual(1, len(activities)) activity = activities[0] self.assertEqual(self.user_one, activity.actor) self.assertEqual(self.user_two, activity.target_user) self.assertEqual(verbs['follow'], activity.verb)
def test_messaging_user_following(self): print "From test: %s" % (self.user.user, ) print "From test: %s" % (self.user_two.user, ) Relationship(source=self.user_two, target_user=self.user).save() form = ComposeForm(data={ 'recipient': self.user_two, 'subject': 'Foo', 'body': 'Bar', }, sender=self.user) self.assertTrue(form.is_bound) self.assertTrue(form.is_valid())
def test_view_message(self): """Test user can view message in inbox.""" Relationship(source=self.user, target_user=self.user_two).save() message = Message(sender=self.user_two.user, recipient=self.user.user, subject='test message subject', body='test message body') message.save() self.client.login(username=self.test_username, password=self.test_password) response = self.client.get("/%s/messages/inbox/" % (self.locale, )) self.assertContains(response, 'test message body')
def test_messaging_user_following_project(self): project = Project(name='test project', short_description='abcd', long_description='edfgh', created_by=self.user) project.save() Relationship(source=self.user_two, target_project=project).save() form = ComposeForm(data={ 'recipient': self.user_two, 'subject': 'Foo', 'body': 'Bar', }, sender=self.user) self.assertTrue(form.is_bound) self.assertTrue(form.is_valid())
def accept_sign_up(request, slug, comment_id): page = get_object_or_404(Page, project__slug=slug, slug='sign-up') project = page.project user = request.user.get_profile() answer = page.comments.get(pk=comment_id) if answer.reply_to or answer.author == project.created_by or request.method != 'POST': return HttpResponseForbidden() try: participation = answer.participation return HttpResponseForbidden() except Participation.DoesNotExist: pass try: participation = project.participants().get(user=answer.author) if participation.sign_up: participation.left_on = datetime.datetime.now() participation.save() raise Participation.DoesNotExist else: participation.sign_up = answer except Participation.DoesNotExist: participation = Participation(project= project, user=answer.author, sign_up=answer) participation.save() new_rel = Relationship(source=answer.author, target_project=project) try: new_rel.save() except IntegrityError: pass accept_content = detail_description_content = render_to_string( "content/accept_sign_up_comment.html", {}) accept_comment = PageComment(content=accept_content, author=user, page=page, reply_to=answer, abs_reply_to=answer) accept_comment.save() messages.success(request, _('Participant added!')) return HttpResponseRedirect(answer.get_absolute_url())
def test_valid_sender_recipient_transaction(self): """If the recipient blacklisted the sender, the form should not validate and report an error""" blocking = RelationshipStatus.objects.get(from_slug='blocking') relationship = Relationship( from_user=self.user2, to_user=self.user1, status=blocking ) relationship.save() form = ComposeForm( { 'recipient': self.user2.username, 'subject': 'this is not empty', 'body': 'this is not empty', }, sender=self.user1, ) self.assertFalse(form.is_valid()) errors = form.errors['recipient'] self.assertEquals(1, len(errors)) expected_error_message = u"%(recipient)s has blacklisted you, you can't message him any more." expected_error_message = expected_error_message % {'recipient': self.user2} self.assertEquals(expected_error_message, errors[0])
def project_creation_handler(sender, **kwargs): project = kwargs.get('instance', None) created = kwargs.get('created', False) if not created or not isinstance(project, Project): return Relationship(source=project.created_by, target_project=project).save() try: from activity.models import Activity act = Activity(actor=project.created_by, verb='http://activitystrea.ms/schema/1.0/post', project=project, target_project=project) act.save() except ImportError: return
def test_unique_project_constraint(self): """Test that a user can't follow the same project twice.""" project = Project( name='test project', short_description='for testing', long_description='for testing relationships', created_by=self.user_one, ) project.save() # creator will automatically be following the project relationships = Relationship.objects.all() self.assertEqual(relationships[0].source, self.user_one) self.assertEqual(relationships[0].target_project, project) relationship = Relationship( source=self.user_one, target_project=project, ) self.assertRaises(IntegrityError, relationship.save)
def test_unique_user_constraint(self): """Test that a user can't follow another user twice.""" # User 1 follows User 2 relationship = Relationship( source=self.user_one, target_user=self.user_two, ) relationship.save() # Try again relationship = Relationship( source=self.user_one, target_user=self.user_two, ) self.assertRaises(IntegrityError, relationship.save)
def test_unique_project_constraint(self): """Test that a user can't follow the same project twice.""" project = Project( name='test project', short_description='for testing', long_description='for testing relationships', ) project.save() relationship = Relationship( source=self.user_one, target_project=project, ) relationship.save() relationship = Relationship( source=self.user_one, target_project=project, ) self.assertRaises(IntegrityError, relationship.save)
def follow(request, object_type, slug): profile = request.user.get_profile() if object_type == PROJECT: project = get_object_or_404(Project, slug=slug) relationship = Relationship(source=profile, target_project=project) elif object_type == USER: user = get_object_or_404(UserProfile, username=slug) relationship = Relationship(source=profile, target_user=user) else: raise Http404 try: relationship.save() except IntegrityError: if object_type == PROJECT: messages.error( request, _('You are already following this study group')) else: messages.error(request, _('You are already following this user')) log.warn("Attempt to create duplicate relationship: %s" % ( relationship,)) return HttpResponseRedirect(request.META['HTTP_REFERER'])
def clone(request): user = request.user.get_profile() if 'school' in request.GET: try: school = School.objects.get(slug=request.GET['school']) except School.DoesNotExist: return http.HttpResponseRedirect(reverse('projects_clone')) else: school = None if request.method == 'POST': form = project_forms.CloneProjectForm(school, request.POST) if form.is_valid(): base_project = form.cleaned_data['project'] project = Project(name=base_project.name, short_description=base_project.short_description, long_description=base_project.long_description, school=base_project.school, clone_of=base_project) project.save() act = Activity(actor=user, verb='http://activitystrea.ms/schema/1.0/post', project=project, target_project=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass detailed_description = Page(title=_('Full Description'), slug='full-description', content=base_project.detailed_description.content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up = Page(title=_('Sign-Up'), slug='sign-up', content=base_project.sign_up.content, listed=False, editable=False, author_id=user.id, project_id=project.id) sign_up.save() project.sign_up_id = sign_up.id project.save() tasks = Page.objects.filter(project=base_project, listed=True, deleted=False).order_by('index') for task in tasks: new_task = Page(title=task.title, content=task.content, author=user, project=project) new_task.save() links = Link.objects.filter(project=base_project).order_by('index') for link in links: new_link = Link(name=link.name, url=link.url, user=user, project=project) new_link.save() messages.success(request, _('The study group has been cloned.')) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, })) else: messages.error(request, _("There was a problem cloning the study group.")) else: form = project_forms.CloneProjectForm(school) return render_to_response('projects/project_clone.html', { 'form': form, 'clone_tab': True, 'school': school, }, context_instance=RequestContext(request))
def comment_sign_up(request, slug, comment_id=None): page = get_object_or_404(Page, project__slug=slug, slug='sign-up') project = page.project user = request.user.get_profile() reply_to = abs_reply_to = None if comment_id: reply_to = page.comments.get(pk=comment_id) abs_reply_to = reply_to while abs_reply_to.reply_to: abs_reply_to = abs_reply_to.reply_to elif project.signup_closed: return HttpResponseForbidden() if user != project.created_by: participants = project.participants() author = abs_reply_to.author if abs_reply_to else user if participants.filter(user=user).exists(): if author != project.created_by and not participants.filter(user=author).exists(): return HttpResponseForbidden() elif author != user: return HttpResponseForbidden() if request.method == 'POST': form = CommentForm(request.POST) profile_form = ProfileEditForm(request.POST, instance=user) profile_image_form = ProfileImageForm() if form.is_valid() and (reply_to or profile_form.is_valid()): if not reply_to: profile_form.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass comment = form.save(commit=False) comment.page = page comment.author = user comment.reply_to = reply_to comment.abs_reply_to = abs_reply_to comment.save() success_msg = _('Reply posted!') if reply_to else _('Answer submitted!') messages.success(request, success_msg) return HttpResponseRedirect(reverse('page_show', kwargs={ 'slug': slug, 'page_slug': page.slug, })) else: error_msg = _('There was a problem posting your reply. Reply cannot be empty. ') if reply_to \ else _('There was a problem submitting your answer. Answer cannot be empty. ') messages.error(request, error_msg) else: profile_form = ProfileEditForm(instance=user) profile_image_form = ProfileImageForm() form = CommentForm() return render_to_response('content/comment_sign_up.html', { 'profile_image_form': profile_image_form, 'profile_form': profile_form, 'profile': user, 'form': form, 'project': project, 'page': page, 'reply_to': reply_to, }, context_instance=RequestContext(request))
def test_user_followers(self): """Test the followers method of the User model.""" self.assertTrue(len(self.user_two.followers()) == 0) Relationship(source=self.user_one, target_user=self.user_two).save() self.assertTrue(len(self.user_two.followers()) == 1) self.assertEqual(self.user_one, self.user_two.followers()[0])
def import_from_old_site(request): user = request.user.get_profile() if 'school' in request.GET: try: school = School.objects.get(slug=request.GET['school']) except School.DoesNotExist: return http.HttpResponseRedirect(reverse('projects_clone')) else: school = None if request.method == 'POST': form = project_forms.ImportProjectForm(school, request.POST) if form.is_valid(): course = form.cleaned_data['course'] project = Project(name=course['name'], short_description= course['short_description'], long_description=course['long_description'], school=course['school'], imported_from=course['slug']) project.save() act = Activity(actor=user, verb='http://activitystrea.ms/schema/1.0/post', project=project, target_project=project) act.save() participation = Participation(project=project, user=user, organizing=True) participation.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass if course['detailed_description']: detailed_description_content = course['detailed_description'] else: detailed_description_content = render_to_string( "projects/detailed_description_initial_content.html", {}) detailed_description = Page(title=_('Full Description'), slug='full-description', content=detailed_description_content, listed=False, author_id=user.id, project_id=project.id) detailed_description.save() project.detailed_description_id = detailed_description.id sign_up_content = render_to_string("projects/sign_up_initial_content.html", {}) sign_up = Page(title=_('Sign-Up'), slug='sign-up', content=sign_up_content, listed=False, editable=False, author_id=user.id, project_id=project.id) sign_up.save() project.sign_up_id = sign_up.id project.save() for title, content in course['tasks']: new_task = Page(title=title, content=content, author=user, project=project) new_task.save() for name, url in course['links']: new_link = Link(name=name, url=url, user=user, project=project) new_link.save() messages.success(request, _('The study group has been imported.')) return http.HttpResponseRedirect(reverse('projects_show', kwargs={ 'slug': project.slug, })) else: messages.error(request, _("There was a problem importing the study group.")) else: form = project_forms.ImportProjectForm(school) return render_to_response('projects/project_import.html', { 'form': form, 'import_tab': True, 'school': school, }, context_instance=RequestContext(request))
def comment_sign_up(request, slug, comment_id=None): page = get_object_or_404(Page, project__slug=slug, slug='sign-up') project = page.project user = request.user.get_profile() is_organizing = project.organizers().filter(user=user).exists() is_participating = project.participants().filter(user=user).exists() reply_to = abs_reply_to = None if comment_id: reply_to = page.comments.get(pk=comment_id) abs_reply_to = reply_to while abs_reply_to.reply_to: abs_reply_to = abs_reply_to.reply_to if not is_organizing: if is_participating: if not project.is_participating(abs_reply_to.author.user): return HttpResponseForbidden(_("You can't see this page")) elif abs_reply_to.author != user: return HttpResponseForbidden(_("You can't see this page")) elif project.signup_closed or is_organizing or is_participating: return HttpResponseForbidden(_("You can't see this page")) else: answers = page.comments.filter(reply_to__isnull=True, deleted=False, author=user) if answers.exists(): return HttpResponseForbidden(_("There exists already an answer")) if request.method == 'POST': form = CommentForm(request.POST) profile_form = ProfileEditForm(request.POST, instance=user) profile_image_form = ProfileImageForm() if form.is_valid() and (reply_to or profile_form.is_valid()): if not reply_to: profile_form.save() new_rel = Relationship(source=user, target_project=project) try: new_rel.save() except IntegrityError: pass comment = form.save(commit=False) comment.page = page comment.author = user comment.reply_to = reply_to comment.abs_reply_to = abs_reply_to comment.save() success_msg = _('Reply posted!') if reply_to else _('Answer submitted!') messages.success(request, success_msg) return HttpResponseRedirect(comment.get_absolute_url()) else: error_msg = _('There was a problem posting your reply. Reply cannot be empty. ') if reply_to \ else _('There was a problem submitting your answer. Answer cannot be empty. ') messages.error(request, error_msg) else: profile_form = ProfileEditForm(instance=user) profile_image_form = ProfileImageForm() form = CommentForm() return render_to_response('content/comment_sign_up.html', { 'profile_image_form': profile_image_form, 'profile_form': profile_form, 'profile': user, 'form': form, 'project': project, 'page': page, 'reply_to': reply_to, }, context_instance=RequestContext(request))
def test_user_is_following(self): """Test the is_following method of the User model.""" self.assertFalse(self.user_one.is_following(self.user_two)) Relationship(source=self.user_one, target_user=self.user_two).save() self.assertTrue(self.user_one.is_following(self.user_two))