def flag(request, username, sound_id): sound = get_object_or_404(Sound, id=sound_id, moderation_state="OK", processing_state="OK") if sound.user.username.lower() != username.lower(): raise Http404 user = None email = None if request.user.is_authenticated(): user = request.user email = request.user.email if request.method == "POST": flag_form = FlagForm(request, request.POST) if flag_form.is_valid(): flag = flag_form.save() flag.reporting_user = user flag.sound = sound flag.save() send_mail_template(u"[flag] flagged file", "sounds/email_flag.txt", dict(flag=flag), flag.email) return HttpResponseRedirect(sound.get_absolute_url()) else: if user: flag_form = FlagForm(request, initial=dict(email=email)) else: flag_form = FlagForm(request) return render_to_response('sounds/sound_flag.html', locals(), context_instance=RequestContext(request))
def save(self): new_sources = self.cleaned_data['sources'] old_sources = set(source["id"] for source in self.sound.sources.all().values("id")) try: new_sources.remove( self.sound.id) # stop the universe from collapsing :-D except KeyError: pass for sid in old_sources - new_sources: # in old but not in new try: source = Sound.objects.get(id=sid) self.sound.sources.remove(source) # modify remix_group send_mail_template(u'Sound removed as remix source', 'sounds/email_remix_update.txt', { 'source': source, 'action': 'removed', 'remix': self.sound }, None, source.user.email) except Sound.DoesNotExist: pass except Exception, e: # Report any other type of exception and fail silently print( "Problem removing source from remix or sending mail: %s" % e)
def contact(request): email_sent = False user = None if request.user.is_authenticated(): user = request.user if request.POST: form = ContactForm(request, request.POST) if form.is_valid(): subject = u"[support] " + form.cleaned_data['subject'] email_from = settings.DEFAULT_FROM_EMAIL message = form.cleaned_data['message'] # append some useful admin information to the email: if not user: try: user = User.objects.get(email__iexact=form.cleaned_data['your_email']) except User.DoesNotExist: pass send_mail_template(subject, "support/email_support.txt", locals(), email_from, reply_to=form.cleaned_data['your_email']) email_sent = True else: if user: form = ContactForm(request, initial={"your_email": user.email}) else: form = ContactForm(request) tvars = {'form': form, 'email_sent': email_sent} return render(request, 'support/contact.html', tvars)
def contact(request): email_sent = False user = None if request.user.is_authenticated(): user = request.user if request.POST: form = ContactForm(request, request.POST) if form.is_valid(): subject = u"[support] " + form.cleaned_data['subject'] email_from = form.cleaned_data['your_email'] message = form.cleaned_data['message'] # append some useful admin information to the email: if not user: try: user = User.objects.get(email__iexact=email_from) except User.DoesNotExist: #@UndefinedVariable pass send_mail_template(subject, "support/email_support.txt", locals(), email_from) email_sent = True else: if user: form = ContactForm(request, initial={"your_email": user.email}) else: form = ContactForm(request) return render_to_response('support/contact.html', locals(), context_instance=RequestContext(request))
def flag(request, username, sound_id): sound = get_object_or_404(Sound, user__username__iexact=username, id=sound_id, moderation_state="OK", processing_state="OK") user = None email = None if request.user.is_authenticated(): user = request.user email = request.user.email if request.method == "POST": flag_form = FlagForm(request, request.POST) if flag_form.is_valid(): flag = flag_form.save() flag.reporting_user=user flag.sound = sound flag.save() send_mail_template(u"[flag] flagged file", "sounds/email_flag.txt", dict(flag=flag), flag.email) return HttpResponseRedirect(sound.get_absolute_url()) else: if user: flag_form = FlagForm(request,initial=dict(email=email)) else: flag_form = FlagForm(request) return render_to_response('sounds/sound_flag.html', locals(), context_instance=RequestContext(request))
def sound(request, username, sound_id): try: sound = Sound.objects.select_related("license", "user", "user__profile", "pack", "remix_group").get(id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 user_is_owner = request.user.is_authenticated() and ( sound.user == request.user or request.user.is_superuser or request.user.is_staff or Group.objects.get(name="moderators") in request.user.groups.all() ) # If the user is authenticated and this file is his, don't worry about moderation_state and processing_state if user_is_owner: if sound.moderation_state != "OK": messages.add_message(request, messages.INFO, "Be advised, this file has <b>not been moderated</b> yet.") if sound.processing_state != "OK": messages.add_message(request, messages.INFO, "Be advised, this file has <b>not been processed</b> yet.") else: if sound.moderation_state != "OK" or sound.processing_state != "OK": raise Http404 except Sound.DoesNotExist: # @UndefinedVariable try: DeletedSound.objects.get(sound_id=sound_id) return render_to_response("sounds/deleted_sound.html", {}, context_instance=RequestContext(request)) except DeletedSound.DoesNotExist: raise Http404 tags = sound.tags.select_related("tag__name") if request.method == "POST": form = CommentForm(request, request.POST) if request.user.profile.is_blocked_for_spam_reports(): messages.add_message( request, messages.INFO, "You're not allowed to post the comment because your account has been temporaly blocked after multiple spam reports", ) else: if form.is_valid(): comment_text = form.cleaned_data["comment"] sound.comments.add(Comment(content_object=sound, user=request.user, comment=comment_text)) sound.num_comments = sound.num_comments + 1 sound.save() try: # send the user an email to notify him of the new comment! logger.debug( "Notifying user %s of a new comment by %s" % (sound.user.username, request.user.username) ) send_mail_template( u"You have a new comment.", "sounds/email_new_comment.txt", {"sound": sound, "user": request.user, "comment": comment_text}, None, sound.user.email, ) except Exception, e: # if the email sending fails, ignore... logger.error("Problem sending email to '%s' about new comment: %s" % (request.user.email, e)) return HttpResponseRedirect(sound.get_absolute_url())
def contact(request): email_sent = False user = None if request.user.is_authenticated(): user = request.user if request.POST: form = ContactForm(request.POST) if form.is_valid(): subject = u"[support] " + form.cleaned_data['subject'] email_from = settings.DEFAULT_FROM_EMAIL message = form.cleaned_data['message'] # append some useful admin information to the email: if not user: try: user = User.objects.get( email__iexact=form.cleaned_data['your_email']) except User.DoesNotExist: pass send_mail_template(subject, "support/email_support.txt", locals(), email_from, reply_to=form.cleaned_data['your_email']) email_sent = True else: if user: form = ContactForm(initial={"your_email": user.email}) else: form = ContactForm() tvars = {'form': form, 'email_sent': email_sent} return render(request, 'support/contact.html', tvars)
def notify_by_email(self): """Notify the user of this sound by email that their sound has been chosen as our Sound of the Day. If the email has already been sent, don't send the notification. If the user has disabled the email notifications for this type of message, don't send it. Returns: True if the email was sent False if it was not sent """ audio_logger.info("Notifying user of random sound of the day") if self.email_sent: audio_logger.info("Email was already sent") return False if self.sound.user.profile.email_not_disabled("random_sound"): send_mail_template( u'One of your sounds has been chosen as random sound of the day!', 'sounds/email_random_sound.txt', {'sound': self.sound, 'user': self.sound.user}, None, self.sound.user.email) self.email_sent = True self.save() audio_logger.info("Finished sending mail to user %s of random sound of the day %s" % (self.sound.user, self.sound)) return True
def save(self): new_sources = self.cleaned_data["sources"] old_sources = set(source["id"] for source in self.sound.sources.all().values("id")) try: new_sources.remove(self.sound.id) # stop the universe from collapsing :-D except KeyError: pass for sid in old_sources - new_sources: # in old but not in new try: source = Sound.objects.get(id=sid) self.sound.sources.remove(source) # modify remix_group send_mail_template( u"Sound removed as remix source", "sounds/email_remix_update.txt", {"source": source, "action": "removed", "remix": self.sound}, None, source.user.email, ) except Sound.DoesNotExist: pass except Exception, e: # Report any other type of exception and fail silently print("Problem removing source from remix or sending mail: %s" % e)
def flag_user(request, username=None): if request.POST: flagged_user = User.objects.get(username__iexact=request.POST["username"]) reporting_user = request.user object_id = request.POST["object_id"] if object_id: if request.POST["flag_type"] == "PM": flagged_object = Message.objects.get(id = object_id) elif request.POST["flag_type"] == "FP": flagged_object = Post.objects.get(id = object_id) elif request.POST["flag_type"] == "SC": flagged_object = Comment.objects.get(id = object_id) else: return HttpResponse(json.dumps({"errors":True}), mimetype='application/javascript') else: return HttpResponse(json.dumps({"errors":True}), mimetype='application/javascript') previous_reports_count = UserFlag.objects.filter(user__username=flagged_user.username)\ .values('reporting_user').distinct().count() uflag = UserFlag(user=flagged_user, reporting_user=reporting_user, content_object=flagged_object) uflag.save() reports_count = UserFlag.objects.filter(user__username = flagged_user.username)\ .values('reporting_user').distinct().count() if reports_count != previous_reports_count and \ (reports_count == settings.USERFLAG_THRESHOLD_FOR_NOTIFICATION or reports_count == settings.USERFLAG_THRESHOLD_FOR_AUTOMATIC_BLOCKING): # Get all flagged objects by the user, create links to admin pages and send email flagged_objects = UserFlag.objects.filter(user__username=flagged_user.username) urls = [] added_objects = [] for f_object in flagged_objects: key = str(f_object.content_type) + str(f_object.object_id) if key not in added_objects: added_objects.append(key) try: obj = f_object.content_type.get_object_for_this_type(id=f_object.object_id) url = reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.module_name), args=[obj.id]) urls.append([str(f_object.content_type), request.build_absolute_uri(url)]) except Exception: urls.append([str(f_object.content_type), "url not available"]) user_url = reverse('admin:%s_%s_delete' % (flagged_user._meta.app_label, flagged_user._meta.module_name), args=[flagged_user.id]) user_url = request.build_absolute_uri(user_url) clear_url = reverse("clear-flags-user", args=[flagged_user.username]) clear_url = request.build_absolute_uri(clear_url) if reports_count < settings.USERFLAG_THRESHOLD_FOR_AUTOMATIC_BLOCKING: template_to_use = 'accounts/report_spammer_admins.txt' else: template_to_use = 'accounts/report_blocked_spammer_admins.txt' to_emails = [] for mail in settings.ADMINS: to_emails.append(mail[1]) send_mail_template(u'Spam report for user ' + flagged_user.username, template_to_use, locals(), None, to_emails) return HttpResponse(json.dumps({"errors": None}), mimetype='application/javascript') else: return HttpResponse(json.dumps({"errors": True}), mimetype='application/javascript')
def save(self): #print "before save", ",".join([str(source.id) for source in self.sound.sources.all()]) new_sources = self.cleaned_data['sources'] old_sources = set(source["id"] for source in self.sound.sources.all().values("id")) try: new_sources.remove(self.sound.id) # stop the universe from collapsing :-D except KeyError: pass for id in old_sources - new_sources: # in old but not in new try: source = Sound.objects.get(id=id) self.sound.sources.remove(source) # modify remix_group send_mail_template( u'Sound removed as remix source', 'sounds/email_remix_update.txt', {'source': source, 'action': 'removed', 'remix': self.sound}, None, source.user.email ) except Sound.DoesNotExist: pass except Exception, e: # Report any other type of exception and fail silently print ("Problem removing source from remix or sending mail: %s" \ % e)
def contact(request): email_sent = False user = None if request.user.is_authenticated(): user = request.user if request.POST: form = ContactForm(request, request.POST) if form.is_valid(): subject = u"[support] " + form.cleaned_data['subject'] email_from = settings.DEFAULT_FROM_EMAIL message = form.cleaned_data['message'] # append some useful admin information to the email: if not user: try: user = User.objects.get(email__iexact=email_from) except User.DoesNotExist: #@UndefinedVariable pass send_mail_template(subject, "support/email_support.txt", locals(), email_from, reply_to=form.cleaned_data['your_email']) email_sent = True else: if user: form = ContactForm(request, initial={"your_email": user.email}) else: form = ContactForm(request) return render_to_response('support/contact.html', locals(), context_instance=RequestContext(request))
def send_activation(user): uid_hash = create_hash(user.id) username = user.username tvars = { 'user': user, 'username': username, 'hash': uid_hash } send_mail_template(u'activation link.', 'accounts/email_activation.txt', tvars, None, user.email)
def send_email_to_support(request_email, subject, message, user=None): if user is None: try: user = User.objects.get(email__iexact=request_email) except User.DoesNotExist: pass send_mail_template(u"[support] " + subject, "support/email_support.txt", {'message': message, 'user': user}, settings.DEFAULT_FROM_EMAIL, reply_to=request_email)
def _save_donation(encoded_data, email, amount, currency, transaction_id, source): extra_data = json.loads(base64.b64decode(encoded_data)) campaign = DonationCampaign.objects.get(id=extra_data['campaign_id']) is_anonymous = False user = None user_id = None display_name = None if 'user_id' in extra_data: user = User.objects.get(id=extra_data['user_id']) user_id = user.id email = user.profile.get_email_for_delivery() # Reset the reminder flag to False so that in a year time user is reminded to donate user.profile.donations_reminder_email_sent = False user.profile.save() if 'name' in extra_data: is_anonymous = True display_name = extra_data['name'] donation_data = { 'email': email, 'display_name': display_name, 'amount': amount, 'currency': currency, 'display_amount': extra_data['display_amount'], 'is_anonymous': is_anonymous, 'user': user, 'campaign': campaign, 'source': source } donation, created = Donation.objects.get_or_create( transaction_id=transaction_id, defaults=donation_data) if created: email_to = None if user is not None else email send_mail_template(u'Thanks for your donation!', 'donations/email_donation.txt', { 'user': user, 'amount': amount, 'display_name': display_name }, user_to=user, email_to=email_to) log_data = donation_data log_data.update({'user_id': user_id}) log_data.update({'created': str(donation.created)}) del log_data['user'] # Don't want to serialize user del log_data['campaign'] # Don't want to serialize campaign log_data['amount_float'] = float(log_data['amount']) logger.info('Recevied donation (%s)' % json.dumps(log_data)) return True
def _save_donation(encoded_data, email, amount, currency, transaction_id, source): extra_data = json.loads(base64.b64decode(encoded_data)) campaign = DonationCampaign.objects.get(id=extra_data['campaign_id']) is_anonymous = False user = None user_id = None display_name = None if 'user_id' in extra_data: user = User.objects.get(id=extra_data['user_id']) user_id = user.id email = user.profile.get_email_for_delivery() # Reset the reminder flag to False so that in a year time user is reminded to donate user.profile.donations_reminder_email_sent = False user.profile.save() if 'name' in extra_data: is_anonymous = True display_name = extra_data['name'] donation_data = { 'email': email, 'display_name': display_name, 'amount': amount, 'currency': currency, 'display_amount': extra_data['display_amount'], 'is_anonymous': is_anonymous, 'user': user, 'campaign': campaign, 'source': source } donation, created = Donation.objects.get_or_create(transaction_id=transaction_id, defaults=donation_data) if created: email_to = None if user is not None else email send_mail_template( u'Thanks for your donation!', 'donations/email_donation.txt', { 'user': user, 'amount': amount, 'display_name': display_name }, user_to=user, email_to=email_to) log_data = donation_data log_data.update({'user_id': user_id}) log_data.update({'created': str(donation.created)}) del log_data['user'] # Don't want to serialize user del log_data['campaign'] # Don't want to serialize campaign log_data['amount_float'] = float(log_data['amount']) logger.info('Recevied donation (%s)' % json.dumps(log_data)) return True
def sound(request, username, sound_id): try: sound = Sound.objects.select_related("license", "user", "user__profile", "pack", "remix_group").get(id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 user_is_owner = request.user.is_authenticated() and (sound.user == request.user or request.user.is_superuser \ or request.user.is_staff or Group.objects.get(name='moderators') in request.user.groups.all()) # If the user is authenticated and this file is his, don't worry about moderation_state and processing_state if user_is_owner: if sound.moderation_state != "OK": messages.add_message(request, messages.INFO, 'Be advised, this file has <b>not been moderated</b> yet.') if sound.processing_state != "OK": messages.add_message(request, messages.INFO, 'Be advised, this file has <b>not been processed</b> yet.') else: if sound.moderation_state != 'OK' or sound.processing_state != 'OK': raise Http404 except Sound.DoesNotExist: #@UndefinedVariable try: DeletedSound.objects.get(sound_id=sound_id) return render_to_response('sounds/deleted_sound.html', {}, context_instance=RequestContext(request)) except DeletedSound.DoesNotExist: raise Http404 tags = sound.tags.select_related("tag__name") if request.method == "POST": form = CommentForm(request, request.POST) if request.user.profile.is_blocked_for_spam_reports(): messages.add_message(request, messages.INFO, "You're not allowed to post the comment because your account has been temporaly blocked after multiple spam reports") else: if form.is_valid(): comment_text=form.cleaned_data["comment"] sound.comments.add(Comment(content_object=sound, user=request.user, comment=comment_text)) sound.num_comments = sound.num_comments + 1 sound.save() try: # send the user an email to notify him of the new comment! logger.debug("Notifying user %s of a new comment by %s" % (sound.user.username, request.user.username)) send_mail_template(u'You have a new comment.', 'sounds/email_new_comment.txt', {'sound': sound, 'user': request.user, 'comment': comment_text}, None, sound.user.email) except Exception, e: # if the email sending fails, ignore... logger.error("Problem sending email to '%s' about new comment: %s" \ % (request.user.email, e)) return HttpResponseRedirect(sound.get_absolute_url())
def sound(request, username, sound_id): try: sound = Sound.objects.select_related("license", "user", "user__profile", "pack").get(id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 user_is_owner = request.user.is_authenticated() and \ (sound.user == request.user or request.user.is_superuser or request.user.is_staff or Group.objects.get(name='moderators') in request.user.groups.all()) # If the user is authenticated and this file is his, don't worry about moderation_state and processing_state if user_is_owner: if sound.moderation_state != "OK": messages.add_message(request, messages.INFO, 'Be advised, this file has <b>not been moderated</b> yet.') if sound.processing_state != "OK": messages.add_message(request, messages.INFO, 'Be advised, this file has <b>not been processed</b> yet.') else: if sound.moderation_state != 'OK' or sound.processing_state != 'OK': raise Http404 except Sound.DoesNotExist: if DeletedSound.objects.filter(sound_id=sound_id).exists(): return render(request, 'sounds/deleted_sound.html') else: raise Http404 tags = sound.tags.select_related("tag__name") if request.method == "POST": form = CommentForm(request, request.POST) if request.user.is_authenticated(): if request.user.profile.is_blocked_for_spam_reports(): messages.add_message(request, messages.INFO, "You're not allowed to post the comment because your account " "has been temporaly blocked after multiple spam reports") else: if form.is_valid(): comment_text = form.cleaned_data["comment"] sound.add_comment(Comment(content_object=sound, user=request.user, comment=comment_text)) try: # Send the user an email to notify him of the new comment! logger.debug("Notifying user %s of a new comment by %s" % (sound.user.username, request.user.username)) send_mail_template(u'You have a new comment.', 'sounds/email_new_comment.txt', {'sound': sound, 'user': request.user, 'comment': comment_text}, None, sound.user.email) except Exception, e: # If the email sending fails, ignore... logger.error("Problem sending email to '%s' about new comment: %s" % (request.user.email, e)) return HttpResponseRedirect(sound.get_absolute_url())
def username_reminder(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse("accounts-home")) if request.method == "POST": form = UsernameReminderForm(request.POST) if form.is_valid(): user = form.cleaned_data["user"] send_mail_template(u'username reminder.', 'accounts/email_username_reminder.txt', dict(user=user), None, user.email) return render_to_response('accounts/username_reminder.html', dict(form=form, sent=True), context_instance=RequestContext(request)) else: form = UsernameReminderForm() return render_to_response('accounts/username_reminder.html', dict(form=form, sent=False), context_instance=RequestContext(request))
def username_reminder(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('accounts-home')) if request.method == 'POST': form = UsernameReminderForm(request.POST) if form.is_valid(): user = form.cleaned_data['user'] send_mail_template(u'username reminder.', 'accounts/email_username_reminder.txt', {'user': user}, None, user.email) return render(request, 'accounts/username_reminder.html', {'form': form, 'sent': True}) else: form = UsernameReminderForm() return render(request, 'accounts/username_reminder.html', {'form': form, 'sent': False})
def username_reminder(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse("accounts-home")) if request.method == "POST": form = UsernameReminderForm(request.POST) if form.is_valid(): user = form.cleaned_data["user"] send_mail_template( u"username reminder.", "accounts/email_username_reminder.txt", {"user": user}, None, user.email ) return render(request, "accounts/username_reminder.html", {"form": form, "sent": True}) else: form = UsernameReminderForm() return render(request, "accounts/username_reminder.html", {"form": form, "sent": False})
class RemixForm(forms.Form): sources = forms.CharField(min_length=1, widget=forms.widgets.HiddenInput(), required=False) def __init__(self, sound, *args, **kwargs): self.sound = sound super(RemixForm, self).__init__(*args, **kwargs) def clean_sources(self): sources = re.sub("[^0-9,]", "", self.cleaned_data['sources']) sources = re.sub(",+", ",", sources) sources = re.sub("^,+", "", sources) sources = re.sub(",+$", "", sources) if len(sources) > 0: sources = set([int(source) for source in sources.split(",")]) else: sources = set() return sources def save(self): new_sources = self.cleaned_data['sources'] old_sources = set(source["id"] for source in self.sound.sources.all().values("id")) try: new_sources.remove(self.sound.id) # stop the universe from collapsing :-D except KeyError: pass for sid in old_sources - new_sources: # in old but not in new try: source = Sound.objects.get(id=sid) self.sound.sources.remove(source) # modify remix_group send_mail_template( u'Sound removed as remix source', 'sounds/email_remix_update.txt', {'source': source, 'action': 'removed', 'remix': self.sound}, None, source.user.email ) except Sound.DoesNotExist: pass except Exception, e: # Report any other type of exception and fail silently print ("Problem removing source from remix or sending mail: %s" % e) for sid in new_sources - old_sources: # in new but not in old source = Sound.objects.get(id=sid) self.sound.sources.add(source) try: send_mail_template( u'Sound added as remix source', 'sounds/email_remix_update.txt', {'source': source, 'action': 'added', 'remix': self.sound}, None, source.user.email ) except Exception, e: # Report any exception but fail silently print ("Problem sending mail about source added to remix: %s" % e)
def send_notification_emails(self, notification_type, sender_moderator): # send message to assigned moderator if sender_moderator in [ Ticket.MODERATOR_ONLY, Ticket.USER_AND_MODERATOR ]: if self.assignee: tvars = {'ticket': self, 'user_to': self.assignee} send_mail_template(settings.EMAIL_SUBJECT_MODERATION_HANDLED, notification_type, tvars, user_to=self.assignee) # send message to user if sender_moderator in [Ticket.USER_ONLY, Ticket.USER_AND_MODERATOR]: if self.sender: tvars = {'ticket': self, 'user_to': self.sender} send_mail_template(settings.EMAIL_SUBJECT_MODERATION_HANDLED, notification_type, tvars, user_to=self.sender)
def send_notification_emails(self, notification_type, sender_moderator): # send message to assigned moderator if sender_moderator in [Ticket.MODERATOR_ONLY, Ticket.USER_AND_MODERATOR]: if self.assignee: tvars = {'ticket': self, 'user_to': self.assignee} send_mail_template(u'A freesound moderator handled your upload.', notification_type, tvars, user_to=self.assignee) # send message to user if sender_moderator in [Ticket.USER_ONLY, Ticket.USER_AND_MODERATOR]: if self.sender: tvars = {'ticket': self, 'user_to': self.sender} send_mail_template(u'A freesound moderator handled your upload.', notification_type, tvars, user_to=self.sender)
def save(self): new_sources = self.cleaned_data['sources'] old_sources = set(source["id"] for source in self.sound.sources.all().values("id")) try: new_sources.remove(self.sound.id) # stop the universe from collapsing :-D except KeyError: pass for sid in old_sources - new_sources: # in old but not in new try: source = Sound.objects.get(id=sid) self.sound.sources.remove(source) source.invalidate_template_caches() # modify remix_group send_mail_template( u'Sound removed as remix source', 'sounds/email_remix_update.txt', {'source': source, 'action': 'removed', 'remix': self.sound}, user_to=source.user ) except Sound.DoesNotExist: pass except Exception as e: # Report any other type of exception and fail silently print ("Problem removing source from remix or sending mail: %s" % e) for sid in new_sources - old_sources: # in new but not in old source = Sound.objects.get(id=sid) source.invalidate_template_caches() self.sound.sources.add(source) try: send_mail_template( u'Sound added as remix source', 'sounds/email_remix_update.txt', {'source': source, 'action': 'added', 'remix': self.sound}, user_to=source.user ) except Exception as e: # Report any exception but fail silently print ("Problem sending mail about source added to remix: %s" % e)
def save(self): new_sources = self.cleaned_data['sources'] old_sources = set(source["id"] for source in self.sound.sources.all().values("id")) try: new_sources.remove( self.sound.id) # stop the universe from collapsing :-D except KeyError: pass for sid in old_sources - new_sources: # in old but not in new try: source = Sound.objects.get(id=sid) self.sound.sources.remove(source) source.invalidate_template_caches() except Sound.DoesNotExist: pass except Exception as e: # Report any other type of exception and fail silently print( "Problem removing source from remix or sending mail: %s" % e) for sid in new_sources - old_sources: # in new but not in old source = Sound.objects.get(id=sid) source.invalidate_template_caches() self.sound.sources.add(source) try: send_mail_template(u'Sound added as remix source', 'sounds/email_remix_update.txt', { 'source': source, 'action': 'added', 'remix': self.sound }, user_to=source.user, email_type_preference_check='new_remix') except Exception as e: # Report any exception but fail silently print("Problem sending mail about source added to remix: %s" % e)
def flag(request, username, sound_id): sound = get_object_or_404(Sound, id=sound_id, moderation_state="OK", processing_state="OK") if sound.user.username.lower() != username.lower(): raise Http404 user = None if request.user.is_authenticated: user = request.user if request.method == "POST": flag_form = FlagForm(request.POST) if flag_form.is_valid(): flag = flag_form.save() flag.reporting_user = user flag.sound = sound flag.save() if user: user_email = user.email else: user_email = flag_form.cleaned_data["email"] from_email = settings.DEFAULT_FROM_EMAIL send_mail_template(u"[flag] flagged file", "sounds/email_flag.txt", {"flag": flag}, from_email, reply_to=user_email) return redirect(sound) else: initial = {} if user: initial["email"] = user.email flag_form = FlagForm(initial=initial) tvars = {"sound": sound, "flag_form": flag_form} return render(request, 'sounds/sound_flag.html', tvars)
def send_notification_emails(self, notification_type, sender_moderator): ticket = self send_to = [] #send message to assigned moderator if sender_moderator in [ Ticket.MODERATOR_ONLY, Ticket.USER_AND_MODERATOR ]: if self.assignee: user_to = self.assignee if self.assignee else False send_mail_template( u'A freesound moderator handled your upload.', notification_type, locals(), '*****@*****.**', self.assignee.email) # send message to user if sender_moderator in [Ticket.USER_ONLY, Ticket.USER_AND_MODERATOR]: user_to = self.sender if self.sender else False email_to = user_to.email if user_to else ticket.sender_email if self.sender: send_mail_template( u'A freesound moderator handled your upload.', notification_type, locals(), '*****@*****.**', email_to)
def send_notification_emails(self, notification_type, sender_moderator): ticket = self send_to = [] #send message to assigned moderator if sender_moderator in [Ticket.MODERATOR_ONLY, Ticket.USER_AND_MODERATOR]: if self.assignee: user_to = self.assignee if self.assignee else False send_mail_template(u'A freesound moderator handled your upload.', notification_type, locals(), '*****@*****.**', self.assignee.email) # send message to user if sender_moderator in [Ticket.USER_ONLY, Ticket.USER_AND_MODERATOR]: user_to = self.sender if self.sender else False email_to = user_to.email if user_to else ticket.sender_email if self.sender: send_mail_template(u'A freesound moderator handled your upload.', notification_type, locals(), '*****@*****.**', email_to)
def flag(request, username, sound_id): sound = get_object_or_404(Sound, id=sound_id, moderation_state="OK", processing_state="OK") if sound.user.username.lower() != username.lower(): raise Http404 user = None if request.user.is_authenticated(): user = request.user if request.method == "POST": flag_form = FlagForm(request.POST) if flag_form.is_valid(): flag = flag_form.save() flag.reporting_user = user flag.sound = sound flag.save() if user: user_email = user.email else: user_email = flag_form.cleaned_data["email"] from_email = settings.DEFAULT_FROM_EMAIL send_mail_template(u"[flag] flagged file", "sounds/email_flag.txt", {"flag": flag}, from_email, reply_to=user_email) return redirect(sound) else: initial = {} if user: initial["email"] = user.email flag_form = FlagForm(initial=initial) tvars = {"sound": sound, "flag_form": flag_form} return render(request, 'sounds/sound_flag.html', tvars)
def sound(request, username, sound_id): try: sound = Sound.objects.select_related("license", "user", "user__profile", "pack").get(id=sound_id) if sound.user.username.lower() != username.lower(): raise Http404 user_is_owner = request.user.is_authenticated and \ (sound.user == request.user or request.user.is_superuser or request.user.is_staff or Group.objects.get(name='moderators') in request.user.groups.all()) # If the user is authenticated and this file is his, don't worry about moderation_state and processing_state if user_is_owner: if sound.moderation_state != "OK": messages.add_message( request, messages.INFO, 'Be advised, this file has <b>not been moderated</b> yet.') if sound.processing_state != "OK": messages.add_message( request, messages.INFO, 'Be advised, this file has <b>not been processed</b> yet.') else: if sound.moderation_state != 'OK' or sound.processing_state != 'OK': raise Http404 except Sound.DoesNotExist: if DeletedSound.objects.filter(sound_id=sound_id).exists(): return render(request, 'sounds/deleted_sound.html') else: raise Http404 if request.method == "POST": form = CommentForm(request, request.POST) if request.user.is_authenticated: if request.user.profile.is_blocked_for_spam_reports(): messages.add_message( request, messages.INFO, "You're not allowed to post the comment because your account " "has been temporaly blocked after multiple spam reports") else: if form.is_valid(): comment_text = form.cleaned_data["comment"] sound.add_comment(request.user, comment_text) try: if request.user.profile.email_not_disabled( "new_comment"): # Send the user an email to notify him of the new comment! logger.debug( "Notifying user %s of a new comment by %s" % (sound.user.username, request.user.username)) send_mail_template( u'You have a new comment.', 'sounds/email_new_comment.txt', { 'sound': sound, 'user': request.user, 'comment': comment_text }, None, sound.user.email) except Exception as e: # If the email sending fails, ignore... logger.error( "Problem sending email to '%s' about new comment: %s" % (request.user.email, e)) return HttpResponseRedirect(sound.get_absolute_url()) else: form = CommentForm(request) qs = Comment.objects.select_related("user", "user__profile")\ .filter(sound_id=sound_id) display_random_link = request.GET.get('random_browsing') is_following = False if request.user.is_authenticated: users_following = follow_utils.get_users_following(request.user) if sound.user in users_following: is_following = True is_explicit = sound.is_explicit and (not request.user.is_authenticated \ or not request.user.profile.is_adult) tvars = { 'sound': sound, 'username': username, 'form': form, 'display_random_link': display_random_link, 'is_following': is_following, 'is_explicit': is_explicit, 'sizes': settings.IFRAME_PLAYER_SIZE, } tvars.update(paginate(request, qs, settings.SOUND_COMMENTS_PER_PAGE)) return render(request, 'sounds/sound.html', tvars)
def new_message(request, username=None, message_id=None): if request.method == 'POST': if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha(request.POST) else: form = MessageReplyForm(request.POST) if request.user.profile.is_blocked_for_spam_reports(): messages.add_message( request, messages.INFO, "You're not allowed to send the message because your account has been temporaly blocked after multiple spam reports" ) else: if form.is_valid(): user_from = request.user user_to = form.cleaned_data["to"] subject = form.cleaned_data["subject"] body = MessageBody.objects.create( body=form.cleaned_data["body"]) Message.objects.create(user_from=user_from, user_to=user_to, subject=subject, body=body, is_sent=True, is_archived=False, is_read=False) Message.objects.create(user_from=user_from, user_to=user_to, subject=subject, body=body, is_sent=False, is_archived=False, is_read=False) invalidate_template_cache("user_header", user_to.id) try: # send the user an email to notify him of the sent message! send_mail_template(u'you have a private message.', 'messages/email_new_message.txt', locals(), None, user_to.email) except: # if the email sending fails, ignore... pass return HttpResponseRedirect(reverse("messages")) else: if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha() else: form = MessageReplyForm() if message_id: try: message = Message.objects.get(id=message_id) if message.user_from != request.user and message.user_to != request.user: raise Http404 body = message.body.body.replace("\r\n", "\n").replace("\r", "\n") body = ''.join(BeautifulSoup(body).findAll(text=True)) body = "\n".join([(">" if line.startswith(">") else "> ") + "\n> ".join(wrap(line.strip(), 60)) for line in body.split("\n")]) body = "> --- " + message.user_from.username + " wrote:\n>\n" + body subject = "re: " + message.subject to = message.user_from.username if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha( initial=dict(to=to, subject=subject, body=body)) else: form = MessageReplyForm( initial=dict(to=to, subject=subject, body=body)) except Message.DoesNotExist: pass elif username: if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha(initial=dict(to=username)) else: form = MessageReplyForm(initial=dict(to=username)) return render_to_response('messages/new.html', locals(), context_instance=RequestContext(request))
def handle(self, **options): logger.info("Sending donation emails") donation_settings, _ = DonationsEmailSettings.objects.get_or_create() if not donation_settings.enabled: return # 0) Define some variables and do some common queries that will be reused later donation_timespan = datetime.datetime.now()-datetime.timedelta( # donation_timestamp is today - X days (12 mo) days=donation_settings.minimum_days_since_last_donation) email_timespan = datetime.datetime.now() - datetime.timedelta( # email_timestap is today - Y days (3 mo) days=donation_settings.minimum_days_since_last_donation_email) user_received_donation_email_within_email_timespan = User.objects.filter( profile__last_donation_email_sent__gt=email_timespan).values_list('id') if donation_settings.never_send_email_to_uploaders: uploaders = User.objects.filter(profile__num_sounds__gt=0).values_list('id') else: uploaders = [] donors_within_donation_timespan = Donation.objects.filter(user__isnull=False, created__gt=donation_timespan)\ .values_list('user_id', flat=True) # 1) Check users that donated in the past # If it's been X days since last donation, send a reminder (typically X=365 days) # users_to_notify -> All users that: # - Made a donation before 'donation_timespan' (12 mo) # - Have not made a donation after 'donation_timespan' (12 mo) # - Have not received any email regarding donations during 'email_timespan' (3 mo) # - Users that have donations_reminder_email_sent set to False (they have not been sent any # reminder in the past) users_to_notify = User.objects.filter( donation__created__lte=donation_timespan, profile__donations_reminder_email_sent=False)\ .exclude(id__in=user_received_donation_email_within_email_timespan)\ .exclude(id__in=uploaders)\ .exclude(id__in=donors_within_donation_timespan) for user in users_to_notify.all(): send_mail_template( u'Thanks for contributing to Freesound', 'donations/email_donation_reminder.txt', { 'user': user, }, user_to=user) user.profile.last_donation_email_sent = datetime.datetime.now() user.profile.donations_reminder_email_sent = True user.profile.save() logger.info("Sent donation email (%s)" % json.dumps( {'user_id': user.id, 'donation_email_type': 'reminder'})) # 2) Send email to users that download a lot of sounds without donating # potential_users -> All users that: # - Downloaded more than M sounds during 'email_timespan' (3 months) # - Have not donated during 'donation_timespan' (12 months) # - Have not received any email regarding donations during 'email_timespan' (3 months) potential_users_sound = Download.objects.filter(created__gte=email_timespan)\ .exclude(user_id__in=user_received_donation_email_within_email_timespan)\ .exclude(user_id__in=donors_within_donation_timespan) \ .exclude(user_id__in=uploaders) \ .values('user_id').annotate(num_download=Count('user_id')).order_by('num_download') potential_users_pack = PackDownload.objects.filter(created__gte=email_timespan)\ .exclude(user_id__in=user_received_donation_email_within_email_timespan)\ .exclude(user_id__in=donors_within_donation_timespan) \ .exclude(user_id__in=uploaders) \ .values('user_id').annotate(num_download=Count('user_id')).order_by('num_download') # Merge downloads from Download and PackDownload tables potential_users = {} for x in potential_users_sound.union(potential_users_pack): potential_users[str(x['user_id'])] = potential_users.get(str(x['user_id']), 0) + x['num_download'] for user_id in potential_users.keys(): if potential_users[user_id] > donation_settings.downloads_in_period: user = User.objects.get(id=user_id) # Check if user downloaded more than M sounds or packs during the relevant period # relevant period is time since last donation + donation_timespan or email_timespan (3 mo) # (the take the closer one) send_email = False last_donation = Donation.objects.filter(user=user, created__gt=donation_timespan).order_by('-created') if last_donation.count() == 0: send_email = True else: relevant_period = max( last_donation.created + datetime.timedelta( days=donation_settings.minimum_days_since_last_donation), email_timespan ) user_sound_downloads = Download.objects.filter(created__gte=relevant_period, user=user).count() user_pack_downloads = PackDownload.objects.filter(created__gte=relevant_period, user=user).count() user_downloads = user_sound_downloads + user_pack_downloads if user_downloads > donation_settings.downloads_in_period: send_email = True if send_email: res = send_mail_template( u'Have you considered making a donation?', 'donations/email_donation_request.txt', { 'user': user, }, user_to=user) if res: user.profile.last_donation_email_sent = datetime.datetime.now() user.profile.save() logger.info("Sent donation email (%s)" % json.dumps( {'user_id': user.id, 'donation_email_type': 'request'})) else: logger.info("Didn't send donation email due to email address being invalid (%s)" % json.dumps( {'user_id': user.id, 'donation_email_type': 'request'})) logger.info("Finished sending donation emails")
def reply(request, forum_name_slug, thread_id, post_id=None): forum = get_object_or_404(Forum, name_slug=forum_name_slug) thread = get_object_or_404(Thread, id=thread_id, forum=forum, first_post__moderation_state="OK") if post_id: post = get_object_or_404(Post, id=post_id, thread__id=thread_id, thread__forum__name_slug=forum_name_slug) quote = loader.render_to_string('forum/quote_style.html', {'post': post}) else: post = None quote = "" latest_posts = Post.objects.select_related('author', 'author__profile', 'thread', 'thread__forum')\ .order_by('-created').filter(thread=thread, moderation_state="OK")[0:15] user_can_post_in_forum = request.user.profile.can_post_in_forum() user_is_blocked_for_spam_reports = request.user.profile.is_blocked_for_spam_reports() if request.method == 'POST': form = PostReplyForm(request, quote, request.POST) if user_can_post_in_forum[0] and not user_is_blocked_for_spam_reports: if form.is_valid(): may_be_spam = text_may_be_spam(form.cleaned_data.get("body", '')) or \ text_may_be_spam(form.cleaned_data.get("title", '')) if not request.user.posts.filter(moderation_state="OK").count() and may_be_spam: post = Post.objects.create( author=request.user, body=form.cleaned_data["body"], thread=thread, moderation_state="NM") # DO NOT add the post to solr, only do it when it is moderated set_to_moderation = True else: post = Post.objects.create(author=request.user, body=form.cleaned_data["body"], thread=thread) add_post_to_solr(post) set_to_moderation = False if form.cleaned_data["subscribe"]: subscription, created = Subscription.objects.get_or_create(thread=thread, subscriber=request.user) if not subscription.is_active: subscription.is_active = True subscription.save() # figure out if there are active subscriptions in this thread if not set_to_moderation: users_to_notify = [] for subscription in Subscription.objects\ .filter(thread=thread, is_active=True).exclude(subscriber=request.user): users_to_notify.append(subscription.subscriber) subscription.is_active = False subscription.save() if users_to_notify and post.thread.get_status_display() != u'Sunk': send_mail_template( u"topic reply notification - " + thread.title, "forum/email_new_post_notification.txt", dict(post=post, thread=thread, forum=forum), user_to=users_to_notify ) if not set_to_moderation: return HttpResponseRedirect(post.get_absolute_url()) else: messages.add_message(request, messages.INFO, "Your post won't be shown until it is manually " "approved by moderators") return HttpResponseRedirect(post.thread.get_absolute_url()) else: if quote: form = PostReplyForm(request, quote, {'body': quote}) else: form = PostReplyForm(request, quote) if not user_can_post_in_forum[0]: messages.add_message(request, messages.INFO, user_can_post_in_forum[1]) if user_is_blocked_for_spam_reports: messages.add_message(request, messages.INFO, "You're not allowed to post in the forums because your account " "has been temporaly blocked after multiple spam reports") tvars = {'forum': forum, 'thread': thread, 'form': form, 'latest_posts': latest_posts} return render(request, 'forum/reply.html', tvars)
def handle(self, **options): logger.info("Sending donation emails") donation_settings, _ = DonationsEmailSettings.objects.get_or_create() if not donation_settings.enabled: return # 0) Define some variables and do some common queries that will be reused later donation_timespan = datetime.datetime.now( ) - datetime.timedelta( # donation_timestamp is today - X days (12 mo) days=donation_settings.minimum_days_since_last_donation) email_timespan = datetime.datetime.now( ) - datetime.timedelta( # email_timestap is today - Y days (3 mo) days=donation_settings.minimum_days_since_last_donation_email) user_received_donation_email_within_email_timespan = User.objects.filter( profile__last_donation_email_sent__gt=email_timespan).values_list( 'id') if donation_settings.never_send_email_to_uploaders: uploaders = User.objects.filter( profile__num_sounds__gt=0).values_list('id') else: uploaders = [] donors_within_donation_timespan = Donation.objects.filter(user__isnull=False, created__gt=donation_timespan)\ .values_list('user_id', flat=True) # 1) Check users that donated in the past # If it's been X days since last donation, send a reminder (typically X=365 days) # users_to_notify -> All users that: # - Made a donation before 'donation_timespan' (12 mo) # - Have not made a donation after 'donation_timespan' (12 mo) # - Have not received any email regarding donations during 'email_timespan' (3 mo) # - Users that have donations_reminder_email_sent set to False (they have not been sent any # reminder in the past) users_to_notify = User.objects.filter( donation__created__lte=donation_timespan, profile__donations_reminder_email_sent=False)\ .exclude(id__in=user_received_donation_email_within_email_timespan)\ .exclude(id__in=uploaders)\ .exclude(id__in=donors_within_donation_timespan) for user in users_to_notify.all(): email_sent_successfully = send_mail_template( u'Thanks for contributing to Freesound', 'donations/email_donation_reminder.txt', {'user': user}, user_to=user, email_type_preference_check='donation_request') if email_sent_successfully: user.profile.last_donation_email_sent = datetime.datetime.now() user.profile.donations_reminder_email_sent = True user.profile.save() logger.info("Sent donation email (%s)" % json.dumps({ 'user_id': user.id, 'donation_email_type': 'reminder' })) else: logger.info( "Didn't send donation email due to email address being invalid or donation" "emails preference disabled (%s)" % json.dumps({ 'user_id': user.id, 'donation_email_type': 'reminder' })) # 2) Send email to users that download a lot of sounds without donating # potential_users -> All users that: # - Downloaded more than M sounds during 'email_timespan' (3 months) # - Have not donated during 'donation_timespan' (12 months) # - Have not received any email regarding donations during 'email_timespan' (3 months) potential_users_sound = Download.objects.filter(created__gte=email_timespan)\ .exclude(user_id__in=user_received_donation_email_within_email_timespan)\ .exclude(user_id__in=donors_within_donation_timespan) \ .exclude(user_id__in=uploaders) \ .values('user_id').annotate(num_download=Count('user_id')).order_by('num_download') potential_users_pack = PackDownload.objects.filter(created__gte=email_timespan)\ .exclude(user_id__in=user_received_donation_email_within_email_timespan)\ .exclude(user_id__in=donors_within_donation_timespan) \ .exclude(user_id__in=uploaders) \ .values('user_id').annotate(num_download=Count('user_id')).order_by('num_download') # Merge downloads from Download and PackDownload tables potential_users = {} for x in potential_users_sound.union(potential_users_pack): potential_users[str(x['user_id'])] = potential_users.get( str(x['user_id']), 0) + x['num_download'] for user_id in potential_users.keys(): if potential_users[user_id] > donation_settings.downloads_in_period: user = User.objects.get(id=user_id) # Check if user downloaded more than M sounds or packs during the relevant period # relevant period is time since last donation + donation_timespan or email_timespan (3 mo) # (the take the closer one) send_email = False last_donation = Donation.objects.filter( user=user, created__gt=donation_timespan).order_by('-created') if last_donation.count() == 0: send_email = True else: relevant_period = max( last_donation.created + datetime.timedelta(days=donation_settings. minimum_days_since_last_donation), email_timespan) user_sound_downloads = Download.objects.filter( created__gte=relevant_period, user=user).count() user_pack_downloads = PackDownload.objects.filter( created__gte=relevant_period, user=user).count() user_downloads = user_sound_downloads + user_pack_downloads if user_downloads > donation_settings.downloads_in_period: send_email = True if send_email: email_sent_successfully = send_mail_template( u'Have you considered making a donation?', 'donations/email_donation_request.txt', { 'user': user, }, user_to=user, email_type_preference_check='donation_request') if email_sent_successfully: user.profile.last_donation_email_sent = datetime.datetime.now( ) user.profile.save() logger.info("Sent donation email (%s)" % json.dumps({ 'user_id': user.id, 'donation_email_type': 'request' })) else: logger.info( "Didn't send donation email due to email address being invalid or donation" "emails preference disabled (%s)" % json.dumps({ 'user_id': user.id, 'donation_email_type': 'request' })) logger.info("Finished sending donation emails")
def send_activation(user): uid_hash = create_hash(user.id) username = user.username tvars = {"user": user, "username": username, "hash": uid_hash} send_mail_template(u"activation link.", "accounts/email_activation.txt", tvars, None, user.email)
def reply(request, forum_name_slug, thread_id, post_id=None): forum = get_object_or_404(Forum, name_slug=forum_name_slug) thread = get_object_or_404(Thread, id=thread_id, forum=forum, first_post__moderation_state="OK") is_survey = False if thread.title == "Freesound Survey": is_survey = True survey_text = """ 1) What do you use Freesound for? (what are your specific interests? what do you do with Freesound samples? ...) 2) Do you perceive some shared goals in Freesounds user community? If so, which ones? (is there a sense of community? and of long-term goals to be achieved? ...) 3) What kinds of sounds are you most interested in? (do you upload and/or download specific types of sounds? which ones? ...) 4) What makes Freesound different from other sound sharing sites? (you can compare with sites like Soundcloud, Looperman, CCMixter or others) """ if post_id: post = get_object_or_404(Post, id=post_id, thread__id=thread_id, thread__forum__name_slug=forum_name_slug) quote = loader.render_to_string('forum/quote_style.html', {'post':post}) else: post = None quote = "" latest_posts = Post.objects.select_related('author', 'author__profile', 'thread', 'thread__forum').order_by('-created').filter(thread=thread, moderation_state="OK")[0:15] user_can_post_in_forum = request.user.profile.can_post_in_forum() user_is_blocked_for_spam_reports = request.user.profile.is_blocked_for_spam_reports() if request.method == 'POST': form = PostReplyForm(request, quote, request.POST) if user_can_post_in_forum[0] and not user_is_blocked_for_spam_reports: if form.is_valid(): mayBeSpam = text_may_be_spam(form.cleaned_data["body"]) if not request.user.post_set.filter(moderation_state="OK").count() and mayBeSpam: # first post has urls post = Post.objects.create(author=request.user, body=form.cleaned_data["body"], thread=thread, moderation_state="NM") # DO NOT add the post to solr, only do it when it is moderated set_to_moderation = True else: post = Post.objects.create(author=request.user, body=form.cleaned_data["body"], thread=thread) add_post_to_solr(post) set_to_moderation = False if form.cleaned_data["subscribe"]: subscription, created = Subscription.objects.get_or_create(thread=thread, subscriber=request.user) if not subscription.is_active: subscription.is_active = True subscription.save() # figure out if there are active subscriptions in this thread if not set_to_moderation: emails_to_notify = [] for subscription in Subscription.objects.filter(thread=thread, is_active=True).exclude(subscriber=request.user): emails_to_notify.append(subscription.subscriber.email) subscription.is_active = False subscription.save() if emails_to_notify: send_mail_template(u"topic reply notification - " + thread.title, "forum/email_new_post_notification.txt", dict(post=post, thread=thread, forum=forum), email_from=None, email_to=emails_to_notify) if not set_to_moderation: return HttpResponseRedirect(post.get_absolute_url()) else: messages.add_message(request, messages.INFO, "Your post won't be shown until it is manually approved by moderators") return HttpResponseRedirect(post.thread.get_absolute_url()) else: if quote: form = PostReplyForm(request, quote, {'body':quote}) else: if is_survey: form = PostReplyForm(request, quote, {'body':survey_text}) else: form = PostReplyForm(request, quote) if not user_can_post_in_forum[0]: messages.add_message(request, messages.INFO, user_can_post_in_forum[1]) if user_is_blocked_for_spam_reports: messages.add_message(request, messages.INFO, "You're not allowed to post in the forums because your account has been temporaly blocked after multiple spam reports") return render_to_response('forum/reply.html', locals(), context_instance=RequestContext(request))
def new_message(request, username=None, message_id=None): if request.method == 'POST': if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha(request.POST) else: form = MessageReplyForm(request.POST) if request.user.profile.is_blocked_for_spam_reports(): messages.add_message(request, messages.INFO, "You're not allowed to send the message because your account has been temporaly blocked after multiple spam reports") else: if form.is_valid(): user_from = request.user user_to = form.cleaned_data["to"] subject = form.cleaned_data["subject"] body = MessageBody.objects.create(body=form.cleaned_data["body"]) Message.objects.create(user_from=user_from, user_to=user_to, subject=subject, body=body, is_sent=True, is_archived=False, is_read=False) Message.objects.create(user_from=user_from, user_to=user_to, subject=subject, body=body, is_sent=False, is_archived=False, is_read=False) invalidate_template_cache("user_header", user_to.id) try: # send the user an email to notify him of the sent message! send_mail_template(u'you have a private message.', 'messages/email_new_message.txt', locals(), None, user_to.email) except: # if the email sending fails, ignore... pass return HttpResponseRedirect(reverse("messages")) else: if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha() else: form = MessageReplyForm() if message_id: try: message = Message.objects.get(id=message_id) if message.user_from != request.user and message.user_to != request.user: raise Http404 body = message.body.body.replace("\r\n", "\n").replace("\r", "\n") body = ''.join(BeautifulSoup(body).findAll(text=True)) body = "\n".join([(">" if line.startswith(">") else "> ") + "\n> ".join(wrap(line.strip(),60)) for line in body.split("\n")]) body = "> --- " + message.user_from.username + " wrote:\n>\n" + body subject = "re: " + message.subject to = message.user_from.username if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha(initial=dict(to=to, subject=subject, body=body)) else: form = MessageReplyForm(initial=dict(to=to, subject=subject, body=body)) except Message.DoesNotExist: pass elif username: if request.user.profile.num_sounds: form = MessageReplyFormNoCaptcha(initial=dict(to=username)) else: form = MessageReplyForm(initial=dict(to=username)) return render_to_response('messages/new.html', locals(), context_instance=RequestContext(request))
def reply(request, forum_name_slug, thread_id, post_id=None): forum = get_object_or_404(Forum, name_slug=forum_name_slug) thread = get_object_or_404(Thread, id=thread_id, forum=forum, first_post__moderation_state="OK") is_survey = False if thread.title == "Freesound Survey": is_survey = True survey_text = """ 1) What do you use Freesound for? (what are your specific interests? what do you do with Freesound samples? ...) 2) Do you perceive some shared goals in Freesounds user community? If so, which ones? (is there a sense of community? and of long-term goals to be achieved? ...) 3) What kinds of sounds are you most interested in? (do you upload and/or download specific types of sounds? which ones? ...) 4) What makes Freesound different from other sound sharing sites? (you can compare with sites like Soundcloud, Looperman, CCMixter or others) """ if post_id: post = get_object_or_404(Post, id=post_id, thread__id=thread_id, thread__forum__name_slug=forum_name_slug) quote = loader.render_to_string('forum/quote_style.html', {'post': post}) else: post = None quote = "" latest_posts = Post.objects.select_related( 'author', 'author__profile', 'thread', 'thread__forum').order_by('-created').filter( thread=thread, moderation_state="OK")[0:15] user_can_post_in_forum = request.user.profile.can_post_in_forum() user_is_blocked_for_spam_reports = request.user.profile.is_blocked_for_spam_reports( ) if request.method == 'POST': form = PostReplyForm(request, quote, request.POST) if user_can_post_in_forum[0] and not user_is_blocked_for_spam_reports: if form.is_valid(): mayBeSpam = text_may_be_spam(form.cleaned_data["body"]) if not request.user.post_set.filter( moderation_state="OK").count( ) and mayBeSpam: # first post has urls post = Post.objects.create(author=request.user, body=form.cleaned_data["body"], thread=thread, moderation_state="NM") # DO NOT add the post to solr, only do it when it is moderated set_to_moderation = True else: post = Post.objects.create(author=request.user, body=form.cleaned_data["body"], thread=thread) add_post_to_solr(post) set_to_moderation = False if form.cleaned_data["subscribe"]: subscription, created = Subscription.objects.get_or_create( thread=thread, subscriber=request.user) if not subscription.is_active: subscription.is_active = True subscription.save() # figure out if there are active subscriptions in this thread if not set_to_moderation: emails_to_notify = [] for subscription in Subscription.objects.filter( thread=thread, is_active=True).exclude(subscriber=request.user): emails_to_notify.append(subscription.subscriber.email) subscription.is_active = False subscription.save() if emails_to_notify: send_mail_template( u"topic reply notification - " + thread.title, "forum/email_new_post_notification.txt", dict(post=post, thread=thread, forum=forum), email_from=None, email_to=emails_to_notify) if not set_to_moderation: return HttpResponseRedirect(post.get_absolute_url()) else: messages.add_message( request, messages.INFO, "Your post won't be shown until it is manually approved by moderators" ) return HttpResponseRedirect(post.thread.get_absolute_url()) else: if quote: form = PostReplyForm(request, quote, {'body': quote}) else: if is_survey: form = PostReplyForm(request, quote, {'body': survey_text}) else: form = PostReplyForm(request, quote) if not user_can_post_in_forum[0]: messages.add_message(request, messages.INFO, user_can_post_in_forum[1]) if user_is_blocked_for_spam_reports: messages.add_message( request, messages.INFO, "You're not allowed to post in the forums because your account has been temporaly blocked after multiple spam reports" ) return render_to_response('forum/reply.html', locals(), context_instance=RequestContext(request))
def sound(request, username, sound_id): try: sound = Sound.objects.prefetch_related("tags__tag")\ .select_related("license", "user", "user__profile", "pack")\ .get(id=sound_id, user__username=username) user_is_owner = request.user.is_authenticated and \ (sound.user == request.user or request.user.is_superuser or request.user.is_staff or Group.objects.get(name='moderators') in request.user.groups.all()) # If the user is authenticated and this file is his, don't worry about moderation_state and processing_state if user_is_owner: if sound.moderation_state != "OK": messages.add_message( request, messages.INFO, 'Be advised, this file has <b>not been moderated</b> yet.') if sound.processing_state != "OK": messages.add_message( request, messages.INFO, 'Be advised, this file has <b>not been processed</b> yet.') else: if sound.moderation_state != 'OK' or sound.processing_state != 'OK': raise Http404 except Sound.DoesNotExist: if DeletedSound.objects.filter(sound_id=sound_id).exists(): return render(request, 'sounds/deleted_sound.html') else: raise Http404 if request.method == "POST": form = CommentForm(request, request.POST) if request.user.is_authenticated: if request.user.profile.is_blocked_for_spam_reports(): messages.add_message( request, messages.INFO, "You're not allowed to post the comment because your " "account has been temporaly blocked after multiple spam " "reports") else: if form.is_valid(): comment_text = form.cleaned_data["comment"] sound.add_comment(request.user, comment_text) sound.invalidate_template_caches() send_mail_template( u'You have a new comment.', 'sounds/email_new_comment.txt', { 'sound': sound, 'user': request.user, 'comment': comment_text }, user_to=sound.user, email_type_preference_check="new_comment") return HttpResponseRedirect(sound.get_absolute_url()) else: form = CommentForm(request) qs = Comment.objects.select_related("user", "user__profile")\ .filter(sound_id=sound_id) display_random_link = request.GET.get('random_browsing', False) is_following = False if request.user.is_authenticated: users_following = follow_utils.get_users_following(request.user) if sound.user in users_following: is_following = True is_explicit = sound.is_explicit and (not request.user.is_authenticated or not request.user.profile.is_adult) tvars = { 'sound': sound, 'username': username, 'form': form, 'display_random_link': display_random_link, 'is_following': is_following, 'is_explicit': is_explicit, # if the sound should be shown blurred, already checks for adult profile 'sizes': settings.IFRAME_PLAYER_SIZE, } tvars.update(paginate(request, qs, settings.SOUND_COMMENTS_PER_PAGE)) return render(request, 'sounds/sound.html', tvars)
def send_activation2(user): hash = create_hash(user.id) username = user.username send_mail_template(u'activation link.', 'accounts/email_activation2.txt', locals(), None, user.email)
def send_activation(user): encrypted_user_id = encrypt(str(user.id)) username = user.username send_mail_template(u'activation link.', 'accounts/email_activation.txt', locals(), None, user.email)
def reply(request, forum_name_slug, thread_id, post_id=None): forum = get_object_or_404(Forum, name_slug=forum_name_slug) thread = get_object_or_404(Thread, id=thread_id, forum=forum, first_post__moderation_state="OK") if post_id: post = get_object_or_404(Post, id=post_id, thread__id=thread_id, thread__forum__name_slug=forum_name_slug) quote = loader.render_to_string('forum/quote_style.html', {'post': post}) else: post = None quote = "" latest_posts = Post.objects.select_related('author', 'author__profile', 'thread', 'thread__forum')\ .order_by('-created').filter(thread=thread, moderation_state="OK")[0:15] user_can_post_in_forum, user_can_post_message = request.user.profile.can_post_in_forum( ) user_is_blocked_for_spam_reports = request.user.profile.is_blocked_for_spam_reports( ) if request.method == 'POST': form = PostReplyForm(request, quote, request.POST) if user_can_post_in_forum and not user_is_blocked_for_spam_reports: if form.is_valid(): may_be_spam = text_may_be_spam(form.cleaned_data.get("body", '')) or \ text_may_be_spam(form.cleaned_data.get("title", '')) if not request.user.posts.filter( moderation_state="OK").count() and may_be_spam: post = Post.objects.create(author=request.user, body=form.cleaned_data["body"], thread=thread, moderation_state="NM") # DO NOT add the post to solr, only do it when it is moderated set_to_moderation = True else: post = Post.objects.create(author=request.user, body=form.cleaned_data["body"], thread=thread) add_post_to_solr(post.id) set_to_moderation = False if form.cleaned_data["subscribe"]: subscription, created = Subscription.objects.get_or_create( thread=thread, subscriber=request.user) if not subscription.is_active: subscription.is_active = True subscription.save() # figure out if there are active subscriptions in this thread if not set_to_moderation: users_to_notify = [] for subscription in Subscription.objects\ .filter(thread=thread, is_active=True).exclude(subscriber=request.user): users_to_notify.append(subscription.subscriber) subscription.is_active = False subscription.save() if users_to_notify and post.thread.get_status_display( ) != u'Sunk': send_mail_template( settings.EMAIL_SUBJECT_TOPIC_REPLY, "forum/email_new_post_notification.txt", { 'post': post, 'thread': thread, 'forum': forum }, extra_subject=thread.title, user_to=users_to_notify, email_type_preference_check="new_post") if not set_to_moderation: return HttpResponseRedirect(post.get_absolute_url()) else: messages.add_message( request, messages.INFO, "Your post won't be shown until it is manually " "approved by moderators") return HttpResponseRedirect(post.thread.get_absolute_url()) else: if quote: form = PostReplyForm(request, quote, {'body': quote}) else: form = PostReplyForm(request, quote) if not user_can_post_in_forum: messages.add_message(request, messages.INFO, user_can_post_message) if user_is_blocked_for_spam_reports: messages.add_message( request, messages.INFO, "You're not allowed to post in the forums because your account " "has been temporaly blocked after multiple spam reports") tvars = { 'forum': forum, 'thread': thread, 'form': form, 'latest_posts': latest_posts } return render(request, 'forum/reply.html', tvars)
def sound(request, username, sound_id): try: sound = Sound.objects.select_related("license", "user", "user__profile", "pack").get(id=sound_id, user__username=username) user_is_owner = request.user.is_authenticated and \ (sound.user == request.user or request.user.is_superuser or request.user.is_staff or Group.objects.get(name='moderators') in request.user.groups.all()) # If the user is authenticated and this file is his, don't worry about moderation_state and processing_state if user_is_owner: if sound.moderation_state != "OK": messages.add_message(request, messages.INFO, 'Be advised, this file has <b>not been moderated</b> yet.') if sound.processing_state != "OK": messages.add_message(request, messages.INFO, 'Be advised, this file has <b>not been processed</b> yet.') else: if sound.moderation_state != 'OK' or sound.processing_state != 'OK': raise Http404 except Sound.DoesNotExist: if DeletedSound.objects.filter(sound_id=sound_id).exists(): return render(request, 'sounds/deleted_sound.html') else: raise Http404 if request.method == "POST": form = CommentForm(request, request.POST) if request.user.is_authenticated: if request.user.profile.is_blocked_for_spam_reports(): messages.add_message(request, messages.INFO, "You're not allowed to post the comment because your account " "has been temporaly blocked after multiple spam reports") else: if form.is_valid(): comment_text = form.cleaned_data["comment"] sound.add_comment(request.user, comment_text) sound.invalidate_template_caches() try: if sound.user.profile.email_not_disabled("new_comment"): # Send the user an email to notify him of the new comment! logger.info("Notifying user %s of a new comment by %s" % (sound.user.username, request.user.username)) send_mail_template(u'You have a new comment.', 'sounds/email_new_comment.txt', {'sound': sound, 'user': request.user, 'comment': comment_text}, user_to=sound.user) except Exception as e: # If the email sending fails, ignore... logger.error("Problem sending email to '%s' about new comment: %s" % (request.user.username, e)) return HttpResponseRedirect(sound.get_absolute_url()) else: form = CommentForm(request) qs = Comment.objects.select_related("user", "user__profile")\ .filter(sound_id=sound_id) display_random_link = request.GET.get('random_browsing', False) is_following = False if request.user.is_authenticated: users_following = follow_utils.get_users_following(request.user) if sound.user in users_following: is_following = True is_explicit = sound.is_explicit and (not request.user.is_authenticated or not request.user.profile.is_adult) tvars = { 'sound': sound, 'username': username, 'form': form, 'display_random_link': display_random_link, 'is_following': is_following, 'is_explicit': is_explicit, # if the sound should be shown blurred, already checks for adult profile 'sizes': settings.IFRAME_PLAYER_SIZE, } tvars.update(paginate(request, qs, settings.SOUND_COMMENTS_PER_PAGE)) return render(request, 'sounds/sound.html', tvars)
def new_message(request, username=None, message_id=None): if request.user.profile.is_trustworthy(): form_class = MessageReplyForm else: form_class = MessageReplyFormWithCaptcha if request.method == 'POST': form = form_class(request.POST) if request.user.profile.is_blocked_for_spam_reports(): messages.add_message( request, messages.INFO, "You're not allowed to send the message because your account " "has been temporaly blocked after multiple spam reports") else: if form.is_valid(): user_from = request.user user_to = form.cleaned_data["to"] subject = form.cleaned_data["subject"] body = MessageBody.objects.create( body=form.cleaned_data["body"]) Message.objects.create(user_from=user_from, user_to=user_to, subject=subject, body=body, is_sent=True, is_archived=False, is_read=False) Message.objects.create(user_from=user_from, user_to=user_to, subject=subject, body=body, is_sent=False, is_archived=False, is_read=False) invalidate_template_cache("user_header", user_to.id) try: # send the user an email to notify him of the sent message! tvars = {'user_to': user_to, 'user_from': user_from} if user_to.profile.email_not_disabled("private_message"): send_mail_template(u'you have a private message.', 'messages/email_new_message.txt', tvars, user_to=user_to) except: # if the email sending fails, ignore... pass return HttpResponseRedirect(reverse("messages")) else: form = form_class(request.POST) if message_id: try: message = Message.objects.get(id=message_id) if message.user_from != request.user and message.user_to != request.user: raise Http404 body = message.body.body.replace("\r\n", "\n").replace("\r", "\n") body = ''.join(BeautifulSoup(body).findAll(text=True)) body = "\n".join([(">" if line.startswith(">") else "> ") + "\n> ".join(wrap(line.strip(), 60)) for line in body.split("\n")]) body = "> --- " + message.user_from.username + " wrote:\n>\n" + body subject = "re: " + message.subject to = message.user_from.username form = form_class(initial={ "to": to, "subject": subject, "body": body }) except Message.DoesNotExist: pass elif username: form = form_class(initial={"to": username}) tvars = {'form': form} return render(request, 'messages/new.html', tvars)