def send_password_reset_mail(self, request, user_id): if not request.user.has_perm('members.change_member'): return HttpResponseForbidden('Not allowed to change user') user = Member.objects.get(pk=user_id) context = { 'email': user.email, 'site': tenant_url(), 'site_name': tenant_url(), 'uid': int_to_base36(user.pk), 'user': user, 'token': default_token_generator.make_token(user), } subject = loader.render_to_string('bb_accounts/password_reset_subject.txt', context) subject = ''.join(subject.splitlines()) send_mail( template_name='bb_accounts/password_reset_email', to=user, subject=subject, **context ) message = _('User {name} will receive an email to reset password.').format(name=user.full_name) self.message_user(request, message) return HttpResponseRedirect(reverse('admin:members_member_change', args=(user.id, )))
def put(self, request, *args, **kwargs): serializer = PasswordResetSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: user = USER_MODEL.objects.get( email__iexact=serializer.validated_data['email']) context = { 'email': user.email, 'site': tenant_url(), 'site_name': tenant_url(), 'uid': int_to_base36(user.pk), 'user': user, 'token': default_token_generator.make_token(user), } with TenantLanguage(user.primary_language): subject = loader.render_to_string( 'bb_accounts/password_reset_subject.txt', context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) send_mail(template_name='bb_accounts/password_reset_email', to=user, subject=subject, **context) except USER_MODEL.DoesNotExist: pass return response.Response({}, status=status.HTTP_200_OK)
def mail_project_complete(project): with TenantLanguage(project.owner.primary_language): subject = _(u"The project '{0}' has been realised").format(project.title) survey_link = Survey.url(project, user_type='initiator') send_mail( template_name="projects/mails/project_complete.mail", subject=subject, to=project.owner, title=project.title, receiver_name=project.owner.short_name, survey_link=mark_safe(survey_link) if survey_link else None, site=tenant_url(), link='/go/projects/{0}'.format(project.slug) ) if project.organization: with TenantLanguage(project.owner.primary_language): subject = _(u"The project '{0}' has been realised").format(project.title) survey_link = Survey.url(project, user_type='organization') send_mail( template_name="projects/mails/organization_project_complete.mail", subject=subject, to=project.organization, title=project.title, receiver_name=project.organization.name, survey_link=mark_safe(survey_link) if survey_link else None, site=tenant_url(), link='/go/projects/{0}'.format(project.slug) )
def mail_project_complete(project): with TenantLanguage(project.owner.primary_language): subject = _(u"The project '{0}' has been realised").format( project.title) survey_link = Survey.url(project, user_type='initiator') send_mail(template_name="projects/mails/project_complete.mail", subject=subject, to=project.owner, title=project.title, receiver_name=project.owner.short_name, survey_link=mark_safe(survey_link) if survey_link else None, site=tenant_url(), link='/go/projects/{0}'.format(project.slug)) if project.organization: with TenantLanguage(project.owner.primary_language): subject = _(u"The project '{0}' has been realised").format( project.title) survey_link = Survey.url(project, user_type='organization') send_mail( template_name="projects/mails/organization_project_complete.mail", subject=subject, to=project.organization, title=project.title, receiver_name=project.organization.name, survey_link=mark_safe(survey_link) if survey_link else None, site=tenant_url(), link='/go/projects/{0}'.format(project.slug))
def put(self, request, *args, **kwargs): serializer = PasswordResetSerializer(data=request.data) serializer.is_valid(raise_exception=True) try: user = USER_MODEL.objects.get(email__iexact=serializer.validated_data['email']) context = { 'email': user.email, 'site': tenant_url(), 'site_name': tenant_url(), 'uid': int_to_base36(user.pk), 'user': user, 'token': default_token_generator.make_token(user), } with TenantLanguage(user.primary_language): subject = loader.render_to_string('bb_accounts/password_reset_subject.txt', context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) send_mail( template_name='bb_accounts/password_reset_email', to=user, subject=subject, **context ) except USER_MODEL.DoesNotExist: pass return response.Response(status=status.HTTP_200_OK)
def send_welcome_mail(user=None): from bluebottle.members.models import MemberPlatformSettings settings = MemberPlatformSettings.objects.get() context = { 'email': user.email, 'site': tenant_url(), 'site_name': tenant_name(), 'user': user, 'first_name': user.first_name, 'contact_email': properties.CONTACT_EMAIL, 'closed_site': settings.closed, 'LANGUAGE_CODE': user.primary_language, } # If there is no password and no remote_id (SSO) then use the # welcome + password template, and then set a random password if not user.password and not user.remote_id: context.update({ 'token': default_token_generator.make_token(user), 'uid': int_to_base36(user.pk), }) msg = AccountActivationMessage(user, context=context) msg.compose_and_send() user.welcome_email_is_sent = True user.save()
def send_welcome_mail(user=None): subject = _("Welcome to %(site_name)s") % {'site_name': tenant_name()} if user and user.primary_language: with TenantLanguage(user.primary_language): subject = _("Welcome to %(site_name)s") % { 'site_name': tenant_name() } data = { 'email': user.email, 'site': tenant_url(), 'site_name': tenant_name(), 'user': user, 'first_name': user.first_name, 'contact_email': properties.CONTACT_EMAIL, 'token': default_token_generator.make_token(user), 'uid': int_to_base36(user.pk), 'LANGUAGE_CODE': user.primary_language, } # If there is no password and no remote_id (SSO) then use the # welcome + password template, and then set a random password if not user.password and not user.remote_id: send_mail(template_name='bb_accounts/activation_email_no_password', subject=subject, to=user, **data) else: send_mail(template_name='bb_accounts/activation_email', subject=subject, to=user, **data)
def _post_to_facebook(instance, tenant=None): """ Post a Wallpost to users Facebook page using Celery """ logger.info("FB post for:") logger.info("{0} with id {1} and tenant {2}".format(instance.__class__, instance.id, tenant.client_name)) if not tenant: return with LocalTenant(tenant, clear_tenant=True): social = instance.author.social_auth.get(provider='facebook') authorization_header = 'Bearer {token}'.format( token=social.extra_data['access_token'] ) graph_url = 'https://graph.facebook.com/v2.4/me/feed' base_url = 'https://{domain}'.format( domain=tenant.domain_url) link = instance.content_object.get_absolute_url() image = None # This code is executed via Celery, we assume the MediaWallpostPhoto # is saved and available on the instance. If the user uploaded # photos with the MediaWallpost we take the first one and include it # in the Facebook post. Otherwise we fallback to the project image. if isinstance(instance, MediaWallpost) and instance.photos.count() > 0: image = urljoin(base_url, get_thumbnail(instance.photos.all()[0].photo, "600x400").url ) else: if hasattr(instance.content_object, 'image') and instance.content_object.image: image = urljoin( base_url, get_thumbnail(instance.content_object.image, "600x400").url ) description = getattr( instance.content_object, 'pitch', instance.content_object.description ) data = { 'link': link, 'name': instance.content_object.title, 'description': description, 'message': instance.text, 'picture': image, 'caption': tenant_url() } # TODO: log failed requests requests.post( graph_url, data=json.dumps(data), headers={ 'Authorization': authorization_header, 'Content-Type': 'application/json'} )
def successful_donation_fundraiser_mail(instance): # should be only when the status is success try: receiver = instance.fundraiser.owner except: # donation it's not coming from a fundraiser return fundraiser_link = '/go/fundraisers/{0}'.format(instance.fundraiser.id) if instance.fundraiser.owner.email: if instance.anonymous: donor_name = _('an anonymous person') elif instance.order.user: if instance.order.user.first_name: donor_name = instance.order.user.first_name else: donor_name = instance.order.user.email else: donor_name = _('a guest') with TenantLanguage(receiver.primary_language): subject = _('You received a new donation') send_mail( template_name='bb_donations/mails/new_oneoff_donation_fundraiser.mail', subject=subject, site=tenant_url(), to=receiver, amount=instance.amount, donor_name=donor_name, link=fundraiser_link, first_name=receiver.first_name )
def order_payment_refund_mail(instance): order_payment = instance order = order_payment.order receiver = order.user if not receiver: return try: # NOTE: only handling on order with a single donation donation = order.donations.first() except IndexError: return try: if donation.fundraiser: project = donation.fundraiser.project else: project = donation.project except AttributeError: return with TenantLanguage(receiver.primary_language): subject = _('Donation Refund') admin_email = properties.TENANT_MAIL_PROPERTIES.get('address') send_mail(template_name='payments/mails/order_payment_refund.mail', subject=subject, to=receiver, site=tenant_url(), project=project, admin_email=admin_email)
def send_welcome_mail(user=None): cur_language = translation.get_language() if user and user.primary_language: translation.activate(user.primary_language) else: translation.activate(properties.LANGUAGE_CODE) c = { 'email': user.email, 'site': tenant_url(), 'site_name': tenant_name(), 'user': user, 'first_name': user.first_name, 'LANGUAGE_CODE': user.primary_language, } subject_template_name = 'bb_accounts/activation_email_subject.txt' subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) send_mail( template_name='bb_accounts/activation_email', subject=subject, to=user, **c ) translation.activate(cur_language)
def send_contact_email(message, contact_email): subject = _('Contact message from %(sender)s') % {'sender': message.name} from_email = properties.CONTACT_EMAIL if not from_email: return # add the url to the backoffice lang_link = reverse('admin:contact_contactmessage_change', args=[message.id]) # Strip language from reverse generated link m = re.match(r'(/[^/]*)(/.*$)', lang_link) try: link = m.groups()[1] except IndexError: link = lang_link ctx = ClientContext( {'message': message, 'link': link, 'site_url': tenant_url(), 'site': tenant_site()}) text_content = render_to_string('contact/contact.mail.txt', context_instance=ctx) html_content = render_to_string('contact/contact.mail.html', context_instance=ctx) msg = EmailMultiAlternatives(subject=subject, body=text_content, to=[contact_email], from_email=from_email) msg.attach_alternative(html_content, "text/html") msg.send()
def __init__(self, instance, *args, **kwargs): self.task_member = instance self.task = instance.task self.task_link = '/go/tasks/{0}'.format(self.task.id) self.site = tenant_url() self.task_list = '/go/tasks' self.project_link = '/go/projects/{0}'.format(self.task.project.slug) self.cur_language = translation.get_language()
def __init__(self, instance): # the object wall the post is left (project, task...) self.parent = instance.content_object # author of the post self.author = instance.author self.site = tenant_url()
def mail_project_incomplete(project): send_mail( template_name="projects/mails/project_incomplete.mail", subject=_(u"The project '{0}' has expired").format(project.title), title=project.title, to=project.owner, site=tenant_url(), link='/go/projects/{0}'.format(project.id) )
def send_mail(template_name=None, subject=None, to=None, attachments=None, **kwargs): from bluebottle.common.tasks import _send_celery_mail if not to: logger.error("No recipient specified") return # Simple check if email address is valid regex = r'[^@]+@[^@]+\.[^@]+' if not re.match(regex, to.email): logger.error( "Trying to send email to invalid email address: {0}".format( to.email)) return if not kwargs.get('site'): kwargs.update({'site': tenant_url()}) kwargs.update({'settings': MailPlatformSettings.load()}) try: msg = create_message(template_name=template_name, to=to, subject=subject, attachments=attachments, **kwargs) except Exception as e: msg = None logger.error("Exception while rendering email template: {0}".format(e)) return # Explicetly set CELERY usage in properties. Used primarily for # testing purposes. try: tenant = connection.tenant except AttributeError: tenant = None if msg and properties.CELERY_MAIL: if properties.SEND_MAIL: _send_celery_mail.delay(msg, tenant, send=True) else: _send_celery_mail.delay(msg, tenant) elif msg: try: if properties.SEND_MAIL: msg.send() else: logger.info("Tried to send async email, " + "but mail sending is turned off.") except Exception as e: logger.error("Exception sending synchronous email: {0}".format(e)) return
def save(self, password_reset_form, domain_override=None, subject_template_name='bb_accounts/password_reset_subject.txt', email_template_name='bb_accounts/password_reset_email', use_https=True, token_generator=default_token_generator, from_email=None, request=None): """ Generates a one-use only link for resetting password and sends to the user. This has been ported from the Django PasswordResetForm to allow HTML emails instead of plaint text emails. """ # TODO: Create a patch to Django to use user.email_user instead of # send_email. user_model = get_user_model() email = password_reset_form.cleaned_data["email"] active_users = user_model._default_manager.filter( email__iexact=email, is_active=True) for user in active_users: if not domain_override: site_name = tenant_name() domain = tenant_url() else: site_name = domain = domain_override c = { 'email': user.email, 'site': domain, 'site_name': site_name, 'uid': int_to_base36(user.pk), 'user': user, 'token': token_generator.make_token(user), 'LANGUAGE_CODE': self.request.LANGUAGE_CODE[:2] } cur_language = translation.get_language() if user.primary_language: translation.activate(user.primary_language) else: translation.activate(properties.LANGUAGE_CODE) subject = loader.render_to_string(subject_template_name, c) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) translation.activate(cur_language) send_mail( template_name=email_template_name, to=user, subject=subject, **c )
def status_changed(self, oldstate, newstate): """ called by post_save signal handler, if status changed """ # confirm everything with task owner if oldstate in ("in progress", "open", "closed") and newstate == "realized": self.project.check_task_status() with TenantLanguage(self.author.primary_language): subject = _("The status of your task '{0}' is set to realized").format(self.title) send_mail( template_name="tasks/mails/task_status_realized.mail", subject=subject, title=self.title, to=self.author, site=tenant_url(), link='/go/tasks/{0}'.format(self.id) ) if oldstate in ("in progress", "open") and newstate == "closed": with TenantLanguage(self.author.primary_language): subject = _("The status of your task '{0}' is set to closed").format(self.title) send_mail( template_name="tasks/mails/task_status_closed.mail", subject=subject, title=self.title, to=self.author, site=tenant_url(), link='/go/tasks/{0}'.format(self.id) ) if oldstate in ("in progress", "open") and newstate in ("realized", "closed"): data = { "Task": self.title, "Author": self.author.username, "Old status": oldstate, "New status": newstate } bb_track("Task Completed", data)
def mail_project_incomplete(project): with TenantLanguage(project.owner.primary_language): subject = _(u"The project '{0}' has expired").format(project.title) send_mail(template_name="projects/mails/project_incomplete.mail", subject=subject, to=project.owner, title=project.title, receiver_name=project.owner.short_name, site=tenant_url(), link='/go/projects/{0}'.format(project.slug))
def mail_project_funded_internal(project): # XXX This is most likely obsolete. Candidate for removal? context = ClientContext( {'project': project, 'link': '/go/projects/{0}'.format(project.slug), 'site': tenant_url()}) subject = "A project has been funded" text_content = get_template('project_funded_internal.mail.txt').render(context) html_content = get_template('project_funded_internal.mail.html').render(context) msg = EmailMultiAlternatives(subject=subject, body=text_content, to=['*****@*****.**']) msg.attach_alternative(html_content, "text/html") msg.send()
def mail_project_complete(project): with TenantLanguage(project.owner.primary_language): subject = _(u"The project '{0}' has been realised").format(project.title) send_mail( template_name="projects/mails/project_complete.mail", subject=subject, title=project.title, to=project.owner, site=tenant_url(), link='/go/projects/{0}'.format(project.id) )
def mail_project_incomplete(project): with TenantLanguage(project.owner.primary_language): subject = _(u"The project '{0}' has expired").format(project.title) send_mail( template_name="projects/mails/project_incomplete.mail", subject=subject, to=project.owner, title=project.title, receiver_name=project.owner.short_name, site=tenant_url(), link='/go/projects/{0}'.format(project.slug) )
def status_changed(self, oldstate, newstate): """ called by post_save signal handler, if status changed """ # confirm everything with task owner if oldstate in ("in progress", "open") and newstate == "realized": send_mail( template_name="tasks/mails/task_status_realized.mail", subject=_("You've set '{0}' to realized").format(self.title), title=self.title, to=self.author, site=tenant_url(), link='/go/tasks/{0}'.format(self.id) )
def send_mail(template_name=None, subject=None, to=None, **kwargs): from bluebottle.common.tasks import _send_celery_mail if not to: logger.error("No recipient specified") return # Simple check if email address is valid regex = r'[^@]+@[^@]+\.[^@]+' if not re.match(regex, to.email): logger.error("Trying to send email to invalid email address: {0}" .format(to.email)) return if not kwargs.get('site'): kwargs.update({ 'site': tenant_url() }) try: msg = create_message(template_name=template_name, to=to, subject=subject, **kwargs) except Exception as e: msg = None logger.error("Exception while rendering email template: {0}".format(e)) return # Explicetly set CELERY usage in properties. Used primarily for # testing purposes. try: tenant = connection.tenant except AttributeError: tenant = None if msg and properties.CELERY_MAIL: if properties.SEND_MAIL: _send_celery_mail.delay(msg, tenant, send=True) else: _send_celery_mail.delay(msg, tenant) elif msg: try: if properties.SEND_MAIL: msg.send() else: logger.info("Tried to send async email, " + "but mail sending is turned off.") except Exception as e: logger.error("Exception sending synchronous email: {0}".format(e)) return
def _post_to_facebook(instance, tenant=None): """ Post a Wallpost to users Facebook page using Celery """ logger.info("FB post for:") logger.info("{0} with id {1} and tenant {2}".format(instance.__class__, instance.id, tenant.client_name)) if not tenant: return from tenant_schemas.utils import get_tenant_model from django.db import connection db_tenant = get_tenant_model().objects.get(client_name=tenant.client_name) connection.set_tenant(db_tenant) with LocalTenant(tenant, clear_tenant=True): social = instance.author.social_auth.get(provider="facebook") authorization_header = "Bearer {token}".format(token=social.extra_data["access_token"]) graph_url = "https://graph.facebook.com/v2.4/me/feed" base_url = "https://{domain}".format(domain=tenant.domain_url) link = instance.content_object.get_absolute_url() image = None # This code is executed via Celery, we assume the MediaWallpostPhoto # is saved and available on the instance. If the user uploaded # photos with the MediaWallpost we take the first one and include it # in the Facebook post. Otherwise we fallback to the project image. if isinstance(instance, MediaWallpost) and instance.photos.count() > 0: image = urljoin(base_url, get_thumbnail(instance.photos.all()[0].photo, "600x400").url) else: if hasattr(instance.content_object, "image") and instance.content_object.image: image = urljoin(base_url, get_thumbnail(instance.content_object.image, "600x400").url) description = getattr(instance.content_object, "pitch", instance.content_object.description) data = { "link": link, "name": instance.content_object.title, "description": description, "message": instance.text, "picture": image, "caption": tenant_url(), } # TODO: log failed requests requests.post( graph_url, data=json.dumps(data), headers={"Authorization": authorization_header, "Content-Type": "application/json"}, )
def __init__(self, instance, message=None, *args, **kwargs): self.task_member = instance self.task = instance.task self.ctx = { 'task': self.task, 'message': message, 'receiver': self.receiver, 'sender': self.sender, 'link': '/go/tasks/{0}'.format(self.task.id), 'site': tenant_url(), 'project_list': '/projects', 'project_link': '/projects/{0}'.format(self.task.project.slug), }
def send_contact_email(message, contact_email): subject = _('Contact message from %(sender)s') % {'sender': message.name} from_email = message.email # add the url to the backoffice link = reverse('admin:contact_contactmessage_change', args=[message.id]) ctx = ClientContext({'message': message, 'link': link, 'site_url': tenant_url(), 'site': tenant_site()}) text_content = render_to_string('contact/contact.mail.txt', context_instance=ctx) html_content = render_to_string('contact/contact.mail.html', context_instance=ctx) msg = EmailMultiAlternatives(subject=subject, body=text_content, to=[contact_email], from_email=from_email) msg.attach_alternative(html_content, "text/html") msg.send()
def get_context(self, recipient): from bluebottle.clients.utils import tenant_url, tenant_name context = { 'site': tenant_url(), 'site_name': tenant_name(), 'language': recipient.primary_language, 'contact_email': properties.CONTACT_EMAIL, 'first_name': recipient.first_name } for key, item in list(self.context.items()): context[key] = attrgetter(item)(self.obj) if 'context' in self.options: context.update(self.options['context']) return context
def get_generic_context(self): from bluebottle.clients.utils import tenant_url, tenant_name language = get_current_language() context = { 'site': tenant_url(), 'site_name': tenant_name(), 'language': language, 'contact_email': properties.CONTACT_EMAIL, 'first_name': _('Name') } for key, item in list(self.context.items()): context[key] = attrgetter(item)(self.obj) if 'context' in self.options: context.update(self.options['context']) return context
def deadline_reached(self): """ The task deadline has been reached. Set it to realised and notify the owner """ # send "The deadline of your task" - mail self.status = 'realized' self._init_status = 'realized' # suppress post_save activation self.save() send_mail( template_name="tasks/mails/task_deadline_reached.mail", subject=_("The deadline for task '{0}' has been reached").format(self.title), title=self.title, to=self.author, site=tenant_url(), link='/go/tasks/{0}'.format(self.id) )
def deadline_reached(self): if self.people_accepted: self.status = self.TaskStatuses.realized else: self.status = self.TaskStatuses.closed with TenantLanguage(self.author.primary_language): subject = _( "The status of your task '{0}' is set to closed").format( self.title) send_mail(template_name="tasks/mails/task_status_closed.mail", subject=subject, title=self.title, to=self.author, site=tenant_url(), link='/tasks/{0}'.format(self.id)) self.save()
def send_task_realized_mail(task, template, subject, tenant): """ Send an email to the task owner with the request to confirm the task participants. """ with LocalTenant(tenant, clear_tenant=True): if len( task.members.filter( status=TaskMember.TaskMemberStatuses.realized)): # There is already a confirmed task member: Do not bother the owner return send_mail(template_name='tasks/mails/{}.mail'.format(template), subject=subject, title=task.title, to=task.author, site=tenant_url(), link='/go/tasks/{0}'.format(task.id))
def email_deadline_update(sender, instance, **kwargs): if instance.pk: previous_instance = Task.objects.get(pk=instance.pk) if (previous_instance.deadline.date() != instance.deadline.date() and instance.status not in (Task.TaskStatuses.realized, Task.TaskStatuses.closed)): for task_member in instance.members_applied: with TenantLanguage(task_member.member.primary_language): subject = _('The deadline of your task is changed') send_mail(template_name='tasks/mails/deadline_changed.mail', subject=subject, title=instance.title, original_date=previous_instance.deadline, date=instance.deadline, to=task_member.member, site=tenant_url(), link='/tasks/{0}'.format(instance.id))
def send_welcome_mail(user=None): subject = _("Welcome to %(site_name)s") % {'site_name': tenant_name()} if user and user.primary_language: with TenantLanguage(user.primary_language): subject = _("Welcome to %(site_name)s") % {'site_name': tenant_name()} c = { 'email': user.email, 'site': tenant_url(), 'site_name': tenant_name(), 'user': user, 'first_name': user.first_name, 'LANGUAGE_CODE': user.primary_language, } send_mail( template_name='bb_accounts/activation_email', subject=subject, to=user, **c )
def successful_donation_fundraiser_mail(instance): donation = instance # should be only when the status is success try: receiver = donation.fundraiser.owner except Exception: # donation it's not coming from a fundraiser return fundraiser_link = '/go/fundraisers/{0}'.format(instance.fundraiser.id) pledged = (donation.order.status == StatusDefinition.PLEDGED) with TenantLanguage(receiver.primary_language): subject = _('You received a new donation') if instance.fundraiser.owner.email: if instance.anonymous: donor_name = _('an anonymous person') elif instance.order.user: if instance.order.user.first_name: donor_name = instance.order.user.first_name else: donor_name = instance.order.user.email else: donor_name = _('a guest') with LogMail(donation.mail_logs, 'new_oneoff_donation_fundraiser') as sent: if not sent: send_mail(template_name= 'donations/mails/new_oneoff_donation_fundraiser.mail', subject=subject, site=tenant_url(), to=receiver, link=fundraiser_link, donation=donation, pledged=pledged, donor_name=donor_name)
def successful_donation_fundraiser_mail(instance): donation = instance # should be only when the status is success try: receiver = donation.fundraiser.owner except: # donation it's not coming from a fundraiser return fundraiser_link = "/go/fundraisers/{0}".format(instance.fundraiser.id) pledged = donation.order.status == StatusDefinition.PLEDGED with TenantLanguage(receiver.primary_language): subject = _("You received a new donation") if instance.fundraiser.owner.email: if instance.anonymous: donor_name = _("an anonymous person") elif instance.order.user: if instance.order.user.first_name: donor_name = instance.order.user.first_name else: donor_name = instance.order.user.email else: donor_name = _("a guest") send_mail( template_name="bb_donations/mails/new_oneoff_donation_fundraiser.mail", subject=subject, site=tenant_url(), to=receiver, link=fundraiser_link, donation=donation, pledged=pledged, donor_name=donor_name, )
def send_deadline_to_apply_passed_mail(task, subject, tenant): with LocalTenant(tenant, clear_tenant=True): if not task.members_applied: template = 'deadline_to_apply_closed' else: if task.people_applied + task.externals_applied < task.people_needed: status = 'partial' elif task.people_accepted < task.people_needed: status = 'accept' else: status = 'target_reached' template = 'deadline_to_apply_{type}_{status}'.format( type=task.type, status=status) with LogMail(task.mail_logs, 'deadline_to_apply_passed') as sent: if not sent: send_mail(template_name='tasks/mails/{}.mail'.format(template), subject=subject, task=task, to=task.author, site=tenant_url(), edit_link='/tasks/{0}/edit'.format(task.id), link='/tasks/{0}'.format(task.id))
def __init__(self, instance): self.reaction = instance self.post = instance.wallpost self.reaction_author = self.reaction.author self.post_author = self.post.author self.site = tenant_url()
def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(MacroMicroListView, self).get_context_data(**kwargs) context['site'] = tenant_url() return context
def email_followers(sender, instance, created, **kwargs): """ When a Wallpost is created, project owners, task owners and fundraiser owners can check a box wether to email their followers. This signal handler looksup the appropriate followers depending on the type of page (project, task, fundraiser). It then sends out an email to those followers if they have campaign notifications enabled. """ from bluebottle.wallposts.models import Wallpost, SystemWallpost if isinstance(instance, Wallpost) and not isinstance(instance, SystemWallpost): if instance.email_followers: content_type = ContentType.objects.get_for_model( instance.content_object) # content_type references project # Determine if this wallpost is on a Project page, Task page, or # Fundraiser page. Required because of different Follow object # lookup mailers = set() # Contains unique user objects link = None if isinstance(instance.content_object, BaseProject): # Send update to all task owners, all fundraisers, all people # who donated and all people who are following (i.e. posted to # the wall) followers = Follow.objects.filter( content_type=content_type, object_id=instance.content_object.id).distinct().exclude(user=instance.author) [mailers.add(follower.user) for follower in followers] follow_object = _('project') link = '/go/projects/{0}'.format(instance.content_object.slug) if isinstance(instance.content_object, BaseTask): # Send update to all task members and to people who posted to # the wall --> Follower followers = Follow.objects.filter( content_type=content_type, object_id=instance.content_object.id).distinct().exclude(user=instance.author) [mailers.add(follower.user) for follower in followers] follow_object = _('task') link = '/go/tasks/{0}'.format(instance.content_object.id) if isinstance(instance.content_object, BaseFundraiser): # Send update to all people who donated or posted to the wall # --> Followers followers = Follow.objects.filter( content_type=content_type, object_id=instance.content_object.id).distinct().exclude(user=instance.author) [mailers.add(follower.user) for follower in followers] follow_object = _('fundraiser') link = '/go/fundraisers/{0}'.format(instance.content_object.id) wallpost_text = instance.text site = tenant_url() full_link = site + link for mailee in mailers: if mailee.campaign_notifications: cur_language = translation.get_language() if mailee.primary_language: translation.activate(mailee.primary_language) else: translation.activate(properties.LANGUAGE_CODE) subject = _("New wallpost on %(name)s") % { 'name': instance.content_object.title} translation.activate(cur_language) send_mail( template_name='bb_follow/mails/wallpost_mail.mail', subject=subject, wallpost_text=wallpost_text[:250], to=mailee, link=full_link, follow_object=follow_object, first_name=mailee.first_name, author=instance.author.first_name )
def _post_to_facebook(instance, tenant=None): """ Post a Wallpost to users Facebook page using Celery """ logger.info("FB post for:") logger.info("{0} with id {1} and tenant {2}".format(instance.__class__, instance.id, tenant.client_name)) if not tenant: return from tenant_schemas.utils import get_tenant_model from django.db import connection db_tenant = get_tenant_model().objects.get(client_name=tenant.client_name) connection.set_tenant(db_tenant) with LocalTenant(tenant, clear_tenant=True): social = instance.author.social_auth.get(provider='facebook') authorization_header = 'Bearer {token}'.format( token=social.extra_data['access_token'] ) graph_url = 'https://graph.facebook.com/v2.4/me/feed' base_url = 'https://{domain}'.format( domain=tenant.domain_url) link = urljoin( base_url, '/go/projects/{slug}'.format(slug=instance.content_object.slug) ) image = None # This code is executed via Celery, we assume the MediaWallpostPhoto # is saved and available on the instance. If the user uploaded # photos with the MediaWallpost we take the first one and include it # in the Facebook post. Otherwise we fallback to the project image. if isinstance(instance, MediaWallpost) and instance.photos.count() > 0: image = urljoin(base_url, get_thumbnail(instance.photos.all()[0].photo, "600x400").url ) else: if instance.content_object.image: image = urljoin( base_url, get_thumbnail(instance.content_object.image, "600x400").url ) logger.info("Image url: {0}".format(image)) data = { 'link': link, 'name': instance.content_object.title, 'description': instance.content_object.pitch, 'message': instance.text, 'picture': image, 'caption': tenant_url() } # TODO: log failed requests requests.post( graph_url, data=json.dumps(data), headers={ 'Authorization': authorization_header, 'Content-Type': 'application/json'} )
def email_followers(sender, instance, created, **kwargs): """ When a Wallpost is created, project owners, task owners and fundraiser owners can check a box wether to email their followers. This signal handler looksup the appropriate followers depending on the type of page (project, task, fundraiser). It then sends out an email to those followers if they have campaign notifications enabled. """ from bluebottle.wallposts.models import Wallpost, SystemWallpost if not created: return if isinstance(instance, Wallpost) and not isinstance(instance, SystemWallpost): if instance.email_followers: content_type = ContentType.objects.get_for_model( instance.content_object) # content_type references project # Determine if this wallpost is on a Project page, Task page, or # Fundraiser page. Required because of different Follow object # lookup mailers = set() # Contains unique user objects link = None if isinstance(instance.content_object, BaseProject): # Send update to all task owners, all fundraisers, all people # who donated and all people who are following (i.e. posted to # the wall) followers = Follow.objects.filter( content_type=content_type, object_id=instance.content_object.id).distinct().exclude( user=instance.author) [mailers.add(follower.user) for follower in followers] follow_object = _('project') link = '/go/projects/{0}'.format(instance.content_object.slug) if isinstance(instance.content_object, Task): # Send update to all task members and to people who posted to # the wall --> Follower followers = Follow.objects.filter( content_type=content_type, object_id=instance.content_object.id).distinct().exclude( user=instance.author) [mailers.add(follower.user) for follower in followers] follow_object = _('task') link = '/go/tasks/{0}'.format(instance.content_object.id) if isinstance(instance.content_object, BaseFundraiser): # Send update to all people who donated or posted to the wall # --> Followers followers = Follow.objects.filter( content_type=content_type, object_id=instance.content_object.id).distinct().exclude( user=instance.author) [mailers.add(follower.user) for follower in followers] follow_object = _('fundraiser') link = '/go/fundraisers/{0}'.format(instance.content_object.id) wallpost_text = instance.text site = tenant_url() full_link = site + link for mailee in mailers: if mailee.campaign_notifications: cur_language = translation.get_language() if mailee.primary_language: translation.activate(mailee.primary_language) else: translation.activate(properties.LANGUAGE_CODE) with TenantLanguage(mailee.primary_language): subject = _("New wallpost on %(name)s") % { 'name': instance.content_object.title } translation.activate(cur_language) send_mail( template_name='bb_follow/mails/wallpost_mail.mail', subject=subject, wallpost_text=wallpost_text[:250], to=mailee, link=full_link, follow_object=follow_object, first_name=mailee.first_name, author=instance.author.first_name)