Skip to content
This repository has been archived by the owner on Aug 15, 2024. It is now read-only.

Commit

Permalink
Merge pull request #130 from blopa/develop
Browse files Browse the repository at this point in the history
Develop
  • Loading branch information
blopa authored Dec 10, 2017
2 parents e57ad34 + 93c5e63 commit fa4e4f3
Show file tree
Hide file tree
Showing 20 changed files with 1,069 additions and 442 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ interface ChatbotAPIInterface
{

const CHATBOTUSER_ID = 'chatbotuser_id';
const LAST_COMMAND_DETAILS = 'last_command_details';
const FALLBACK_QTY = 'fallback_qty';
const CHATBOTAPI_ID = 'chatbotapi_id';
const CREATED_AT = 'created_at';
Expand All @@ -34,7 +35,6 @@ interface ChatbotAPIInterface
const CHATBOT_TYPE = 'chatbot_type';
const UPDATED_AT = 'updated_at';
const ENABLED = 'enabled';
const LAST_COMMAND_DETAILS = 'last_command_details';
const CHAT_ID = 'chat_id';


Expand Down
32 changes: 30 additions & 2 deletions Magento2/app/code/Werules/Chatbot/Api/Data/MessageInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,19 @@
interface MessageInterface
{

const MESSAGE_ID = 'message_id';
const CONTENT_TYPE = 'content_type';
const CONTENT = 'content';
const CONTENT_TYPE = 'content_type';
const SENT_AT = 'sent_at';
const STATUS = 'status';
const MESSAGE_ID = 'message_id';
const CREATED_AT = 'created_at';
const SENDER_ID = 'sender_id';
const DIRECTION = 'direction';
const CHATBOT_TYPE = 'chatbot_type';
const UPDATED_AT = 'updated_at';
const MESSAGE_PAYLOAD = 'message_payload';
const CHAT_MESSAGE_ID = 'chat_message_id';
const CURRENT_COMMAND_DETAILS = 'current_command_details';


/**
Expand Down Expand Up @@ -179,4 +181,30 @@ public function getMessagePayload();
* @return \Werules\Chatbot\Api\Data\MessageInterface
*/
public function setMessagePayload($message_payload);

/**
* Get sent_at
* @return string|null
*/
public function getSentAt();

/**
* Set sent_at
* @param string $sent_at
* @return \Werules\Chatbot\Api\Data\MessageInterface
*/
public function setSentAt($sent_at);

/**
* Get current_command_details
* @return string|null
*/
public function getCurrentCommandDetails();

/**
* Set current_command_details
* @param string $current_command_details
* @return \Werules\Chatbot\Api\Data\MessageInterface
*/
public function setCurrentCommandDetails($current_command_details);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* Magento Chatbot Integration
* Copyright (C) 2017
*
* This file is part of Werules/Chatbot.
*
* Werules/Chatbot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

namespace Werules\Chatbot\Block\Adminhtml\System\Config\Form\Field;

class MessageQueueModeList implements \Magento\Framework\Option\ArrayInterface
{
/**
* Provide available options as a value/label array
*
* @return array
*/
public function toOptionArray()
{
return array(
array('value' => 0, 'label' => __("None")),
array('value' => 1, 'label' => __("Simple Restrictive")),
array('value' => 2, 'label' => __("Restrictive")),
array('value' => 3, 'label' => __("Non-restrictive"))
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php
/**
* Magento Chatbot Integration
* Copyright (C) 2017
*
* This file is part of Werules/Chatbot.
*
* Werules/Chatbot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

namespace Werules\Chatbot\Block\Adminhtml\System\Config\Form\Field;

class MessageQueueModeSelect extends \Magento\Framework\View\Element\Html\Select
{
/**
* @var \Werules\Chatbot\Block\Adminhtml\System\Config\Form\Field\MessageQueueModeList
*/
protected $_messageQueueModeList;

public function __construct(
\Werules\Chatbot\Block\Adminhtml\System\Config\Form\Field\MessageQueueModeList $messageQueueModeList,
\Magento\Backend\Block\Template\Context $context, array $data = array())
{
parent::__construct($context, $data);
$this->_messageQueueModeList = $messageQueueModeList;
}

public function _toHtml()
{
if (!$this->getOptions()) {
foreach ($this->_messageQueueModeList->toOptionArray() as $option) {
$this->addOption($option['value'], $option['label']);
}
}
return parent::_toHtml();
}

public function getName()
{
return $this->getInputName();
}
}
68 changes: 50 additions & 18 deletions Magento2/app/code/Werules/Chatbot/Block/Webhook/Index.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,26 +87,46 @@ public function requestHandler()

protected function messageHandler($messageObject)
{
$messageModel = $this->_messageModel->create();
$messageModel->setSenderId($messageObject->senderId);
$messageModel->setContent($messageObject->content);
$messageModel->setChatbotType($messageObject->chatType);
$messageModel->setContentType($messageObject->contentType);
$messageModel->setStatus($messageObject->status);
$messageModel->setDirection($messageObject->direction);
$messageModel->setMessagePayload($messageObject->messagePayload);
$messageModel->setChatMessageId($messageObject->chatMessageId);
$messageModel->setCreatedAt($messageObject->createdAt);
$messageModel->setUpdatedAt($messageObject->updatedAt);

try {
$messageModel->save();
} catch (\Magento\Framework\Exception\LocalizedException $e) {
return $this->_helper->getJsonErrorResponse();
// $messageModel = $this->_messageModel->create();
// $messageModel->setSenderId($messageObject->senderId);
// $messageModel->setContent($messageObject->content);
// $messageModel->setChatbotType($messageObject->chatType);
// $messageModel->setContentType($messageObject->contentType);
// $messageModel->setStatus($messageObject->status);
// $messageModel->setDirection($messageObject->direction);
// $messageModel->setMessagePayload($messageObject->messagePayload);
// $messageModel->setChatMessageId($messageObject->chatMessageId);
// $messageModel->setCreatedAt($messageObject->createdAt);
// $messageModel->setUpdatedAt($messageObject->updatedAt);

// try {
// $messageModel->save();
// } catch (\Magento\Framework\Exception\LocalizedException $e) {
// return $this->_helper->getJsonErrorResponse();
// }
$messageModel = $this->_helper->createIncomingMessage($messageObject);
if ($messageModel->getMessageId())
{
$messageQueueMode = $this->_helper->getQueueMessageMode();
if (($messageQueueMode == $this->_define::QUEUE_NONE) || ($messageQueueMode == $this->_define::QUEUE_NON_RESTRICTIVE))
{
$outgoingMessages = $this->_helper->processIncomingMessage($messageModel);
foreach ($outgoingMessages as $outgoingMessage)
{
$result = $this->_helper->processOutgoingMessage($outgoingMessage);
}
}
else if (($messageQueueMode == $this->_define::QUEUE_RESTRICTIVE) || ($messageQueueMode == $this->_define::QUEUE_SIMPLE_RESTRICTIVE))
{
$result = $this->_helper->processIncomingMessageQueueBySenderId($messageModel->getSenderId());
if ($result)
$result = $this->_helper->processOutgoingMessageQueueBySenderId($messageModel->getSenderId());
}
}
$result = $this->_helper->processMessage($messageModel->getMessageId());
else
return $this->_helper->getJsonErrorResponse();

return $this->_helper->getJsonSuccessResponse();
return $this->getJsonSuccessResponse();
}

public function getConfigValue($code)
Expand All @@ -119,6 +139,18 @@ protected function getJsonErrorResponse()
return $this->_helper->getJsonErrorResponse();
}

protected function getJsonSuccessResponse()
{
return $this->_helper->getJsonSuccessResponse();
}

protected function logPostData($data, $file = 'werules_chatbot.log')
{
$postLog = ($this->getConfigValue('werules_chatbot_general/general/enable_post_log') == $this->_define::ENABLED);
if ($postLog)
$this->_helper->logger($data, $file);
}

// public function getDefine()
// {
// return $this->_define;
Expand Down
20 changes: 15 additions & 5 deletions Magento2/app/code/Werules/Chatbot/Block/Webhook/Messenger.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,13 @@ protected function processRequest()
else // process message
{
$messengerInstance = $this->getMessengerInstance();
$postLog = ($this->getConfigValue('werules_chatbot_general/general/enable_post_log') == $this->_define::ENABLED);
if ($postLog)
$this->_helper->logger($messengerInstance->getPostData(), 'werules_chatbot_messenger.log');
$this->logPostData($messengerInstance->getPostData(), 'werules_chatbot_messenger.log');

$messageObject = $this->createMessageObject($messengerInstance);
$result = $this->messageHandler($messageObject);
if (isset($messageObject->content))
$result = $this->messageHandler($messageObject);
else
$result = $this->getJsonSuccessResponse(); // return success to avoid receiving the same message again
}
// }
// else
Expand All @@ -108,18 +110,26 @@ protected function getMessengerInstance()
protected function createMessageObject($messenger)
{
$messageObject = new \stdClass();
$messageObject->senderId = $messenger->ChatID();
if ($messenger->Text())
$content = $messenger->Text();
else
$content = $messenger->getPostbackTitle();
if (!$content)
return $messageObject;

$messageObject->senderId = $messenger->ChatID();
$messageObject->content = $content;
$messageObject->status = $this->_define::PROCESSING;
$messageObject->direction = $this->_define::INCOMING;
$messageObject->chatType = $this->_define::MESSENGER_INT; // TODO
$messageObject->contentType = $this->_define::CONTENT_TEXT; // TODO
$messageObject->currentCommandDetails = $this->_define::CURRENT_COMMAND_DETAILS_DEFAULT; // TODO
$messageObject->messagePayload = $this->getMessengerPayload($messenger); // TODO
$messageObject->chatMessageId = $messenger->MessageID();
if ($messenger->getMessageTimestamp())
$messageObject->sentAt = (int)$messenger->getMessageTimestamp();
else
$messageObject->sentAt = time();
$datetime = date('Y-m-d H:i:s');
$messageObject->createdAt = $datetime;
$messageObject->updatedAt = $datetime;
Expand Down
71 changes: 55 additions & 16 deletions Magento2/app/code/Werules/Chatbot/Cron/Worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,29 +61,68 @@ public function execute()
// ->addFieldToFilter('status', array('eq' => '0'));
// }
// }
$processingLimit = $this->_define::SECONDS_IN_MINUTE * 3;
$messageCollection = $this->_messageModel->getCollection()
->addFieldToFilter('status', array('neq' => $this->_define::PROCESSED))
;
foreach ($messageCollection as $message) {
$result = true;
$datetime = date('Y-m-d H:i:s');
if ($message->getStatus() == $this->_define::NOT_PROCESSED)
if ($this->_helper->getConfigValue('werules_chatbot_danger/general/clear_message_pending') == $this->_define::CLEAR_MESSAGE_QUEUE)
{
$messageSenderId = $this->_helper->getConfigValue('werules_chatbot_danger/general/clear_message_sender_id');
if ($messageSenderId)
{
$message->updateMessageStatus($this->_define::PROCESSING);
$result = $this->_helper->processMessage($message->getMessageId());
$messageCollection = $this->_messageModel->getCollection()
->addFieldToFilter('sender_id', array('eq' => $messageSenderId))
;
}
else if (($message->getStatus() == $this->_define::PROCESSING) && ((strtotime($datetime) - strtotime($message->getUpdatedAt())) > $processingLimit))
else
$messageCollection = $this->_messageModel->getCollection();

foreach ($messageCollection as $message)
{
// if a message is in 'processing' status for more than 3 minutes, try to reprocess it
// $message->updateMessageStatus($this->_define::PROCESSING); // already on 'processing' status
$result = $this->_helper->processMessage($message->getMessageId());
$message->updateMessageStatus($this->_define::PROCESSED);
}

if (!$result)
$message->updateMessageStatus($this->_define::NOT_PROCESSED);
$this->_helper->setConfigValue('werules_chatbot_danger/general/clear_message_pending', $this->_define::DONT_CLEAR_MESSAGE_QUEUE);
}

$messageQueueMode = $this->_helper->getQueueMessageMode();
if (($messageQueueMode == $this->_define::QUEUE_NONE) || ($messageQueueMode == $this->_define::QUEUE_NON_RESTRICTIVE))
{
$processingLimit = $this->_define::QUEUE_PROCESSING_LIMIT;
$messageCollection = $this->_messageModel->getCollection()
->addFieldToFilter('status', array('neq' => $this->_define::PROCESSED))
;
foreach ($messageCollection as $message)
{
$result = array();
$datetime = date('Y-m-d H:i:s');
if ( // if not processed neither in the processing queue limit
($message->getStatus() == $this->_define::NOT_PROCESSED) ||
(($message->getStatus() == $this->_define::PROCESSING) && ((strtotime($datetime) - strtotime($message->getUpdatedAt())) > $processingLimit))
)
{
// $message->updateMessageStatus($this->_define::PROCESSING);
if ($message->getDirection() == $this->_define::INCOMING)
$result = $this->_helper->processIncomingMessage($message);
else //if ($message->getDirection() == $this->_define::OUTGOING)
$result = $this->_helper->processOutgoingMessage($message);
}

if (!$result)
$message->updateMessageStatus($this->_define::NOT_PROCESSED);
// else
// $this->_logger->addInfo('Result of MessageID ' . $message->getMessageId() . ':\n' . var_export($result, true));
}
}
else if (($messageQueueMode == $this->_define::QUEUE_RESTRICTIVE) || ($messageQueueMode == $this->_define::QUEUE_SIMPLE_RESTRICTIVE))
{
// get all messages with different sender_id values (aka list of all sender_id)
$uniqueMessageCollection = $this->_messageModel->getCollection()->distinct(true);
$uniqueMessageCollection->getSelect()->group('sender_id');

foreach ($uniqueMessageCollection as $message)
{
// foreach unique sender_id, process all their queue messages
$result = $this->_helper->processIncomingMessageQueueBySenderId($message->getSenderId());
if ($result)
$result = $this->_helper->processOutgoingMessageQueueBySenderId($message->getSenderId());
}
}
// $this->_logger->addInfo("Chatbot Cronjob was executed.");
}
Expand Down
Loading

0 comments on commit fa4e4f3

Please sign in to comment.