Skip to content

Commit

Permalink
refactor to add restapi endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
cekk committed May 13, 2024
1 parent 42b2108 commit 1e76986
Show file tree
Hide file tree
Showing 21 changed files with 361 additions and 164 deletions.
35 changes: 0 additions & 35 deletions src/rer/newsletter/browser/message/messageviewlet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,41 +7,6 @@


class MessageManagerViewlet(ViewletBase):
def _getChannel(self):
return [x for x in aq_chain(self.context) if isinstance(x, Channel)]

def canManageNewsletter(self):
if not self._getChannel():
return False

isEditor = "Editor" in api.user.get_roles(obj=self.context)
hasManageNewsletter = api.user.get_permissions(obj=self.context).get(
"rer.newsletter: Manage Newsletter"
) and "Gestore Newsletter" not in api.user.get_roles(obj=self.context)
if isEditor or hasManageNewsletter:
return True
else:
return False

def canSendMessage(self):
if not self._getChannel():
return False

if api.content.get_state(
obj=self.context
) == "published" and api.user.get_permissions(obj=self.context).get(
"rer.newsletter: Send Newsletter"
):
return True
else:
return False

def messageAlreadySent(self):
history = ContentHistoryView(self.context, self.request).fullHistory()
if not history:
return False
send_history = [x for x in history if x["action"] == "Invio"]
return len(send_history) > 0

def render(self):
return self.index()
81 changes: 1 addition & 80 deletions src/rer/newsletter/browser/message/sendingtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,38 +45,6 @@ def _getDate(self):
# locale.setlocale(locale.LC_ALL, 'it_IT')
return datetime.today().strftime("Newsletter %d-%m-%Y")

def _getMessage(self, channel, message, footer):
message_template = self.context.restrictedTraverse(
"@@messagepreview_view"
)
parameters = {
"message_subheader": f"""
<tr>
<td align="left" colspan="2">
<div class="newsletterTitle">
<h1>{self.context.title}</h1>
</div>
</td>
</tr>""",
"message_unsubscribe_default": f"""
<tr>
<td align="left" colspan="2">
<div class="newsletter-unsubscribe">
{footer}
</div>
</td>
</tr>
""",
}

body = message_template(**parameters)

# passo la mail per il transform
portal = api.portal.get()
body = portal.portal_transforms.convertTo("text/mail", body)

return body

@button.buttonAndHandler(_("send_sendingtest", default="Send"))
def handleSave(self, action):
data, errors = self.extractData()
Expand All @@ -86,54 +54,7 @@ def handleSave(self, action):

try:
# prendo l'email dai parametri
email = data["email"]
emails = re.compile("[,|;]").split(email)

ns_obj = None
for obj in self.context.aq_chain:
if isinstance(obj, Channel):
ns_obj = obj
break
else:
if not ns_obj:
# non riesco a recuperare le info di un channel
return
message_obj = self.context

unsubscribe_footer_template = self.context.restrictedTraverse(
"@@unsubscribe_channel_template"
)
parameters = {
"portal_name": get_site_title(),
"channel_name": ns_obj.title,
"unsubscribe_link": ns_obj.absolute_url(),
"enabled": ns_obj.standard_unsubscribe,
}
unsubscribe_footer_text = unsubscribe_footer_template(**parameters)
body = self._getMessage(
ns_obj, message_obj, unsubscribe_footer_text
)

sender = compose_sender(channel=ns_obj)

nl_subject = (
" - " + ns_obj.subject_email if ns_obj.subject_email else ""
)

subject = "Messaggio di prova - " + message_obj.title + nl_subject
# per mandare la mail non passo per l'utility
# in ogni caso questa mail viene mandata da plone
mailHost = api.portal.get_tool(name="MailHost")
for email in emails:
mailHost.send(
body.getData(),
mto=email.strip(),
mfrom=sender,
subject=subject,
charset="utf-8",
msg_type="text/html",
immediate=True,
)
self.context.send_preview(email=data["email"])

except SMTPRecipientsRefused:
self.errors = "problemi con l'invio del messaggio"
Expand Down
28 changes: 9 additions & 19 deletions src/rer/newsletter/browser/message/sendmessageview.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,32 +57,22 @@ def channel(self):
@property
@memoize
def active_subscriptions(self):
channel = getMultiAdapter((self.channel, self.request), IChannelSubscriptions)
channel = getMultiAdapter(
(self.channel, self.request), IChannelSubscriptions
)
return channel.active_subscriptions

@button.buttonAndHandler(_("send_sendingview", default="Send"))
def handleSave(self, action):
if HAS_TASKQUEUE:
messageQueue = queryUtility(IMessageQueue)
isQueuePresent = queryUtility(ITaskQueue, name=QUEUE_NAME)
if isQueuePresent is not None and messageQueue is not None:
# se non riesce a connettersi con redis allora si spacca
messageQueue.start(self.context)
else:
# invio sincrono del messaggio
status = self.send_syncronous()
else:
# invio sincrono del messaggio
status = self.send_syncronous()
res = self.context.send_message()
status = res.get("status", "")
message = status == OK and self.success_message or self.error_message
type = status == OK and "info" or "error"
api.portal.show_message(message=message, request=self.request, type=type)
message_type = status == OK and "info" or "error"
api.portal.show_message(
message=message, request=self.request, type=message_type
)
self.request.response.redirect(self.context.absolute_url())

def send_syncronous(self):
adapter = getMultiAdapter((self.channel, self.request), IChannelSender)
return adapter.sendMessage(message=self.context)


message_sending_view = wrap_form(
SendMessageView, index=ViewPageTemplateFile("templates/sendmessageview.pt")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
>
<div style="margin-bottom: 2%;">
<span id="message-preview">
<a tal:condition="view/canManageNewsletter"
<a tal:condition="context/can_manage_newsletter"
tal:attributes="
href string:${context/absolute_url}/@@messagepreview_view;
class python: plone_6 and 'btn btn-primary' or 'plone-btn plone-btn-primary';
Expand All @@ -17,7 +17,7 @@
</a>
</span>
<span id="message-test">
<a tal:condition="view/canManageNewsletter"
<a tal:condition="context/can_manage_newsletter"
tal:attributes="
href string:${context/absolute_url}/@@sendingtest_view;
class python: plone_6 and 'btn btn-primary' or 'plone-btn plone-btn-primary';
Expand All @@ -29,9 +29,9 @@
</span>
<span id="message-preview"
tal:define="
already_sent view/messageAlreadySent;
already_sent context/message_already_sent;
"
tal:condition="view/canSendMessage"
tal:condition="context/can_send_message"
>
<a tal:condition="not: already_sent"
tal:attributes="
Expand Down
7 changes: 6 additions & 1 deletion src/rer/newsletter/content/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@
from plone.app.contenttypes.content import Folder
from rer.newsletter.interfaces import IChannel
from zope.interface import implementer
from rer.newsletter.adapter.subscriptions import IChannelSubscriptions
from zope.component import getMultiAdapter


@implementer(IChannel)
class Channel(Folder):
pass

def active_subscriptions(self):
channel = getMultiAdapter((self, self.REQUEST), IChannelSubscriptions)
return channel.active_subscriptions
160 changes: 159 additions & 1 deletion src/rer/newsletter/content/message.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,167 @@
# -*- coding: utf-8 -*-
from Acquisition import aq_chain
from plone import api
from plone.app.contenttypes.content import Folder
from plone.app.layout.viewlets.content import ContentHistoryView
from rer.newsletter import _
from rer.newsletter.adapter.sender import IChannelSender
from rer.newsletter.content.channel import Channel
from rer.newsletter.interfaces import IMessage
from rer.newsletter.utils import compose_sender
from rer.newsletter.utils import get_site_title
from rer.newsletter.utils import OK
from zope.component import getMultiAdapter
from zope.component import queryUtility
from zope.interface import implementer


try:
from collective.taskqueue.interfaces import ITaskQueue
from rer.newsletter.queue.handler import QUEUE_NAME
from rer.newsletter.queue.interfaces import IMessageQueue

HAS_TASKQUEUE = True
except ImportError:
HAS_TASKQUEUE = False


KEY = "rer.newsletter.message.details"


import re


@implementer(IMessage)
class Message(Folder):
pass

def get_channel(self):
for parent in aq_chain(self):
if isinstance(parent, Channel):
return parent
return None

def can_manage_newsletter(self):
if not self.get_channel():
return False

is_editor = "Editor" in api.user.get_roles(obj=self)
can_manage = api.user.get_permissions(obj=self).get(
"rer.newsletter: Manage Newsletter"
) and "Gestore Newsletter" not in api.user.get_roles(obj=self)
if is_editor or can_manage:
return True
return False

def can_send_message(self):
if not self.get_channel():
return False

if api.content.get_state(obj=self) != "published":
return False
return api.user.get_permissions(obj=self).get(
"rer.newsletter: Send Newsletter"
)

def message_already_sent(self):
history = ContentHistoryView(self, self.REQUEST).fullHistory()
if not history:
return False
send_history = [x for x in history if x["action"] == "Invio"]
return len(send_history) > 0

def active_subscriptions(self):
channel = self.get_channel()
if not channel:
return 0
return channel.active_subscriptions()

# send methods
def send_message(self):
if HAS_TASKQUEUE:
message_queue = queryUtility(IMessageQueue)
is_queue_present = queryUtility(ITaskQueue, name=QUEUE_NAME)
if is_queue_present is not None and message_queue is not None:
# se non riesce a connettersi con redis allora si spacca
message_queue.start(self)
else:
# invio sincrono del messaggio
status = self.send_syncronous()
else:
# invio sincrono del messaggio
status = self.send_syncronous()
return {"status": status}

def send_syncronous(self):
channel = self.get_channel()
adapter = getMultiAdapter((channel, self.REQUEST), IChannelSender)
return adapter.sendMessage(message=self)

def send_preview(self, email):
emails = re.compile("[,|;]").split(email)
channel = self.get_channel()
if not channel:
# non riesco a recuperare le info di un channel
return

body = self.compose_message(channel=channel)

sender = compose_sender(channel=channel)

nl_subject = (
" - " + channel.subject_email if channel.subject_email else ""
)

subject = "Messaggio di prova - " + self.title + nl_subject
# per mandare la mail non passo per l'utility
# in ogni caso questa mail viene mandata da plone
mail_host = api.portal.get_tool(name="MailHost")
for email in emails:
mail_host.send(
body.getData(),
mto=email.strip(),
mfrom=sender,
subject=subject,
charset="utf-8",
msg_type="text/html",
immediate=True,
)

def compose_message(self, channel):
unsubscribe_footer_template = self.restrictedTraverse(
"@@unsubscribe_channel_template"
)
parameters = {
"portal_name": get_site_title(),
"channel_name": channel.title,
"unsubscribe_link": channel.absolute_url(),
"enabled": channel.standard_unsubscribe,
}

message_template = self.restrictedTraverse("@@messagepreview_view")
parameters = {
"message_subheader": f"""
<tr>
<td align="left" colspan="2">
<div class="newsletterTitle">
<h1>{self.title}</h1>
</div>
</td>
</tr>""",
"message_unsubscribe_default": f"""
<tr>
<td align="left" colspan="2">
<div class="newsletter-unsubscribe">
{unsubscribe_footer_template(**parameters)}
</div>
</td>
</tr>
""",
}

body = message_template(**parameters)

# passo la mail per il transform
portal = api.portal.get()
body = portal.portal_transforms.convertTo("text/mail", body)

return body
Empty file.
Loading

0 comments on commit 1e76986

Please sign in to comment.