diff options
author | dartcafe <github@dartcafe.de> | 2022-01-26 01:49:42 +0300 |
---|---|---|
committer | dartcafe <github@dartcafe.de> | 2022-01-26 01:49:42 +0300 |
commit | 3c0421e891d06528e561122f91f52142f9b303ca (patch) | |
tree | 5c222572947d97f7f3c4150e396e07835d69be3e /lib | |
parent | f4d87bbc2d573bafcdf5246ef6304e54b4d2b6d0 (diff) |
refactor mail classes
Signed-off-by: dartcafe <github@dartcafe.de>
Diffstat (limited to 'lib')
-rw-r--r-- | lib/Model/Mail/InvitationMail.php | 53 | ||||
-rw-r--r-- | lib/Model/Mail/MailBase.php | 99 | ||||
-rw-r--r-- | lib/Model/Mail/NotificationMail.php | 19 | ||||
-rw-r--r-- | lib/Model/Mail/ReminderMail.php | 57 |
4 files changed, 132 insertions, 96 deletions
diff --git a/lib/Model/Mail/InvitationMail.php b/lib/Model/Mail/InvitationMail.php index 1acbe51d..8ccd5381 100644 --- a/lib/Model/Mail/InvitationMail.php +++ b/lib/Model/Mail/InvitationMail.php @@ -25,10 +25,6 @@ namespace OCA\Polls\Model\Mail; use OCA\Polls\Db\Share; -use League\CommonMark\MarkdownConverter; -use League\CommonMark\Environment\Environment; -use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; -use League\CommonMark\Extension\Table\TableExtension; class InvitationMail extends MailBase { private const TEMPLATE_CLASS = 'polls.Invitation'; @@ -42,52 +38,39 @@ class InvitationMail extends MailBase { ) { parent::__construct($recipientId, $share->getPollId()); $this->share = $share; - $this->buildEmailTemplate(); } - public function buildEmailTemplate() : void { - $this->emailTemplate->setSubject($this->trans->t('Poll invitation "%s"', $this->poll->getTitle())); - $this->emailTemplate->addHeader(); - $this->emailTemplate->addHeading($this->trans->t('Poll invitation "%s"', $this->poll->getTitle()), false); - $this->emailTemplate->addBodyText($this->getMainBody()); - $this->emailTemplate->addBodyText($this->getRichDescription()); + protected function getSubject(): string { + return $this->trans->t('Poll invitation "%s"', $this->poll->getTitle()); + } - $this->emailTemplate->addBodyButton( - $this->trans->t('Go to poll'), - $this->url - ); - $this->emailTemplate->addBodyText($this->trans->t('This link gives you personal access to the poll named above. Press the button above or copy the following link and add it in your browser\'s location bar:')); - $this->emailTemplate->addBodyText($this->url); - $this->emailTemplate->addBodyText($this->trans->t('Do not share this link with other people, because it is connected to your votes.')); - $this->emailTemplate->addFooter($this->trans->t('This email is sent to you, because you are invited to vote in this poll by the poll owner. At least your name or your email address is recorded in this poll. If you want to get removed from this poll, contact the site administrator or the initiator of this poll, where the mail is sent from.')); + protected function getFooter(): string { + return $this->trans->t('This email is sent to you, because you are invited to vote in this poll by the poll owner. At least your name or your email address is recorded in this poll. If you want to get removed from this poll, contact the site administrator or the initiator of this poll, where the mail is sent from.'); } - protected function getMainBody() : string { + protected function buildBody(): void { if ($this->share->getType() === Share::TYPE_GROUP) { - return str_replace( + $this->emailTemplate->addBodyText(str_replace( ['{owner}', '{title}', '{group_name}'], [$this->owner->getDisplayName(), $this->poll->getTitle(), $this->share->getDisplayName()], $this->trans->t('{owner} invited you to take part in the poll "{title}" as a member of the group {group_name}') - ); + )); } else { - return str_replace( + $this->emailTemplate->addBodyText(str_replace( ['{owner}', '{title}'], [$this->owner->getDisplayName(), $this->poll->getTitle()], $this->trans->t('{owner} invited you to take part in the poll "{title}"') - ); + )); } - } - protected function getRichDescription() : string { - $config = [ - 'html_input' => 'strip', - 'allow_unsafe_links' => false, - ]; + $this->emailTemplate->addBodyText($this->getRichDescription(), $this->getRichDescription()); - $environment = new Environment($config); - $environment->addExtension(new CommonMarkCoreExtension()); - $environment->addExtension(new TableExtension()); - $converter = new MarkdownConverter($environment); - return $converter->convertToHtml($this->poll->getDescription())->getContent(); + if ($this->getButtonText() && $this->url) { + $this->emailTemplate->addBodyButton($this->getButtonText(), $this->url); + } + + $this->emailTemplate->addBodyText($this->trans->t('This link gives you personal access to the poll named above. Press the button above or copy the following link and add it in your browser\'s location bar:')); + $this->emailTemplate->addBodyText($this->url); + $this->emailTemplate->addBodyText($this->trans->t('Do not share this link with other people, because it is connected to your votes.')); } } diff --git a/lib/Model/Mail/MailBase.php b/lib/Model/Mail/MailBase.php index d6479a40..58f354fa 100644 --- a/lib/Model/Mail/MailBase.php +++ b/lib/Model/Mail/MailBase.php @@ -35,9 +35,13 @@ use OCA\Polls\Exceptions\InvalidEmailAddress; use OCP\L10N\IFactory; use OCP\Mail\IEMailTemplate; use OCP\Mail\IMailer; +use League\CommonMark\MarkdownConverter; +use League\CommonMark\Environment\Environment; +use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; +use League\CommonMark\Extension\Table\TableExtension; use Psr\Log\LoggerInterface; -class MailBase { +abstract class MailBase { private const TEMPLATE_CLASS = 'polls.Mail'; /** @var UserBase */ @@ -64,12 +68,12 @@ class MailBase { /** @var IFactory */ protected $transFactory; - /** @var IEMailTemplate */ - protected $emailTemplate; - /** @var IUserManager */ private $userManager; + /** @var IEmailTemplate */ + protected $emailTemplate; + /** @var User */ protected $owner; @@ -78,16 +82,33 @@ class MailBase { int $pollId, string $url = null ) { - $this->poll = $this->getPoll($pollId); - $this->recipient = $this->getUser($recipientId); - $this->url = $url ?? $this->poll->getVoteUrl(); $this->userManager = Container::queryClass(IUserManager::class); $this->logger = Container::queryClass(LoggerInterface::class); $this->mailer = Container::queryClass(IMailer::class); $this->transFactory = Container::queryClass(IFactory::class); + + $this->poll = $this->getPoll($pollId); + $this->recipient = $this->getUser($recipientId); + $this->url = $url ?? $this->poll->getVoteUrl(); + $this->initializeClass(); } + public function send(): void { + $this->validateEmailAddress(); + + try { + $message = $this->mailer->createMessage(); + $message->setTo([$this->recipient->getEmailAddress() => $this->recipient->getDisplayName()]); + $message->useTemplate($this->getEmailTemplate()); + $this->mailer->send($message); + } catch (\Exception $e) { + $this->logger->error('Error sending Mail to ' . json_encode($this->recipient)); + $this->logger->alert($e->getMessage()); + throw $e; + } + } + protected function initializeClass(): void { $this->owner = $this->poll->getOwnerUserObject(); @@ -101,8 +122,9 @@ class MailBase { ? $this->recipient->getLanguage() : $this->owner->getLanguage() ); + } - $this->footer = $this->trans->t('This email is sent to you, because you subscribed to notifications of this poll. To opt out, visit the poll and remove your subscription.'); + private function getEmailTemplate() : IEMailTemplate { $this->emailTemplate = $this->mailer->createEMailTemplate( self::TEMPLATE_CLASS, [ 'owner' => $this->owner->getDisplayName(), @@ -110,25 +132,39 @@ class MailBase { 'link' => $this->url ] ); - } - public function getEmailTemplate() : IEMailTemplate { + $this->emailTemplate->setSubject($this->getSubject()); + + // add heading + $this->emailTemplate->addHeader(); + $this->emailTemplate->addHeading($this->getHeading(), false); + + $this->buildBody(); + + // add footer + $this->emailTemplate->addFooter($this->getFooter()); + return $this->emailTemplate; } - public function send(): void { - $this->validateEmailAddress(); + protected function getSubject(): string { + return $this->trans->t('Notification for poll "%s"', $this->poll->getTitle()); + } - try { - $message = $this->mailer->createMessage(); - $message->setTo([$this->recipient->getEmailAddress() => $this->recipient->getDisplayName()]); - $message->useTemplate($this->emailTemplate); - $this->mailer->send($message); - } catch (\Exception $e) { - $this->logger->error('Error sending Mail to ' . json_encode($this->recipient)); - $this->logger->alert($e->getMessage()); - throw $e; - } + protected function getHeading(): string { + return $this->getSubject(); + } + + protected function getButtonText(): string { + return $this->trans->t('Go to poll'); + } + + protected function getFooter(): string { + return $this->trans->t('This email is sent to you, because you subscribed to notifications of this poll. To opt out, visit the poll and remove your subscription.'); + } + + protected function buildBody(): void { + $this->emailTemplate->addBodyText('Sorry. This eMail has no text and this should not happen.'); } protected function getUser(string $userId) : UserBase { @@ -140,15 +176,28 @@ class MailBase { return Container::findShare($this->poll->getId(), $userId)->getUserObject(); } - protected function getShareURL() : string { + protected function getRichDescription() : string { + $config = [ + 'html_input' => 'strip', + 'allow_unsafe_links' => false, + ]; + + $environment = new Environment($config); + $environment->addExtension(new CommonMarkCoreExtension()); + $environment->addExtension(new TableExtension()); + $converter = new MarkdownConverter($environment); + return $converter->convertToHtml($this->poll->getDescription())->getContent(); + } + + private function getShareURL() : string { return Container::findShare($this->poll->getId(), $this->recipient->getId())->getURL(); } - protected function getPoll(int $pollId) : Poll { + private function getPoll(int $pollId) : Poll { return Container::queryPoll($pollId); } - protected function validateEmailAddress(): void { + private function validateEmailAddress(): void { if (!$this->recipient->getEmailAddress() || !filter_var($this->recipient->getEmailAddress(), FILTER_VALIDATE_EMAIL)) { throw new InvalidEmailAddress('Invalid email address (' . $this->recipient->getEmailAddress() . ')'); diff --git a/lib/Model/Mail/NotificationMail.php b/lib/Model/Mail/NotificationMail.php index 9f179dc5..df266e91 100644 --- a/lib/Model/Mail/NotificationMail.php +++ b/lib/Model/Mail/NotificationMail.php @@ -44,13 +44,17 @@ class NotificationMail extends MailBase { ) { parent::__construct($subscription->getUserId(), $subscription->getPollId()); $this->subscription = $subscription; - $this->buildEmailTemplate(); } - public function buildEmailTemplate() : void { - $this->emailTemplate->setSubject($this->trans->t('Polls App - New Activity')); - $this->emailTemplate->addHeader(); - $this->emailTemplate->addHeading($this->trans->t('Polls App - New Activity'), false); + protected function getSubject(): string { + return $this->trans->t('Polls App - New Activity'); + } + + protected function getFooter(): string { + return $this->trans->t('This email is sent to you, because you subscribed to notifications of this poll. To opt out, visit the poll and remove your subscription.'); + } + + protected function buildBody(): void { $this->emailTemplate->addBodyText(str_replace( ['{title}'], [$this->poll->getTitle()], @@ -68,11 +72,10 @@ class NotificationMail extends MailBase { $this->emailTemplate->addBodyListItem($this->getComposedLogString($logItem, $displayName)); } - $this->emailTemplate->addBodyButton(htmlspecialchars($this->trans->t('Go to poll')), $this->url, ''); - $this->emailTemplate->addFooter($this->trans->t('This email is sent to you, because you subscribed to notifications of this poll. To opt out, visit the poll and remove your subscription.')); + $this->emailTemplate->addBodyButton($this->getButtonText(), $this->url); } - protected function getComposedLogString(Log $logItem, string $displayName): string { + private function getComposedLogString(Log $logItem, string $displayName): string { $logStrings = [ Log::MSG_ID_SETVOTE => $this->trans->t('%s has voted.', [$displayName]), Log::MSG_ID_UPDATEPOLL => $this->trans->t('Updated poll configuration. Please check your votes.'), diff --git a/lib/Model/Mail/ReminderMail.php b/lib/Model/Mail/ReminderMail.php index 30b5ac62..0855e7c0 100644 --- a/lib/Model/Mail/ReminderMail.php +++ b/lib/Model/Mail/ReminderMail.php @@ -53,52 +53,53 @@ class ReminderMail extends MailBase { parent::__construct($recipientId, $pollId); $this->deadline = $deadline; $this->timeToDeadline = $timeToDeadline; - $this->buildEmailTemplate(); } - public function buildEmailTemplate() : void { + protected function getSubject(): string { + return $this->trans->t('Reminder for poll "%s"', $this->poll->getTitle()); + } + + protected function getButtonText(): string { + return $this->trans->t('Check your votes'); + } + + protected function getFooter(): string { + return $this->trans->t('This email is sent to you, because you are invited to vote in this poll by the poll owner. At least your name or your email address is recorded in this poll. If you want to get removed from this poll, contact the site administrator or the initiator of this poll, where the mail is sent from.'); + } + + protected function buildBody(): void { $dtDeadline = new DateTime('now', $this->recipient->getTimeZone()); $dtDeadline->setTimestamp($this->deadline); $deadlineText = (string) $this->trans->l('datetime', $dtDeadline, ['width' => 'long']); - $this->emailTemplate->setSubject($this->trans->t('Reminder for poll "%s"', $this->poll->getTitle())); - $this->emailTemplate->addHeader(); - $this->emailTemplate->addHeading($this->trans->t('Reminder for poll "%s"', $this->poll->getTitle()), false); - - $reminderText = str_replace( - ['{owner}'], - [$this->owner->getDisplayName()], - $this->trans->t('{owner} sends you this reminder to make sure, your votes are set.') - ); - if ($this->getReminderReason() === self::REASON_OPTION) { - $reminderText = str_replace( + $this->emailTemplate->addBodyText(str_replace( ['{leftPeriod}', '{dateTime}', '{timezone}'], [($this->timeToDeadline / 3600), $deadlineText, $this->recipient->getTimeZone()->getName()], $this->trans->t('The first poll option is away less than {leftPeriod} hours ({dateTime}, {timezone}).') - ); + )); + } elseif ($this->getReminderReason() === self::REASON_EXPIRATION) { + $this->emailTemplate->addBodyText(str_replace( + ['{leftPeriod}', '{dateTime}', '{timezone}'], + [($this->timeToDeadline / 3600), $deadlineText, $this->recipient->getTimeZone()->getName()], + $this->trans->t('The poll is about to expire in less than {leftPeriod} hours ({dateTime}, {timezone}).') + )); + } else { + $this->emailTemplate->addBodyText(str_replace( + ['{owner}'], + [$this->owner->getDisplayName()], + $this->trans->t('{owner} sends you this reminder to make sure, your votes are set.') + )); } - if ($this->getReminderReason() === self::REASON_EXPIRATION) { - $reminderText = str_replace( - ['{leftPeriod}', '{dateTime}', '{timezone}'], - [($this->timeToDeadline / 3600), $deadlineText, $this->recipient->getTimeZone()->getName()], - $this->trans->t('The poll is about to expire in less than {leftPeriod} hours ({dateTime}, {timezone}).') - ); - } + $this->emailTemplate->addBodyButton($this->getButtonText(), $this->url); - $this->emailTemplate->addBodyText($reminderText); - $this->emailTemplate->addBodyButton( - $this->trans->t('Check your votes'), - $this->url - ); $this->emailTemplate->addBodyText($this->trans->t('This link gives you personal access to the poll named above. Press the button above or copy the following link and add it in your browser\'s location bar:')); $this->emailTemplate->addBodyText($this->url); $this->emailTemplate->addBodyText($this->trans->t('Do not share this link with other people, because it is connected to your votes.')); - $this->emailTemplate->addFooter($this->trans->t('This email is sent to you, because you are invited to vote in this poll by the poll owner. At least your name or your email address is recorded in this poll. If you want to get removed from this poll, contact the site administrator or the initiator of this poll, where the mail is sent from.')); } - public function getReminderReason() : ?string { + private function getReminderReason() : ?string { if ($this->poll->getExpire()) { return self::REASON_EXPIRATION; } elseif ($this->poll->getType() === Poll::TYPE_DATE) { |