def report_abuse(request, model, app_label, pk): """Report abusive or irrelavent content.""" if request.method == 'POST': # we only use the form for the csrf middleware. skip validation. form = AbuseForm(request.POST) content_type_cls = get_object_or_404(ContentType, model=model, app_label=app_label).model_class() instance = get_object_or_404(content_type_cls, pk=pk) try: url = request.build_absolute_uri(instance.get_absolute_url()) except NoReverseMatch: url = request.build_absolute_uri(reverse('dashboard')) subject_template = 'drumbeat/emails/abuse_report_subject.txt' body_template = 'drumbeat/emails/abuse_report.txt' context = { 'user': request.user.get_profile(), 'url': url, 'model': model, 'app_label': app_label, 'pk': pk, } try: profile = UserProfile.objects.get(email=settings.ADMINS[0][1]) send_notifications([profile], subject_template, body_template, context) except: log.debug("Error sending abuse report: %s" % sys.exc_info()[0]) pass return render_to_response('drumbeat/report_received.html', {}, context_instance=RequestContext(request)) else: form = AbuseForm() return render_to_response('drumbeat/report_abuse.html', { 'form': form, 'model': model, 'app_label': app_label, 'pk': pk, }, context_instance=RequestContext(request))
def test_reply_by_email(self): subject_template = 'replies/emails/post_comment_subject.txt' body_template = 'replies/emails/post_comment.txt' context = { 'comment': self.comment, 'domain': 'example.org', } callback_url = "/{0}/comments/{1}/email_reply/".format(self.locale, self.comment.id) send_notifications( self.user, subject_template, body_template, context, callback_url ) self.assertEqual(ResponseToken.objects.count(), 1) token = ResponseToken.objects.all()[0] data = { u'from': [u'Testing <*****@*****.**>'], u'to': [u'reply+{0}@reply.p2pu.org'.format(token.response_token)], u'text': [u'Maybe this time\n'], } #post_notification_response(token, '*****@*****.**', 'my response') response = self.client.post('/{0}/notifications/response/'.format(self.locale), data) self.assertEqual(response.status_code, 200)
def test_reply_by_email(self): subject_template = 'replies/emails/post_comment_subject.txt' body_template = 'replies/emails/post_comment.txt' context = { 'comment': self.comment, 'domain': 'example.org', } callback_url = "/{0}/comments/{1}/email_reply/".format( self.locale, self.comment.id) send_notifications(self.user, subject_template, body_template, context, callback_url) self.assertEqual(ResponseToken.objects.count(), 1) token = ResponseToken.objects.all()[0] data = { u'from': [u'Testing <*****@*****.**>'], u'to': [u'reply+{0}@reply.p2pu.org'.format(token.response_token)], u'text': [u'Maybe this time\n'], } #post_notification_response(token, '*****@*****.**', 'my response') response = self.client.post( '/{0}/notifications/response/'.format(self.locale), data) self.assertEqual(response.status_code, 200)
def test_send_notification(self): subject = 'Notification subject' text = 'Notifications body.\n\nSome random text.' html = '<html></html>' message_count = len(mail.outbox) send_notifications([self.user], subject, text, html) self.assertEqual(ResponseToken.objects.count(), 0) self.assertEqual(len(mail.outbox), message_count + 1)
def send_notification(self): """Send notification when a new submission is posted.""" subject_template = 'badges/emails/new_submission_subject.txt' body_template = 'badges/emails/new_submission.txt' context = { 'submission': self, 'domain': Site.objects.get_current().domain, } profiles = self.badge.get_adopters() send_notifications(profiles, subject_template, body_template, context)
def send_new_signup_answer_notification(answer): recipients = answer.sign_up.project.organizers() subject_template = 'signups/emails/new_signup_answer_subject.txt' body_template = 'signups/emails/new_signup_answer.txt' context = { 'answer': answer, 'domain': Site.objects.get_current().domain, } profiles = [recipient.user for recipient in recipients] send_notifications(profiles, subject_template, body_template, context)
def test_notification_with_response(self): """ Test notification with possible response """ subject_template = 'replies/emails/post_comment_subject.txt' body_template = 'replies/emails/post_comment.txt' context = { 'comment': self.comment, 'domain': 'example.org', } send_notifications(self.user, subject_template, body_template, context, "/call/me/back") self.assertEqual(ResponseToken.objects.count(), 1)
def send_comment_notification(self): recipients = self.page_object.comment_notification_recipients(self) subject_template = "replies/emails/post_comment_subject.txt" body_template = "replies/emails/post_comment.txt" context = {"comment": self, "domain": Site.objects.get_current().domain} profiles = [] for profile in recipients: if self.author != profile: profiles.append(profile) reply_url = reverse("email_reply", args=[self.id]) send_notifications(profiles, subject_template, body_template, context, reply_url, self.author.username)
def send_notifications(self): subject_template = 'reviews/emails/review_submitted_subject.txt' body_template = 'reviews/emails/review_submitted.txt' context = { 'course': self.project.name, 'reviewer': self.author.username, 'review_text': self.content, 'review_url': self.get_absolute_url(), 'domain': Site.objects.get_current().domain, } profiles = [recipient.user for recipient in self.project.organizers()] send_notifications(profiles, subject_template, body_template, context)
def test_send_notification(self): """ Test non replyable notification """ #TODO use templates and context that doesn't rely on another app! subject_template = 'replies/emails/post_comment_subject.txt' body_template = 'replies/emails/post_comment.txt' context = { 'comment': self.comment, 'domain': 'example.org', } send_notifications(self.user, subject_template, body_template, context) self.assertEqual(ResponseToken.objects.count(), 0)
def test_send_notification(self): """ Test non replyable notification """ #TODO use templates and context that doesn't rely on another app! subject_template = 'replies/emails/post_comment_subject.txt' body_template = 'replies/emails/post_comment.txt' context = { 'comment': self.comment, 'domain': 'example.org', } message_count = len(mail.outbox) send_notifications(self.user, subject_template, body_template, context) self.assertEqual(ResponseToken.objects.count(), 0)
def test_send_notification(self): subject = 'Notification subject' text = 'Notifications body.\n\nSome random text.' html = '<html></html>' message_count = len(mail.outbox) send_notifications([self.user], subject, text, html, notification_category='account') self.assertEqual(ResponseToken.objects.count(), 0) self.assertEqual(len(mail.outbox), message_count + 1)
def notifications_create(request): """ API call for creating notifications Json data should look like: { api-key: '34jsd8s04kl24j50sdf809sdfj', user: '******', subject: 'Notification subject', text: 'Notification text.\nProbably containing multiple paragraphs', html: '<html><head></head><body><p>Notification text.</p></body></html>', callback: 'https://mentors.p2pu.org/api/reply', sender: 'Bob Bader', category: 'badge-awarded.web-maker-badge' } Translation is the callers responsibility! """ notification_json = json.loads(request.raw_post_data) api_key = notification_json.get('api-key') if not api_key == settings.INTERNAL_API_KEY: return http.HttpResponseForbidden() username = notification_json.get('user') subject = notification_json.get('subject') text = notification_json.get('text') html = notification_json.get('html') callback_url = notification_json.get('callback') sender = notification_json.get('sender') # TODO don't default to badge once other app use this API! notification_category = notification_json.get('category', 'badges') # find user user = None try: user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: log.error("username {0} does not exist") if user and subject and text: send_notifications([user], subject, text, html, callback_url, sender, notification_category=notification_category) return http.HttpResponse(status=200) raise http.Http404
def send_comment_notification(self): recipients = self.page_object.comment_notification_recipients(self) subject_template = 'replies/emails/post_comment_subject.txt' body_template = 'replies/emails/post_comment.txt' context = { 'comment': self, 'domain': Site.objects.get_current().domain, } profiles = [] for profile in recipients: if self.author != profile: profiles.append(profile) reply_url = reverse('email_reply', args=[self.id]) send_notifications(profiles, subject_template, body_template, context, reply_url, self.author.username)
def send_abuse_report(url, reason, other, user): from users.models import UserProfile try: profile = UserProfile.objects.get(email=settings.ADMINS[0][1]) subject_template = 'drumbeat/emails/abuse_report_subject.txt' body_template = 'drumbeat/emails/abuse_report.txt' context = { 'user': user, 'url': url, 'reason': reason, 'other': other } send_notifications([profile], subject_template, body_template, context) except: log.debug("Error sending abuse report!")
def notifications_create(request): """ API call for creating notifications Json data should look like: { api-key: '34jsd8s04kl24j50sdf809sdfj', user: '******', subject: 'Notification subject', text: 'Notification text.\nProbably containing multiple paragraphs', callback: 'https://mentors.p2pu.org/api/reply', sender: 'Bob Bader' } Translation is the callers responsibility! """ notification_json = json.loads(request.raw_post_data) api_key = notification_json.get('api-key') if not api_key == settings.INTERNAL_API_KEY: return http.HttpResponseForbidden() username = notification_json.get('user') subject = notification_json.get('subject') text = notification_json.get('text') callback_url = notification_json.get('callback') sender = notification_json.get('sender') # find user user = None try: user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: log.error("username {0} does not exist") if user and subject and text: subject_template = 'notifications/emails/api_notification_subject.txt' body_template = 'notifications/emails/api_notification.txt' context = { 'subject': subject, 'text': text } send_notifications([user], subject_template, body_template, context, callback_url, sender) statsd.Statsd.increment('api-notifications') return http.HttpResponse(status=200) raise http.Http404
def send_comment_notification(self): recipients = self.page_object.comment_notification_recipients(self) subject_template = 'replies/emails/post_comment_subject.txt' body_template = 'replies/emails/post_comment.txt' context = { 'comment': self, 'domain': Site.objects.get_current().domain, } profiles = [] for profile in recipients: if self.author != profile: profiles.append(profile) reply_url = reverse('email_reply', args=[self.id]) send_notifications(profiles, subject_template, body_template, context, reply_url )
def notifications_create(request): """ API call for creating notifications Json data should look like: { api-key: '34jsd8s04kl24j50sdf809sdfj', user: '******', subject: 'Notification subject', text: 'Notification text.\nProbably containing multiple paragraphs', html: '<html><head></head><body><p>Notification text.</p></body></html>', callback: 'https://mentors.p2pu.org/api/reply', sender: 'Bob Bader', category: 'badge-awarded.web-maker-badge' } Translation is the callers responsibility! """ notification_json = json.loads(request.raw_post_data) api_key = notification_json.get('api-key') if not api_key == settings.INTERNAL_API_KEY: return http.HttpResponseForbidden() username = notification_json.get('user') subject = notification_json.get('subject') text = notification_json.get('text') html = notification_json.get('html') callback_url = notification_json.get('callback') sender = notification_json.get('sender') # TODO don't default to badge once other app use this API! notification_category = notification_json.get('category', 'badges') # find user user = None try: user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: log.error("username {0} does not exist") if user and subject and text: send_notifications([user], subject, text, html, callback_url, sender, notification_category=notification_category ) return http.HttpResponse(status=200) raise http.Http404
def notifications_create(request): """ API call for creating notifications Json data should look like: { api-key: '34jsd8s04kl24j50sdf809sdfj', user: '******', subject: 'Notification subject', text: 'Notification text.\nProbably containing multiple paragraphs', callback: 'https://mentors.p2pu.org/api/reply', sender: 'Bob Bader' } Translation is the callers responsibility! """ notification_json = json.loads(request.raw_post_data) api_key = notification_json.get('api-key') if not api_key == settings.INTERNAL_API_KEY: return http.HttpResponseForbidden() username = notification_json.get('user') subject = notification_json.get('subject') text = notification_json.get('text') callback_url = notification_json.get('callback') sender = notification_json.get('sender') # find user user = None try: user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: log.error("username {0} does not exist") if user and subject and text: subject_template = 'notifications/emails/api_notification_subject.txt' body_template = 'notifications/emails/api_notification.txt' context = {'subject': subject, 'text': text} send_notifications([user], subject_template, body_template, context, callback_url, sender) statsd.Statsd.increment('api-notifications') return http.HttpResponse(status=200) raise http.Http404
def send_creation_notification(self): """Send notification when a new project is created.""" subject_template = 'projects/emails/project_created_subject.txt' body_template = 'projects/emails/project_created.txt' context = { 'project': self, 'domain': Site.objects.get_current().domain, } profiles = [recipient.user for recipient in self.organizers()] send_notifications(profiles, subject_template, body_template, context) if not self.test: admin_subject = render_to_string( "projects/emails/admin_project_created_subject.txt", context).strip() admin_body = render_to_string( "projects/emails/admin_project_created.txt", context).strip() for admin_email in settings.ADMIN_PROJECT_CREATE_EMAIL: send_mail(admin_subject, admin_body, admin_email, [admin_email], fail_silently=True)
def send_wall_notification(self): if not self.project: return recipients = self.project.participants() subject_template = 'statuses/emails/wall_updated_subject.txt' body_template = 'statuses/emails/wall_updated.txt' context = { 'status': self, 'project': self.project, 'domain': Site.objects.get_current().domain, } from_organizer = self.project.organizers().filter( user=self.author).exists() profiles = [] for recipient in recipients: profile = recipient.user if self.important: unsubscribed = False elif from_organizer: unsubscribed = recipient.no_organizers_wall_updates else: unsubscribed = recipient.no_participants_wall_updates if self.author != profile and not unsubscribed: profiles.append(profile) kwargs = { 'page_app_label': 'activity', 'page_model': 'activity', 'page_pk': self.activity.get().id, } if self.project: kwargs.update({ 'scope_app_label': 'projects', 'scope_model': 'project', 'scope_pk': self.project.id, }) callback_url = reverse('page_comment_callback', kwargs=kwargs) send_notifications(profiles, subject_template, body_template, context, callback_url, self.author.username)
def send_wall_notification(self): if not self.project: return recipients = self.project.participants() subject_template = 'statuses/emails/wall_updated_subject.txt' body_template = 'statuses/emails/wall_updated.txt' context = { 'status': self, 'project': self.project, 'domain': Site.objects.get_current().domain, } from_organizer = self.project.organizers().filter( user=self.author).exists() profiles = [] for recipient in recipients: profile = recipient.user if self.important: unsubscribed = False elif from_organizer: unsubscribed = recipient.no_organizers_wall_updates else: unsubscribed = recipient.no_participants_wall_updates if self.author != profile and not unsubscribed: profiles.append(profile) kwargs = { 'page_app_label':'activity', 'page_model': 'activity', 'page_pk' : self.activity.get().id, } if self.project: kwargs.update({ 'scope_app_label': 'projects', 'scope_model': 'project', 'scope_pk': self.project.id, }) callback_url = reverse('page_comment_callback', kwargs=kwargs) send_notifications( profiles, subject_template, body_template, context, callback_url, self.author.username )
def send_email_notification(instance): project = instance.project if not instance.listed: return recipients = project.participants() subject_template = 'content/emails/content_update_subject.txt' body_template = 'content/emails/content_update.txt' context = { 'instance': instance, 'project': project, 'domain': Site.objects.get_current().domain, } from_organizer = project.organizers().filter(user=instance.author).exists() profiles = [] for recipient in recipients: profile = recipient.user if from_organizer: unsubscribed = recipient.no_organizers_content_updates else: unsubscribed = recipient.no_participants_content_updates if instance.author != profile and not unsubscribed: profiles.append(profile) send_notifications(profiles, subject_template, body_template, context)
def message_sent_handler(sender, **kwargs): message = kwargs.get('instance', None) created = kwargs.get('created', False) if not created or not isinstance(message, Message): return recipient = message.recipient.get_profile() preferences = AccountPreferences.objects.filter( user=recipient, key='no_email_message_received') for preference in preferences: if preference.value: return sender = message.sender.get_profile() reply_url = reverse('drumbeatmail_reply', kwargs={'message': message.pk}) msg_body = clean_html('rich', message.body) subject_template = 'drumbeatmail/emails/direct_message_subject.txt' body_template = 'drumbeatmail/emails/direct_message.txt' context = { 'sender': sender, 'message': msg_body, 'domain': Site.objects.get_current().domain, 'reply_url': reply_url, } send_notifications([recipient], subject_template, body_template, context)
def follow_handler(sender, **kwargs): rel = kwargs.get('instance', None) created = kwargs.get('created', False) if not created or not isinstance(rel, Relationship) or rel.deleted: return activity = Activity(actor=rel.source, verb=verbs['follow'], target_object=rel) recipients = [] if rel.target_user: preferences = AccountPreferences.objects.filter( user=rel.target_user, key='no_email_new_follower') for pref in preferences: if pref.value: break else: recipients.append(rel.target_user) else: activity.scope_object = rel.target_project for organizer in rel.target_project.organizers(): if organizer.user != rel.source: preferences = AccountPreferences.objects.filter( user=organizer.user, key='no_email_new_project_follower') for pref in preferences: if pref.value: break else: recipients.append(organizer.user) activity.save() subject_template = 'relationships/emails/new_follower_subject.txt' body_template = 'relationships/emails/new_follower.txt' context = { 'user': rel.source, 'project': rel.target_project, 'domain': Site.objects.get_current().domain } send_notifications(recipients, subject_template, body_template, context)
def send_email_notification(instance): project = instance.project if not instance.listed: return recipients = project.participants() subject_template = 'content/emails/content_update_subject.txt' body_template = 'content/emails/content_update.txt' context = { 'instance': instance, 'project': project, 'domain': Site.objects.get_current().domain, } from_organizer = project.organizers().filter( user=instance.author).exists() profiles = [] for recipient in recipients: profile = recipient.user if from_organizer: unsubscribed = recipient.no_organizers_content_updates else: unsubscribed = recipient.no_participants_content_updates if instance.author != profile and not unsubscribed: profiles.append(profile) send_notifications(profiles, subject_template, body_template, context)
def add_user_to_cohort(cohort_uri, user_uri, role, notify_organizers=False): cohort_db = _get_cohort_db(cohort_uri) username = user_uri.strip("/").split("/")[-1] if not UserProfile.objects.filter(username=username).exists(): raise ResourceNotFoundException("User does not exist") if db.CohortSignup.objects.filter(cohort=cohort_db, user_uri=user_uri, leave_date__isnull=True).exists(): return None signup_db = db.CohortSignup(cohort=cohort_db, user_uri=user_uri, role=role) signup_db.save() if notify_organizers: cohort = get_cohort(cohort_uri) course = get_course(cohort["course_uri"]) organizers = UserProfile.objects.filter(username__in=cohort["organizers"]) context = {"course": course, "new_user": username} subject_template = "courses/emails/course_join_subject.txt" body_template = "courses/emails/course_join.txt" notification_model.send_notifications(organizers, subject_template, body_template, context) signup = {"cohort_uri": cohort_uri, "user_uri": user_uri, "role": role} return signup
def email_confirmation_code(self, url, new_user=True): """Send a confirmation email to the user after registering.""" subject_template = 'users/emails/registration_confirm_subject.txt' body_template = 'users/emails/registration_confirm.txt' context = {'confirmation_url': url, 'new_user': new_user} send_notifications([self], subject_template, body_template, context)