Skip to content
This repository has been archived by the owner on Feb 9, 2018. It is now read-only.

Handle subscribing to mailplatform async #782

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php
namespace Hanzo\Bundle\NewsletterBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\EventDispatcher\Event;
use Hanzo\Bundle\NewsletterBundle\Providers\MailPlatformRequest;

/**
* @author Henrik Farre <hf@bellcom.dk>
*/
class MailPlatformApiHandlerCommand extends ContainerAwareCommand
{
/**
* @var bool
*/
private $shutdown = false;
private $isWorking = false;
private $quiet = false;

/**
* Shutdown running process - if in demon mode.
*
* @param int $signal pcntl signal
*/
public function shutdown($signal)
{
$map = [
SIGINT => 'SIGINT',
SIGQUIT => 'SIGQUIT',
SIGTERM => 'SIGTERM',
SIGHUP => 'SIGHUP',
];

if (isset($map[$signal])) {
if (!$this->isWorking) {
exit;
}

$this->shutdown = true;
}
}

/**
* {@inheritDoc}
*
*/
protected function configure()
{
$this->setName('hanzo:newsletter:phenstalk-mailplatformapihandler-worker')
->setDescription('Handles async calls for MailPlatformProvider')
->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'Set max number of loops before exit.', 0)
->addOption('ttl', null, InputOption::VALUE_OPTIONAL, 'Set ttl on script, will exit script in tts seconds.', 0)
->addOption('once', null, InputOption::VALUE_OPTIONAL, 'Only run once, do not listen for jobs in beanstalk', false);
}

/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
// Disable instance pooling when operating in a loop..
\Propel::disableInstancePooling();

$this->quiet = $input->getOption('quiet');

if (!$this->quiet) {
$output->writeln(sprintf(
'<comment>[%s]</comment> <info>Loaded. Ctrl+C to break</info>',
date('Y-m-d H:i:s')
));
}

$loop = 0;
$now = time();
$ttl = (int) $input->getOption('ttl');
$once = $input->getOption('once');

if ($once === false) {
// Watch beanstalk
// bind pcntl signals
$this->bind();

while ($this->watch($input, $output)) {
$loop++;

if ($ttl && strtotime('now +'.(int) $ttl.' seconds') > $now) {
exit;
}

if ($input->getOption('limit') && $loop > $input->getOption('limit')) {
exit;
}

// handle term signals
pcntl_signal_dispatch();
}
}
}

/**
* Watch for incoming jobs
*
* @param InputInterface $input
* @param OutputInterface $output
*
* @return bool
*/
private function watch(InputInterface $input, OutputInterface $output)
{
if ($this->shutdown) {
exit;
}

if (!$this->quiet) {
$output->writeln(sprintf(
'<comment>[%s]</comment> <info>Watching for incomming jobs ...</info>',
date('Y-m-d H:i:s')
));
}

/** @var \Leezy\PheanstalkBundle\Proxy\PheanstalkProxy $pheanstalk */
$pheanstalk = $this->getContainer()->get('leezy.pheanstalk');

/** @var \Pheanstalk_Job $job */
$job = $pheanstalk
->watch('mailplatform')
->ignore('default')
->reserve();

$this->isWorking = true;
$data = json_decode($job->getData(), true);

if (!$this->quiet) {
$output->writeln(sprintf(
'<comment>[%s]</comment> <info>Job #'.$job->getId().' received - calling mailplatform</info>',
date('Y-m-d H:i:s')
));
}

try {
$this->handle($data);
} catch (\Exception $exception) {
}

$pheanstalk->delete($job);
$this->isWorking = false;

return true;
}

/**
* @param Array $data
*/
private function handle(Array $data)
{
extract($data);

$request = new MailPlatformRequest($username, $token, $baseUrl, $query);
$request->type = $type;
$request->method = $method;
$request->body = $body;

return $request->execute();
}

/**
* Bind proc signals, so shutdowns will be executed correctly.
*/
private function bind()
{
pcntl_signal(SIGALRM, [$this, 'shutdown']);
pcntl_signal(SIGINT, [$this, 'shutdown']);
pcntl_signal(SIGQUIT, [$this, 'shutdown']);
pcntl_signal(SIGTERM, [$this, 'shutdown']);
pcntl_alarm(2);
}
}
23 changes: 15 additions & 8 deletions src/Hanzo/Bundle/NewsletterBundle/NewsletterApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
**/
class NewsletterApi
{
protected $domainKey = null;
protected $mailer = null;
protected $provider = null;
protected $cache = null;
public $domainKey = null;
protected $mailer = null;
protected $provider = null;
protected $cache = null;

/**
* __construct
Expand All @@ -26,13 +26,21 @@ class NewsletterApi
**/
public function __construct( $mailer, $provider, $cache )
{
// TODO: priority: low, hardcoded vars
$this->mailer = $mailer;
$this->domainKey = Hanzo::getInstance()->get('core.domain_key');
$this->provider = $provider;
$this->cache = $cache;
}

/**
* @param string $key
*/
public function setDomainKey($key)
{
$this->domainKey = $key;
$this->provider->domainKey = $key;
}

/**
* sendNotificationEmail
* @return void
Expand All @@ -54,7 +62,7 @@ public function sendNotificationEmail( $action, $email, $name = '' )
* @return stdClass
* @author Henrik Farre <hf@bellcom.dk>
**/
public function subscribe( $email, $list_id, Array $extraData = [] )
public function subscribe($email, $list_id, Array $extraData = [])
{
if (is_array($list_id))
{
Expand Down Expand Up @@ -314,8 +322,7 @@ protected function getLanguageForMails()
$language = 'EN';
// EN, DK, DE, NO, SE

$domainKey = Hanzo::getInstance()->get('core.domain_key');
switch ($domainKey)
switch ($this->domainKey)
{
case 'SalesDK':
case 'DK':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@

class MailPlatformProvider extends BaseProvider
{
public $domainKey;

public function __construct()
{
$this->domainKey = Hanzo::getInstance()->get('core.domain_key');
}

/**
* subscriberCreate
*
Expand Down Expand Up @@ -48,7 +55,7 @@ public function subscriberUpdate($subscriber_id, $list_id, Array $params = [])
'details' => [
'emailaddress' => $subscriber_id,
'listid' => $list_id,
],
],
];

$optionalParams = ['customfields'];
Expand Down Expand Up @@ -85,7 +92,7 @@ public function subscriberDelete($subscriber_id, $list_id = false, Array $params
'sendthankyou' => 'true',
'language' => 'EN',
'formid' => $this->getUnsubscribeFormId($list_id),
],
],
];

if ($list_id !== false)
Expand Down Expand Up @@ -120,7 +127,7 @@ public function subscriberGet($subscriber_id)
$request->body = [
'details' => [
'emailaddress' => $subscriber_id,
],
],
];

return $request->execute();
Expand All @@ -145,7 +152,7 @@ public function loadCustomFields($ext_id)

$requestBody = [
'details' => ['subscriberid' => $ext_id],
];
];

$request->body = $requestBody;

Expand All @@ -169,7 +176,7 @@ public function subscriberActivate($subscriber_id, $list_id)
'details' => [
'emailaddress' => $subscriber_id,
'listid' => $list_id,
],
],
];

$request = $this->getRequest();
Expand Down Expand Up @@ -199,7 +206,7 @@ public function subscriberIsSubscribed($subscriber_id, Array $list_ids)
'details' => [
'emailaddress' => $subscriber_id,
'listids' => $list_ids,
],
],
];

// $optionalParams = ['active_only', 'not_bounced', 'return_listid'];
Expand Down Expand Up @@ -235,9 +242,8 @@ public function subscriberAddToList($subscriber_id, $list_id, Array $params = []
'format' => 'html',
'confirmed' => 'false',
'confirm_language' => 'EN',
// Results in an increased amounts for 500 errors
// 'add_to_autoresponders' => 1,
],
'add_to_autoresponders' => 1,
],
];

$optionalParams = ['format', 'confirmed', 'confirm_language', 'add_to_autoresponders', 'customfields'];
Expand All @@ -248,6 +254,8 @@ public function subscriberAddToList($subscriber_id, $list_id, Array $params = []
$request->type = 'subscribers';
$request->method = 'AddSubscriberToList';
$request->body = $requestBody;
// Run using beanstalk
$request->async = true;

return $request->execute();
}
Expand All @@ -270,7 +278,7 @@ public function subscriberGetSubscribedLists($subscriber_id)
$request->body = [
'details' => [
'emailaddress' => $subscriber_id,
],
],
];

return $request->execute();
Expand All @@ -295,7 +303,7 @@ public function listsGet(Array $params = [])
'details' => [
'start' => 0,
'perpage' => 50,
],
],
];

$optionalParams = ['start', 'perpage'];
Expand All @@ -317,14 +325,13 @@ public function listsGet(Array $params = [])
*/
protected function getRequest()
{
$domainKey = Hanzo::getInstance()->get('core.domain_key');
$username = false;
$token = false;

$baseUrl = 'http://client2.mailmailmail.net';
$query = 'xml.php';

switch ($domainKey)
switch ($this->domainKey)
{
case 'SalesDK':
case 'DK':
Expand Down
Loading