From d807406da3a807772239a7ae3eff841e99fdb907 Mon Sep 17 00:00:00 2001 From: tuyennn Date: Thu, 28 Mar 2019 19:20:20 +0700 Subject: [PATCH 1/3] [TASK] Add Cron for auto post --- Block/Adminhtml/System/Config/Hashtag.php | 19 +- Controller/Adminhtml/Manage/MassPost.php | 82 +-- Controller/Adminhtml/Manage/Post.php | 72 +-- .../System/Config/TestConnection.php | 60 +- Cron/SchedulePost.php | 181 ++++++ Helper/Data.php | 519 ++++++------------ Model/Config.php | 338 ++++++++++++ Model/Config/Backend/Cron.php | 116 ++++ Model/Instagram.php | 22 +- Observer/Catalog/ProductSaveAfter.php | 74 +-- Plugin/Model/Menu/BuilderPlugin.php | 14 +- .../Listing/Columns/ProductActions.php | 30 +- etc/adminhtml/system.xml | 49 +- etc/config.xml | 12 +- etc/crontab.xml | 8 + 15 files changed, 1097 insertions(+), 499 deletions(-) create mode 100644 Cron/SchedulePost.php create mode 100644 Model/Config.php create mode 100644 Model/Config/Backend/Cron.php create mode 100644 etc/crontab.xml diff --git a/Block/Adminhtml/System/Config/Hashtag.php b/Block/Adminhtml/System/Config/Hashtag.php index b8707c5..5661711 100644 --- a/Block/Adminhtml/System/Config/Hashtag.php +++ b/Block/Adminhtml/System/Config/Hashtag.php @@ -2,25 +2,28 @@ namespace GhoSter\AutoInstagramPost\Block\Adminhtml\System\Config; -class Hashtag extends \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray +use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray; +use GhoSter\AutoInstagramPost\Block\Adminhtml\System\Config\Hashtag\Activation; + +class Hashtag extends AbstractFieldArray { /** - * @var $_attributesRenderer \GhoSter\AutoInstagramPost\Block\Adminhtml\System\Config\Hashtag\Activation + * @var $_attributesRenderer Activation */ protected $_activation; /** * Get activation options. * - * @return \GhoSter\AutoInstagramPost\Block\Adminhtml\System\Config\Hashtag\Activation + * @return Activation * @throws \Magento\Framework\Exception\LocalizedException */ protected function _getActivationRenderer() { if (!$this->_activation) { $this->_activation = $this->getLayout()->createBlock( - '\GhoSter\AutoInstagramPost\Block\Adminhtml\System\Config\Hashtag\Activation', + Activation::class, '', ['data' => ['is_render_to_js_template' => true]] ); @@ -34,7 +37,13 @@ protected function _getActivationRenderer() */ protected function _prepareToRender() { - $this->addColumn('hashtag', ['label' => __('Hashtag Value'), 'renderer' => false]); + $this->addColumn( + 'hashtag', + [ + 'label' => __('Hashtag Value'), + 'renderer' => false + ] + ); $this->addColumn( 'status', [ diff --git a/Controller/Adminhtml/Manage/MassPost.php b/Controller/Adminhtml/Manage/MassPost.php index 39fd71c..584ab24 100644 --- a/Controller/Adminhtml/Manage/MassPost.php +++ b/Controller/Adminhtml/Manage/MassPost.php @@ -11,21 +11,25 @@ use Magento\Framework\Exception\NotFoundException; use Magento\Ui\Component\MassAction\Filter; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; -use GhoSter\AutoInstagramPost\Model\Logger; +use GhoSter\AutoInstagramPost\Model\Logger as InstagramLogger; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; +use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; class MassPost extends Action { /** - * @var \GhoSter\AutoInstagramPost\Helper\Data + * @var InstagramHelper */ protected $helper; + /** @var InstagramConfig */ + protected $config; + /** - * @var Logger + * @var InstagramLogger */ - protected $_logger; - + protected $logger; /** * @var array @@ -37,18 +41,6 @@ class MassPost extends Action */ protected $_instagram; - /** - * @var \Magento\Framework\App\Filesystem\DirectoryList - */ - protected $_directoryList; - - /** - * Store manager - * - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $_storeManager; - /** * @var ProductFactory */ @@ -71,26 +63,40 @@ class MassPost extends Action */ protected $collectionFactory; - + /** + * MassPost constructor. + * + * @param Action\Context $context + * @param InstagramConfig $config + * @param InstagramHelper $helper + * @param ProductFactory $productFactory + * @param Instagram $instagram + * @param ImageProcessor $imageProcessor + * @param Filter $filter + * @param CollectionFactory $collectionFactory + * @param InstagramLogger $logger + */ public function __construct( Action\Context $context, - \GhoSter\AutoInstagramPost\Helper\Data $helper, + InstagramConfig $config, + InstagramHelper $helper, ProductFactory $productFactory, Instagram $instagram, ImageProcessor $imageProcessor, Filter $filter, CollectionFactory $collectionFactory, - Logger $logger + InstagramLogger $logger ) { + $this->config = $config; $this->helper = $helper; $this->productFactory = $productFactory; $this->_instagram = $instagram; $this->imageProcessor = $imageProcessor; - $this->_account = $this->helper->getAccountInformation(); + $this->_account = $this->config->getAccountInformation(); $this->filter = $filter; $this->collectionFactory = $collectionFactory; - $this->_logger = $logger; + $this->logger = $logger; parent::__construct($context); } @@ -105,8 +111,6 @@ public function execute() $productIds = $this->getRequest()->getParam('selected'); if (!empty($productIds)) { - $storeId = (int)$this->getRequest()->getParam('store', 0); - $productCollection = $this->collectionFactory->create() ->addAttributeToSelect('*') ->addAttributeToFilter('entity_id', ['in' => $productIds]); @@ -115,15 +119,17 @@ public function execute() if (!empty($this->_account) && isset($this->_account['username']) && isset($this->_account['password'])) { - $this->_getInstagram()->setUser( + $this->getInstagram()->setUser( $this->_account['username'], $this->_account['password'] ); } - if (!$this->_getInstagram()->login()) { - $this->messageManager->addErrorMessage(__('Unauthorized Instagram Account, check your user/password setting')); + if (!$this->getInstagram()->login()) { + $this->messageManager->addErrorMessage( + __('Unauthorized Instagram Account, check your user/password setting') + ); } $productUploaded = $errorNumber = 0; @@ -134,11 +140,16 @@ public function execute() if ($image) { $caption = $this->helper->getInstagramPostDescription($product); - $result = $this->_getInstagram()->uploadPhoto($image, $caption); + + $result = $this->getInstagram() + ->uploadPhoto( + $image, + $caption + ); if (empty($result)) { $errorNumber++; - $this->_logger->recordInstagramLog( + $this->logger->recordInstagramLog( $product, [], InstagramItem::TYPE_ERROR @@ -149,7 +160,7 @@ public function execute() && $result['status'] === Instagram::STATUS_OK ) { $productUploaded++; - $this->_logger->recordInstagramLog( + $this->logger->recordInstagramLog( $product, $result, InstagramItem::TYPE_SUCCESS @@ -178,7 +189,10 @@ public function execute() } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { - $this->messageManager->addExceptionMessage($e, __('Something went wrong while posting to Instagram.')); + $this->messageManager->addExceptionMessage( + $e, + __('Something went wrong while posting to Instagram.') + ); } return $resultRedirect->setPath('*/*/'); @@ -188,11 +202,9 @@ public function execute() } /** - * Get Instagram Client - * - * @return \GhoSter\AutoInstagramPost\Model\Instagram + * @return Instagram */ - private function _getInstagram() + public function getInstagram(): Instagram { return $this->_instagram; } diff --git a/Controller/Adminhtml/Manage/Post.php b/Controller/Adminhtml/Manage/Post.php index 51e483e..144687f 100644 --- a/Controller/Adminhtml/Manage/Post.php +++ b/Controller/Adminhtml/Manage/Post.php @@ -8,19 +8,24 @@ use GhoSter\AutoInstagramPost\Model\Item as InstagramItem; use Magento\Catalog\Model\ProductFactory; use GhoSter\AutoInstagramPost\Model\ImageProcessor; -use GhoSter\AutoInstagramPost\Model\Logger; +use GhoSter\AutoInstagramPost\Model\Logger as InstagramLogger; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; +use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; class Post extends Action { /** - * @var \GhoSter\AutoInstagramPost\Helper\Data + * @var InstagramHelper */ protected $helper; + /** @var InstagramConfig */ + protected $config; + /** - * @var Logger + * @var InstagramLogger */ - protected $_logger; + protected $logger; /** * @var array @@ -32,18 +37,6 @@ class Post extends Action */ protected $_instagram; - /** - * @var \Magento\Framework\App\Filesystem\DirectoryList - */ - protected $_directoryList; - - /** - * Store manager - * - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $_storeManager; - /** * @var ProductFactory */ @@ -55,21 +48,34 @@ class Post extends Action protected $imageProcessor; + /** + * Post constructor. + * + * @param Action\Context $context + * @param InstagramConfig $config + * @param InstagramHelper $helper + * @param ProductFactory $productFactory + * @param Instagram $instagram + * @param ImageProcessor $imageProcessor + * @param InstagramLogger $logger + */ public function __construct( Action\Context $context, - \GhoSter\AutoInstagramPost\Helper\Data $helper, + InstagramConfig $config, + InstagramHelper $helper, ProductFactory $productFactory, Instagram $instagram, ImageProcessor $imageProcessor, - Logger $logger + InstagramLogger $logger ) { + $this->config = $config; $this->helper = $helper; $this->productFactory = $productFactory; $this->_instagram = $instagram; $this->imageProcessor = $imageProcessor; - $this->_logger = $logger; - $this->_account = $this->helper->getAccountInformation(); + $this->logger = $logger; + $this->_account = $this->config->getAccountInformation(); parent::__construct($context); } @@ -93,25 +99,29 @@ public function execute() if (!empty($this->_account) && isset($this->_account['username']) && isset($this->_account['password'])) { - $this->_getInstagram() + $this->getInstagram() ->setUser( $this->_account['username'], $this->_account['password'] ); } - if (!$this->_getInstagram()->login()) { + if (!$this->getInstagram()->login()) { $this->messageManager->addErrorMessage(__('Unauthorized Instagram Account, check your user/password setting')); } - $result = $this->_getInstagram()->uploadPhoto($image, $caption); + $result = $this->getInstagram() + ->uploadPhoto( + $image, + $caption + ); if (empty($result)) { $this->messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); } if (empty($result)) { - $this->_logger->recordInstagramLog( + $this->logger->recordInstagramLog( $product, [], InstagramItem::TYPE_ERROR @@ -128,7 +138,7 @@ public function execute() if (isset($result['status']) && $result['status'] === Instagram::STATUS_OK ) { - $this->_logger->recordInstagramLog( + $this->logger->recordInstagramLog( $product, $result, InstagramItem::TYPE_SUCCESS @@ -148,7 +158,10 @@ public function execute() } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { - $this->messageManager->addExceptionMessage($e, __('Something went wrong while posting to Instagram.')); + $this->messageManager->addExceptionMessage( + $e, + __('Something went wrong while posting to Instagram.') + ); } return $resultRedirect->setPath('*/*/'); @@ -157,16 +170,13 @@ public function execute() } /** - * Get Instagram Client - * - * @return \GhoSter\AutoInstagramPost\Model\Instagram + * @return Instagram */ - private function _getInstagram() + public function getInstagram(): Instagram { return $this->_instagram; } - /** * Is the user allowed to view the blog post grid. * diff --git a/Controller/Adminhtml/System/Config/TestConnection.php b/Controller/Adminhtml/System/Config/TestConnection.php index 08f6713..cac05c4 100644 --- a/Controller/Adminhtml/System/Config/TestConnection.php +++ b/Controller/Adminhtml/System/Config/TestConnection.php @@ -5,7 +5,9 @@ use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\Controller\Result\JsonFactory; - +use GhoSter\AutoInstagramPost\Model\Instagram; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; +use Psr\Log\LoggerInterface; class TestConnection extends Action { @@ -13,32 +15,46 @@ class TestConnection extends Action protected $resultJsonFactory; /** - * @var \GhoSter\AutoInstagramPost\Model\Instagram + * @var Instagram */ protected $_instagram; + + /** @var InstagramConfig */ + protected $config; + /** - * @var \GhoSter\AutoInstagramPost\Helper\Data + * @var LoggerInterface */ - protected $_instagramHelper; + private $logger; /** - * @var \Psr\Log\LoggerInterface + * @var array */ - private $_logger; + private $account = []; + /** + * TestConnection constructor. + * + * @param Context $context + * @param JsonFactory $resultJsonFactory + * @param Instagram $instagram + * @param InstagramConfig $config + * @param LoggerInterface $logger + */ public function __construct( Context $context, JsonFactory $resultJsonFactory, - \GhoSter\AutoInstagramPost\Model\Instagram $instagram, - \GhoSter\AutoInstagramPost\Helper\Data $instagramHelper, - \Psr\Log\LoggerInterface $logger + Instagram $instagram, + InstagramConfig $config, + LoggerInterface $logger ) { $this->resultJsonFactory = $resultJsonFactory; $this->_instagram = $instagram; - $this->_instagramHelper = $instagramHelper; - $this->_logger = $logger; + $this->config = $config; + $this->logger = $logger; + $this->account = $this->config->getAccountInformation(); parent::__construct($context); } @@ -54,14 +70,18 @@ public function execute() /** @var \Magento\Framework\Controller\Result\Json $result */ $result = $this->resultJsonFactory->create(); - $account = $this->_instagramHelper->getAccountInformation(); + try { - $instagram = $this->getInstagram(); + if (!empty($this->account) + && isset($this->account['username']) + && isset($this->account['password'])) { - try { + $this->getInstagram() + ->setUser( + $this->account['username'], + $this->account['password'] + ); - if (!empty($account) && isset($account['username']) && isset($account['password'])) { - $instagram->setUser($account['username'], $account['password']); } else { $responseData = [ 'success' => false, @@ -71,7 +91,7 @@ public function execute() return $result->setData($responseData); } - if (!$instagram->login()) { + if (!$this->getInstagram()->login()) { $responseData = [ 'success' => false, 'message' => __('Unauthorized Instagram Account, check your user/password settings') @@ -95,11 +115,9 @@ public function execute() } /** - * Get Instagram Client - * - * @return \GhoSter\AutoInstagramPost\Model\Instagram + * @return Instagram */ - private function getInstagram() + public function getInstagram(): Instagram { return $this->_instagram; } diff --git a/Cron/SchedulePost.php b/Cron/SchedulePost.php new file mode 100644 index 0000000..339183c --- /dev/null +++ b/Cron/SchedulePost.php @@ -0,0 +1,181 @@ +instagramHelper = $instagramHelper; + $this->config = $config; + $this->instagram = $instagram; + $this->imageProcessor = $imageProcessor; + $this->logger = $logger; + $this->account = $this->config->getAccountInformation(); + $this->productCollection = $productCollectionFactory->create(); + } + + /** + * Execute the cron + */ + public function execute() + { + $limit = $this->config->getCronLimit(); + + if (!$limit) { + $limit = InstagramConfig::DEFAULT_LIMIT_CRON; + } + + try { + + $collection = $this->productCollection + ->addAttributeToFilter( + 'posted_toinstagram', + [ + 'or' => [ + 0 => ['is' => 0], + 1 => ['is' => new \Zend_Db_Expr('null')], + ] + ], + 'left' + ); + + $collection->getSelect()->limit($limit); + + if (!empty($this->account) + && isset($this->account['username']) + && isset($this->account['password'])) { + $this->getInstagram() + ->setUser( + $this->account['username'], + $this->account['password'] + ); + } + + foreach ($collection as $product) { + + $image = $this->imageProcessor->processBaseImage($product); + + if ($image) { + + $caption = $this->instagramHelper + ->getInstagramPostDescription($product); + + try { + + $result = $this->getInstagram() + ->uploadPhoto( + $image, + $caption + ); + + if (empty($result)) { + $this->logger->recordInstagramLog( + $product, + [], + InstagramItem::TYPE_ERROR + ); + } + + if ($result['status'] === Instagram::STATUS_FAIL) { + $this->logger->recordInstagramLog( + $product, + $result, + InstagramItem::TYPE_ERROR + ); + + } + + if ($result['status'] === Instagram::STATUS_OK) { + $this->logger->recordInstagramLog( + $product, + $result, + InstagramItem::TYPE_SUCCESS + ); + + } + + + } catch (\Exception $e) { + + } + } + } + + } catch (\Exception $e) { + } + + return; + } + + + /** + * @return Instagram + */ + public function getInstagram(): Instagram + { + return $this->instagram; + } +} \ No newline at end of file diff --git a/Helper/Data.php b/Helper/Data.php index 67719e3..2f4db07 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -3,399 +3,234 @@ namespace GhoSter\AutoInstagramPost\Helper; use Magento\Framework\App\Helper\AbstractHelper; -use Magento\Store\Model\Store; -use Magento\Framework\Encryption\EncryptorInterface as Encryptor; +use Magento\Catalog\Model\Product; use Magento\Catalog\Model\ProductFactory; -use Magento\Catalog\Model\CategoryFactory; -use Magento\Framework\Escaper; -use GhoSter\AutoInstagramPost\Model\Serialize\Serializer; +use Magento\Catalog\Model\ResourceModel\Category\Collection as CategoryCollection; +use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory; +use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\Filesystem; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; +use Psr\Log\LoggerInterface; class Data extends AbstractHelper { - const XML_PATH_ENABLED_MODULE = 'auto_instagram_post/general/enable'; - const XML_PATH_INSTAGRAM_USER = 'auto_instagram_post/general/username'; - const XML_PATH_INSTAGRAM_PASSWORD = 'auto_instagram_post/general/password'; - const XML_PATH_DEFAULT_IMAGE = 'auto_instagram_post/general/upload_image_id'; - const XML_PATH_ENABLE_OBSERVER = 'auto_instagram_post/general/enable_observer'; - - const XML_PATH_ENABLE_HASHTAG_DESCRIPTION = 'auto_instagram_post/comment_hashtag/enable'; - const XML_PATH_ENABLE_PRODUCT_DESCRIPTION = 'auto_instagram_post/comment_hashtag/product_description'; - const XML_PATH_ENABLE_CATEGORY_HASHTAG = 'auto_instagram_post/comment_hashtag/category_hashtag'; - const XML_PATH_ENABLE_CUSTOM_HASHTAG = 'auto_instagram_post/comment_hashtag/enable_custom'; - const XML_PATH_CUSTOM_HASHTAG = 'auto_instagram_post/comment_hashtag/hashtag'; - const XML_PATH_DESCRIPTION_TEMPLATE = 'auto_instagram_post/comment_hashtag/description_template'; - const XML_INSTAGRAM_CHARACTER_LIMIT = 2200; - const XML_INSTAGRAM_HASHTAG_LIMIT = 30; - const XML_CATEGORY_HASHTAG_LIMIT = 10; + const DEFAULT_INSTAGRAM_CHARACTER_LIMIT = 2200; + const DEFAULT_INSTAGRAM_HASHTAG_LIMIT = 30; + const DEFAULT_CATEGORY_HASHTAG_LIMIT = 10; const SPACE_STRING = ' '; + /** @var DirectoryList */ + protected $directoryList; - /** - * Store manager - * - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $_storeManager; - - /** - * @var \Magento\Framework\Encryption\EncryptorInterface - */ - protected $_encryptor; + /** @var Filesystem\Directory\WriteInterface */ + protected $mediaWriteDirectory; - /** - * @var \Magento\Framework\App\Filesystem\DirectoryList - */ - protected $directory_list; + /** @var Filesystem */ + protected $filesystem; - /** - * @var \Magento\Framework\Filesystem $filesystem - */ - protected $_filesystem; + /** @var \Magento\Framework\Image\AdapterFactory */ + protected $imageFactory; - /** - * @var \Magento\Framework\Image\AdapterFactory - */ - protected $_imageFactory; - - /** - * @var ProductFactory - */ + /** @var ProductFactory */ protected $productFactory; /** - * @var CategoryFactory + * @var CategoryCollectionFactory */ - protected $categoryFactory; + protected $categoryCollectionFactory; - /** - * @var Escaper - */ - protected $_escaper; + /** @var InstagramConfig */ + protected $config; + + /** @var LoggerInterface */ + protected $logger; /** - * @var Serializer + * Data constructor. + * @param \Magento\Framework\App\Helper\Context $context + * @param DirectoryList $directoryList + * @param Filesystem $filesystem + * @param \Magento\Framework\Image\AdapterFactory $imageFactory + * @param ProductFactory $productFactory + * @param CategoryCollectionFactory $categoryCollectionFactory + * @param InstagramConfig $config + * @param LoggerInterface $logger + * @throws \Magento\Framework\Exception\FileSystemException */ - protected $_serializer; - public function __construct( \Magento\Framework\App\Helper\Context $context, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\App\Filesystem\DirectoryList $directory_list, - \Magento\Framework\Filesystem $filesystem, + DirectoryList $directoryList, + Filesystem $filesystem, \Magento\Framework\Image\AdapterFactory $imageFactory, - Encryptor $encryptor, - Escaper $_escaper, ProductFactory $productFactory, - CategoryFactory $categoryFactory, - Serializer $serializer + CategoryCollectionFactory $categoryCollectionFactory, + InstagramConfig $config, + LoggerInterface $logger ) { - $this->_storeManager = $storeManager; - $this->_encryptor = $encryptor; - $this->directory_list = $directory_list; - $this->_filesystem = $filesystem; - $this->_imageFactory = $imageFactory; + $this->directoryList = $directoryList; + $this->filesystem = $filesystem; + $this->imageFactory = $imageFactory; $this->productFactory = $productFactory; - $this->categoryFactory = $categoryFactory; - $this->_escaper = $_escaper; - $this->_serializer = $serializer; + $this->categoryCollectionFactory = $categoryCollectionFactory; + $this->config = $config; + $this->mediaWriteDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); + $this->logger = $logger; parent::__construct($context); } /** - * How to resize Your image before upload to Instagram + * Resize befor uploading * * @param $imageDir - * @param null $image + * @param $image * @param $width * @param null $height * @param int $quality - * @return mixed|string + * @return bool|string * @throws \Magento\Framework\Exception\FileSystemException */ - public function getResizeImage($imageDir, $image = null, $width, $height = null, $quality = 100) + public function getResizeImage( + $imageDir, + $image, + $width, + $height = null, + $quality = 100 + ) { if ($height) { - $imageResized = $this->directory_list->getPath('media') + $imageResizedDir = $this->directoryList->getPath('media') . DIRECTORY_SEPARATOR . 'catalog' . DIRECTORY_SEPARATOR . 'product' - . DIRECTORY_SEPARATOR . 'product_resized' - . DIRECTORY_SEPARATOR . $width . 'x' . $height . $image; + . DIRECTORY_SEPARATOR . 'instagram_processed' + . DIRECTORY_SEPARATOR . $width . 'x' . $height; } else { - $imageResized = $this->directory_list->getPath('media') + $imageResizedDir = $this->directoryList->getPath('media') . DIRECTORY_SEPARATOR . 'catalog' . DIRECTORY_SEPARATOR . 'product' - . DIRECTORY_SEPARATOR . 'product_resized' - . DIRECTORY_SEPARATOR . $width . $image; + . DIRECTORY_SEPARATOR . 'instagram_processed' + . DIRECTORY_SEPARATOR . $width; } - if (!file_exists($imageResized)): - $imageObj = $this->_imageFactory->create(); - $imageObj->open($imageDir); - $imageObj->constrainOnly(true); - $imageObj->keepAspectRatio(true); - $imageObj->keepFrame(true); - $imageObj->backgroundColor(array(255, 255, 255)); - $imageObj->resize($width, $height); - $imageObj->save($imageResized); - endif; - - if (file_exists($imageResized)) { - $imageExts = explode('.', $imageResized); - if (strtolower($imageExts[count($imageExts) - 1]) == 'png') { - $realPng = $imageResized; - $imageResized = str_replace(array('.png', '.Png', '.pNg', '.pnG', '.PNg', '.PnG', '.pNG', '.PNG'), '.jpg', $imageResized); - if (!file_exists($imageResized)) { - $jpgImage = imagecreatefrompng($realPng); - $bg = imagecreatetruecolor(imagesx($jpgImage), imagesy($jpgImage)); - imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255)); - imagealphablending($bg, TRUE); - imagecopy($bg, $jpgImage, 0, 0, 0, 0, imagesx($jpgImage), imagesy($jpgImage)); - imagedestroy($jpgImage); - imagejpeg($bg, $imageResized, $quality); - imagedestroy($bg); - } - } - return $imageResized; + $imageResized = $imageResizedDir . $image; - } else { - return ''; - } - } + try { + if (!file_exists($imageResized)) { + $image = $this->imageFactory->create(); + $image->open($imageDir); + $image->constrainOnly(true); + $image->keepAspectRatio(true); + $image->keepFrame(true); + $image->backgroundColor(array(255, 255, 255)); + $image->resize($width, $height); + $image->save($imageResized); + } - /** - * Check if module enabled - * - * @param null|string|bool|int|Store $store - * @return bool - */ + if (file_exists($imageResized)) { + $extOriginal = strtolower(pathinfo($image, PATHINFO_EXTENSION)); - public function isModuleEnabled($store = null) - { - if (empty($this->getUsernameInfo($store)) || empty($this->getPwdInfo($store))) { - return false; - } + if (!in_array($extOriginal, ['jpg', 'jpeg'])) { + $wrongImageFormat = $imageResized; - return (bool)$this->scopeConfig->getValue( - self::XML_PATH_ENABLED_MODULE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - ); - } + $imageResized = $imageResizedDir . str_replace($extOriginal, '.jpg', $image); - /** - * Get Account Information from Configuration - * - * @param null|string|bool|int|Store $store - * @return array - */ - public function getAccountInformation($store = null) - { - if (empty($this->getUsernameInfo($store)) || empty($this->getPwdInfo($store))) { - return null; - } - - return [ - 'username' => $this->getUsernameInfo($store), - 'password' => $this->getPwdInfo($store) - ]; - } - - /** - * Get Username - * @param null $store - * @return mixed - */ - public function getUsernameInfo($store = null) - { - return $this->scopeConfig->getValue( - self::XML_PATH_INSTAGRAM_USER, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store); - } - - /** - * Get Password - * - * @param null $store - * @return mixed - */ - public function getPwdInfo($store = null) - { - return $this->scopeConfig->getValue( - self::XML_PATH_INSTAGRAM_PASSWORD, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store); - } + $this->_convertWrongFormatImage( + $imageResized, + $wrongImageFormat, + $extOriginal, + $quality + ); + } - /** - * Get Default Image URL Path - * - * @param null $store - * @return string - * @throws \Magento\Framework\Exception\FileSystemException - */ - public function getDefaultImage($store = null) - { - $uploadDir = \GhoSter\AutoInstagramPost\Model\Config\Backend\Image::UPLOAD_DIR; + return $imageResized; + } - $image = $this->scopeConfig->getValue( - self::XML_PATH_DEFAULT_IMAGE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store); + return false; - if (!$image) { - return ''; + } catch (\Magento\Framework\Exception\FileSystemException $e) { + $this->logger->critical($e); + return false; } - $imagePath = $this->directory_list->getPath('media') - . DIRECTORY_SEPARATOR . $uploadDir - . DIRECTORY_SEPARATOR . $image; - - return $imagePath; - } - - /** - * Auto Observer after product saved - * - * @param null $store - * @return bool - */ - public function isObserverEnabled($store = null) - { - return (bool)$this->scopeConfig->getValue( - self::XML_PATH_ENABLE_OBSERVER, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - ); - } - - /** - * Check if Hashtag was enabled - * - * @param null $store - * @return mixed - */ - public function isEnableHashtag($store = null) - { - return (bool)$this->scopeConfig->getValue( - self::XML_PATH_ENABLE_HASHTAG_DESCRIPTION, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - ); } - /** - * Check if Custom Hashtag was enabled + * Convert Non JPG format * - * @param null $store - * @return mixed + * @param $convertedImage + * @param $sourceImage + * @param $imageExt + * @param int $quality */ - public function isEnableCustomHashtag($store = null) + private function _convertWrongFormatImage( + $convertedImage, + $sourceImage, + $imageExt, + $quality = 100 + ) { - return (bool)$this->scopeConfig->getValue( - self::XML_PATH_ENABLE_CUSTOM_HASHTAG, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - ); - } - /** - * Check if Hashtag follows Parent Category - * @param null $store - * @return mixed - */ - public function isEnableCategoryHashtag($store = null) - { - return (bool)$this->scopeConfig->getValue( - self::XML_PATH_ENABLE_CATEGORY_HASHTAG, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - ); - } + if (!file_exists($convertedImage)) { + switch ($imageExt) { + case 'jpg': + case 'jpeg': + $jpgImage = imagecreatefromjpeg($sourceImage); + break; + case 'png': + $jpgImage = imagecreatefrompng($sourceImage); + break; + case 'gif': + $jpgImage = imagecreatefromgif($sourceImage); + break; + case 'bmp': + $jpgImage = imagecreatefrombmp($sourceImage); + break; + } - /** - * Check if Caption included Product Desc - * - * @param null $store - * @return mixed - */ - public function isEnableProductDescription($store = null) - { - return (bool)$this->scopeConfig->getValue( - self::XML_PATH_ENABLE_PRODUCT_DESCRIPTION, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - ); + $trueColorImage = imagecreatetruecolor(imagesx($jpgImage), imagesy($jpgImage)); + imagefill($trueColorImage, 0, 0, imagecolorallocate($trueColorImage, 255, 255, 255)); + imagealphablending($trueColorImage, true); + imagecopy($trueColorImage, $jpgImage, 0, 0, 0, 0, imagesx($jpgImage), imagesy($jpgImage)); + imagedestroy($jpgImage); + imagejpeg($trueColorImage, $convertedImage, $quality); + imagedestroy($trueColorImage); + } } /** - * Get Custom Tags + * Get Category Tags * - * @param null $store + * @param $product Product * @return string */ - public function getCustomHashHashtags($store = null) + public function getCategoriesHashtagsHtml($product) { - $hashTagsStripped = []; $html = ''; - $hashTagConfig = $this->scopeConfig->getValue( - self::XML_PATH_CUSTOM_HASHTAG, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - ); + $hashTagsStrippedData = []; - if ($hashTagConfig && $this->isEnableHashtag() && $this->isEnableCustomHashtag()) { - $hashTags = $this->_serializer->unserialize($hashTagConfig); + if ($this->config->isEnableCategoryHashtag() && $this->config->isEnableHashtag()) { - if (is_array($hashTags)) { - foreach ($hashTags as $key => $hashTag) { - $hashTagsStripped[$key]['hashtag'] = strtolower(preg_replace('/\s+/', '', $hashTag['hashtag'])); - $hashTagsStripped[$key]['status'] = $hashTag['status']; + try { - } - } - } + /** @var $collection CategoryCollection */ + $collection = $this->categoryCollectionFactory->create(); + $collection->addAttributeToSelect('name'); + $collection->addAttributeToFilter('entity_id', $product->getCategoryIds()); - if (!empty($hashTagsStripped)) { - foreach ($hashTagsStripped as $hashTag) { - if ($hashTag['status']) { - $html .= '#' . $hashTag['hashtag'] . self::SPACE_STRING; + $i = 1; + foreach ($collection as $category) { + $hashTagsStrippedData[] = strtolower(preg_replace('/\s+/', '', $category->getName())); + if ($i++ == self::DEFAULT_CATEGORY_HASHTAG_LIMIT) break; } - } - } - return $html; - } + } catch (\Exception $e) { - /** - * Get Category Tags - * - * @param $_product \Magento\Catalog\Model\Product - * @return string - */ - public function getCategoriesHashtags($_product) - { - - $hashTagsStripped = []; - $html = ''; - - if ($this->isEnableCategoryHashtag() && $this->isEnableHashtag()) { - - $categoryIds = $_product->getCategoryIds(); - $i = 1; - if (count($categoryIds)) { - foreach ($categoryIds as $categoryId) { - $_category = $this->categoryFactory->create()->load($categoryId); - $hashTagsStripped[] = strtolower(preg_replace('/\s+/', '', $_category->getName())); - if ($i++ == self::XML_CATEGORY_HASHTAG_LIMIT) break; - } } + } if (!empty($hashTagsStripped)) { @@ -409,58 +244,45 @@ public function getCategoriesHashtags($_product) /** - * @param $_product \Magento\Catalog\Model\Product + * @param $product Product * @return string */ - public function getProductDescription($_product) + public function getProductDescription($product) { - return strip_tags($_product->getDescription()); - } - - /** - * @param null $store - * @return array|string - */ - public function getInstagramPostTemplate($store = null) - { - return $this->_escaper->escapeHtml($this->scopeConfig->getValue( - self::XML_PATH_DESCRIPTION_TEMPLATE, - \Magento\Store\Model\ScopeInterface::SCOPE_STORE, - $store - )); + return strip_tags($product->getDescription()); } /** * Get Final Caption for Instagram Post * - * @param $_product \Magento\Catalog\Model\Product + * @param $product Product * @return string */ - public function getInstagramPostDescription($_product = null) + public function getInstagramPostDescription($product) { $html = ''; - $stringTemplate = $this->getInstagramPostTemplate(); + $stringTemplate = $this->config->getInstagramPostTemplate(); if (preg_match_all("~\{\{\s*(.*?)\s*\}\}~", $stringTemplate, $matches)) { - if(isset($matches[1]) && is_array($matches[1])) { + if (isset($matches[1]) && is_array($matches[1])) { foreach ($matches[1] as $key => $match) { - $addOnSpace = $key !== 0 ? self::SPACE_STRING: ''; + $addOnSpace = $key !== 0 ? self::SPACE_STRING : ''; switch ($match) { case 'CUSTOMHASTAG': - $html .= $addOnSpace . $this->getCustomHashHashtags(); + $html .= $addOnSpace . $this->getCustomHashHashtagsHtml(); break; case 'CATEGORYHASHTAG': - $html .= $addOnSpace . $this->getCategoriesHashtags($_product); + $html .= $addOnSpace . $this->getCategoriesHashtagsHtml($product); break; case 'PRODUCTDESC': - $html .= $addOnSpace . $this->getProductDescription($_product); + $html .= $addOnSpace . $this->getProductDescription($product); break; case 'PRODUCTNAME': - $html .= $addOnSpace . $_product->getName(); + $html .= $addOnSpace . $product->getName(); break; case 'PRODUCTLINK': - $html .= $addOnSpace . $_product->getProductUrl(); + $html .= $addOnSpace . $product->getProductUrl(); break; default: break; @@ -468,7 +290,30 @@ public function getInstagramPostDescription($_product = null) } } } else { - $html .= $_product->getName(); + $html .= $product->getName(); + } + + return $html; + } + + /** + * Get Custom Tags + * + * @param null $store + * @return string + */ + public function getCustomHashHashtagsHtml($store = null) + { + $html = ''; + + $hashTagsStripped = $this->config->getCustomHashHashtags(); + + if (!empty($hashTagsStripped)) { + foreach ($hashTagsStripped as $hashTag) { + if ($hashTag['status']) { + $html .= '#' . $hashTag['hashtag'] . self::SPACE_STRING; + } + } } return $html; diff --git a/Model/Config.php b/Model/Config.php new file mode 100644 index 0000000..011e782 --- /dev/null +++ b/Model/Config.php @@ -0,0 +1,338 @@ +scopeConfig = $scopeConfig; + $this->storeManager = $storeManager; + $this->encryptor = $encryptor; + $this->escaper = $escaper; + $this->directoryList = $directoryList; + $this->serializer = $serializer; + } + + /** + * Check if module enabled + * + * @param null|string|bool|int|Store $store + * @return bool + */ + + public function isEnabled($store = null) + { + if (empty($this->getUsernameInfo($store)) + || empty($this->getPwdInfo($store))) { + return false; + } + + return (bool)$this->scopeConfig->getValue( + static::XML_PATH_ENABLED_MODULE, + ScopeInterface::SCOPE_STORE, + $store + ); + } + + /** + * Get Username + * + * @param null $store + * @return mixed + */ + public function getUsernameInfo($store = null) + { + return $this->scopeConfig->getValue( + self::XML_PATH_INSTAGRAM_USER, + ScopeInterface::SCOPE_STORE, + $store); + } + + /** + * Get Password + * + * @param null $store + * @return mixed + */ + public function getPwdInfo($store = null) + { + return $this->scopeConfig->getValue( + self::XML_PATH_INSTAGRAM_PASSWORD, + ScopeInterface::SCOPE_STORE, + $store); + } + + /** + * Get Account Information from Configuration + * + * @param null|string|bool|int|Store $store + * @return array + */ + public function getAccountInformation($store = null) + { + if (empty($this->getUsernameInfo($store)) + || empty($this->getPwdInfo($store))) { + return null; + } + + return [ + 'username' => $this->getUsernameInfo($store), + 'password' => $this->getPwdInfo($store) + ]; + } + + /** + * Get Default Image URL Path + * + * @param null $store + * @return string + * @throws \Magento\Framework\Exception\FileSystemException + */ + public function getDefaultImage($store = null) + { + $uploadDir = InstagramDefaultImage::UPLOAD_DIR; + + $image = $this->scopeConfig->getValue( + self::XML_PATH_DEFAULT_IMAGE, + ScopeInterface::SCOPE_STORE, + $store + ); + + if (!$image) { + return ''; + } + + $imagePath = $this->directoryList->getPath('media') + . DIRECTORY_SEPARATOR . $uploadDir + . DIRECTORY_SEPARATOR . $image; + + return $imagePath; + } + + /** + * Auto Observer after product saved + * + * @param $store + * @return bool + */ + public function isObserverEnabled($store = null) + { + return (bool)$this->scopeConfig->getValue( + self::XML_PATH_ENABLE_OBSERVER, + ScopeInterface::SCOPE_STORE, + $store + ); + } + + /** + * Check if Hashtag was enabled + * + * @param null $store + * @return mixed + */ + public function isEnableHashtag($store = null) + { + return (bool)$this->scopeConfig->getValue( + self::XML_PATH_COMMENT_ENABLED, + ScopeInterface::SCOPE_STORE, + $store + ); + } + + /** + * Check if Hashtag follows Parent Category + * @param null $store + * @return mixed + */ + public function isEnableCategoryHashtag($store = null) + { + return (bool)$this->scopeConfig->getValue( + self::XML_PATH_COMMENT_CATEGORY_HASHTAG, + ScopeInterface::SCOPE_STORE, + $store + ); + } + + /** + * Check if Custom Hashtag was enabled + * + * @param null $store + * @return mixed + */ + public function isEnableCustomHashtag($store = null) + { + return (bool)$this->scopeConfig->getValue( + self::XML_PATH_COMMENT_CUSTOM_HASHTAG_ENABLED, + ScopeInterface::SCOPE_STORE, + $store + ); + } + + /** + * Check if Caption included Product Desc + * + * @param null $store + * @return mixed + */ + public function isEnableProductDescription($store = null) + { + return (bool)$this->scopeConfig->getValue( + self::XML_PATH_COMMENT_PRODUCT_DESCRIPTION, + ScopeInterface::SCOPE_STORE, + $store + ); + } + + /** + * Get Custom Tags + * + * @param null $store + * @return array + */ + public function getCustomHashHashtags($store = null) + { + $hashTagsStripped = []; + + $hashTagConfig = $this->scopeConfig->getValue( + self::XML_PATH_COMMENT_CUSTOM_HASHTAG, + ScopeInterface::SCOPE_STORE, + $store + ); + + if ($hashTagConfig && $this->isEnableHashtag() && $this->isEnableCustomHashtag()) { + $hashTags = $this->serializer->unserialize($hashTagConfig); + + if (is_array($hashTags)) { + foreach ($hashTags as $key => $hashTag) { + $hashTagsStripped[$key]['hashtag'] = strtolower(preg_replace('/\s+/', '', $hashTag['hashtag'])); + $hashTagsStripped[$key]['status'] = $hashTag['status']; + + } + } + } + + return $hashTagsStripped; + } + + /** + * @param null $store + * @return array|string + */ + public function getInstagramPostTemplate($store = null) + { + return $this->escaper->escapeHtml($this->scopeConfig->getValue( + self::XML_PATH_COMMENT_TEMPLATE, + ScopeInterface::SCOPE_STORE, + $store + )); + } + + public function isCronEnabled($store = null) + { + return $this->escaper->escapeHtml($this->scopeConfig->getValue( + self::XML_PATH_CRON_ENABLED, + ScopeInterface::SCOPE_STORE, + $store + )); + } + + public function getCronTime() + { + return $this->escaper->escapeHtml($this->scopeConfig->getValue( + self::XML_PATH_CRON_TIME, + ScopeInterface::SCOPE_STORE + )); + } + + public function getCronFreq() + { + return $this->escaper->escapeHtml($this->scopeConfig->getValue( + self::XML_PATH_CRON_FREQUENCY, + ScopeInterface::SCOPE_STORE + )); + } + + public function getCronLimit(){ + return $this->escaper->escapeHtml($this->scopeConfig->getValue( + self::XML_PATH_CRON_LIMIT, + ScopeInterface::SCOPE_STORE + )); + } +} \ No newline at end of file diff --git a/Model/Config/Backend/Cron.php b/Model/Config/Backend/Cron.php new file mode 100644 index 0000000..ab3817a --- /dev/null +++ b/Model/Config/Backend/Cron.php @@ -0,0 +1,116 @@ +_runModelPath = $runModelPath; + $this->_configValueFactory = $configValueFactory; + parent::__construct( + $context, + $registry, + $config, + $cacheTypeList, + $resource, + $resourceCollection, + $data + ); + } + + /** + * Cron settings after save + * + * @return $this + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function afterSave() + { + $enabled = $this->getData(self::XML_PATH_BACKUP_ENABLED); + $time = $this->getData(self::XML_PATH_BACKUP_TIME); + $frequency = $this->getData(self::XML_PATH_BACKUP_FREQUENCY); + + $frequencyWeekly = SourceCronFrequency::CRON_WEEKLY; + $frequencyMonthly = SourceCronFrequency::CRON_MONTHLY; + + if ($enabled) { + $cronExprArray = [ + (int)$time[1], + (int)$time[0], + $frequency == $frequencyMonthly ? '1' : '*', + '*', + $frequency == $frequencyWeekly ? '1' : '*', + ]; + $cronExprString = join(' ', $cronExprArray); + } else { + $cronExprString = ''; + } + + try { + $this->_configValueFactory->create()->load( + self::CRON_STRING_PATH, + 'path' + )->setValue( + $cronExprString + )->setPath( + self::CRON_STRING_PATH + )->save(); + + } catch (\Exception $e) { + throw new LocalizedException(__('We can\'t save the Cron expression.')); + } + return parent::afterSave(); + } +} diff --git a/Model/Instagram.php b/Model/Instagram.php index c1897de..883cb8d 100644 --- a/Model/Instagram.php +++ b/Model/Instagram.php @@ -23,8 +23,8 @@ class Instagram protected $isLoggedIn = false; // Session status protected $rank_token; // Rank token protected $IGDataPath; // Data storage path - protected $directory_list; - protected $helper; + protected $directoryList; + protected $config; protected $logger; @@ -36,30 +36,30 @@ class Instagram * @param $helper \GhoSter\AutoInstagramPost\Helper\Data * Default folder to store data, you can change it. * - * @param \Magento\Framework\App\Filesystem\DirectoryList $directory_list - * @param \GhoSter\AutoInstagramPost\Helper\Data $helper + * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList + * @param \GhoSter\AutoInstagramPost\Model\Config $config * @param \Psr\Log\LoggerInterface $logger * @param array $data */ public function __construct( - \Magento\Framework\App\Filesystem\DirectoryList $directory_list, - \GhoSter\AutoInstagramPost\Helper\Data $helper, + \Magento\Framework\App\Filesystem\DirectoryList $directoryList, + \GhoSter\AutoInstagramPost\Model\Config $config, \Psr\Log\LoggerInterface $logger, array $data = [] ) { $this->logger = $logger; - $this->helper = $helper; + $this->config = $config; - if ($this->helper->isModuleEnabled()) { - $account = $this->helper->getAccountInformation(); + if ($this->config->isEnabled()) { + $account = $this->config->getAccountInformation(); $this->device_id = $this->generateDeviceId(md5($account['username'] . $account['password'])); $this->setUser($account['username'], $account['password']); } - $this->directory_list = $directory_list; + $this->directoryList = $directoryList; - $this->IGDataPath = $this->directory_list->getPath('var') . DIRECTORY_SEPARATOR; + $this->IGDataPath = $this->directoryList->getPath('var') . DIRECTORY_SEPARATOR; } diff --git a/Observer/Catalog/ProductSaveAfter.php b/Observer/Catalog/ProductSaveAfter.php index 966eb71..71c968e 100644 --- a/Observer/Catalog/ProductSaveAfter.php +++ b/Observer/Catalog/ProductSaveAfter.php @@ -6,25 +6,34 @@ use GhoSter\AutoInstagramPost\Model\Instagram; use GhoSter\AutoInstagramPost\Model\ImageProcessor; use GhoSter\AutoInstagramPost\Model\Item as InstagramItem; -use GhoSter\AutoInstagramPost\Model\Logger; +use GhoSter\AutoInstagramPost\Model\Logger as InstagramLogger; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; +use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; +use Psr\Log\LoggerInterface; + class ProductSaveAfter implements ObserverInterface { /** - * @var \GhoSter\AutoInstagramPost\Helper\Data + * @var InstagramHelper */ - protected $_helper; + protected $instagramHelper; /** - * @var Logger + * @var InstagramConfig */ - protected $_logger; + protected $config; + + /** + * @var InstagramLogger + */ + protected $logger; /** * @var \Magento\Framework\Message\ManagerInterface */ - protected $_messageManager; + protected $messageManager; /** * @var array @@ -35,7 +44,7 @@ class ProductSaveAfter implements ObserverInterface /** * @var Instagram */ - protected $_instagram; + private $_instagram; /** * @var \Magento\Framework\App\Filesystem\DirectoryList @@ -62,33 +71,36 @@ class ProductSaveAfter implements ObserverInterface /** * ProductSaveAfter constructor. * @param \Magento\Framework\App\Action\Context $context - * @param \GhoSter\AutoInstagramPost\Helper\Data $helper + * @param InstagramHelper $instagramHelper + * @param InstagramConfig $config * @param Instagram $instagram * @param ImageProcessor $imageProcessor - * @param Logger $logger + * @param InstagramLogger $logger * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Catalog\Model\ResourceModel\Product\Action $action */ public function __construct( \Magento\Framework\App\Action\Context $context, - \GhoSter\AutoInstagramPost\Helper\Data $helper, + InstagramHelper $instagramHelper, + InstagramConfig $config, Instagram $instagram, ImageProcessor $imageProcessor, - Logger $logger, + InstagramLogger $logger, \Magento\Framework\App\Filesystem\DirectoryList $directoryList, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Model\ResourceModel\Product\Action $action ) { - $this->_helper = $helper; + $this->instagramHelper = $instagramHelper; + $this->config = $config; $this->_instagram = $instagram; $this->imageProcessor = $imageProcessor; - $this->_logger = $logger; + $this->logger = $logger; $this->_directoryList = $directoryList; - $this->_account = $this->_helper->getAccountInformation(); - $this->_messageManager = $context->getMessageManager(); + $this->_account = $this->config->getAccountInformation(); + $this->messageManager = $context->getMessageManager(); $this->_storeManager = $storeManager; $this->_action = $action; @@ -105,11 +117,11 @@ public function execute( \Magento\Framework\Event\Observer $observer ) { - if (!$this->_helper->isModuleEnabled()) { + if (!$this->config->isEnabled()) { return; } - if (!$this->_helper->isObserverEnabled()) { + if (!$this->config->isObserverEnabled()) { return; } @@ -124,12 +136,12 @@ public function execute( // Start to Send Image to Instagram if ($image) { - $caption = $this->_helper->getInstagramPostDescription($product); + $caption = $this->instagramHelper->getInstagramPostDescription($product); if (!empty($this->_account) && isset($this->_account['username']) && isset($this->_account['password'])) { - $this->_getInstagram() + $this->getInstagram() ->setUser( $this->_account['username'], $this->_account['password'] @@ -138,24 +150,24 @@ public function execute( try { - if (!$this->_getInstagram()->login()) { - $this->_messageManager->addErrorMessage(__('Unauthorized Instagram Account, check your user/password setting')); + if (!$this->getInstagram()->login()) { + $this->messageManager->addErrorMessage(__('Unauthorized Instagram Account, check your user/password setting')); } - $result = $this->_getInstagram()->uploadPhoto($image, $caption); + $result = $this->getInstagram()->uploadPhoto($image, $caption); if (empty($result)) { - $this->_messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); + $this->messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); } if ($result['status'] === Instagram::STATUS_FAIL) { - $this->_logger->recordInstagramLog( + $this->logger->recordInstagramLog( $product, $result, InstagramItem::TYPE_ERROR ); - $this->_messageManager->addComplexErrorMessage( + $this->messageManager->addComplexErrorMessage( 'InstagramError', [ 'instagram_link' => 'https://help.instagram.com/1631821640426723' @@ -164,13 +176,13 @@ public function execute( } if ($result['status'] === Instagram::STATUS_OK) { - $this->_logger->recordInstagramLog( + $this->logger->recordInstagramLog( $product, $result, InstagramItem::TYPE_SUCCESS ); - $this->_messageManager->addComplexSuccessMessage( + $this->messageManager->addComplexSuccessMessage( 'InstagramSuccess', [ 'instagram_link' => 'https://www.instagram.com/p/' . $result['media']['code'] @@ -180,7 +192,7 @@ public function execute( } catch (\Exception $e) { - $this->_messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); + $this->messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); } } } @@ -188,11 +200,9 @@ public function execute( } /** - * Get Instagram Client - * - * @return \GhoSter\AutoInstagramPost\Model\Instagram + * @return Instagram */ - private function _getInstagram() + public function getInstagram(): Instagram { return $this->_instagram; } diff --git a/Plugin/Model/Menu/BuilderPlugin.php b/Plugin/Model/Menu/BuilderPlugin.php index ee71fce..5101131 100644 --- a/Plugin/Model/Menu/BuilderPlugin.php +++ b/Plugin/Model/Menu/BuilderPlugin.php @@ -5,7 +5,7 @@ use Magento\Backend\Model\Menu\Builder; use Magento\Backend\Model\Menu; use Magento\Backend\Model\Menu\ItemFactory; -use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; class BuilderPlugin { @@ -18,22 +18,22 @@ class BuilderPlugin private $menuItemFactory; /** - * @var InstagramHelper + * @var InstagramConfig */ - protected $helper; + protected $config; /** * BuilderPlugin constructor. * * @param ItemFactory $menuItemFactory - * @param InstagramHelper $helper + * @param InstagramConfig $config */ public function __construct( ItemFactory $menuItemFactory, - InstagramHelper $helper + InstagramConfig $config ) { - $this->helper = $helper; + $this->config = $config; $this->menuItemFactory = $menuItemFactory; } @@ -49,7 +49,7 @@ public function afterGetResult( Menu $menu ) { - if(!$this->helper->isModuleEnabled() && $menu->get(self::MENU_MANAGE_ID)) { + if(!$this->config->isEnabled() && $menu->get(self::MENU_MANAGE_ID)) { $menu->remove(self::MENU_MANAGE_ID); } diff --git a/Ui/Component/Listing/Columns/ProductActions.php b/Ui/Component/Listing/Columns/ProductActions.php index 429cf53..2f2ba3f 100644 --- a/Ui/Component/Listing/Columns/ProductActions.php +++ b/Ui/Component/Listing/Columns/ProductActions.php @@ -5,7 +5,7 @@ use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\UiComponent\ContextInterface; use Magento\Framework\View\Element\UiComponentFactory; -use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; /** * Class ProductActions @@ -18,21 +18,37 @@ class ProductActions extends \Magento\Catalog\Ui\Component\Listing\Columns\Produ const URL_PATH_POST = 'auto_instagram/manage/post'; /** - * @var InstagramHelper + * @var InstagramConfig */ - protected $helper; + protected $config; + /** + * ProductActions constructor. + * + * @param ContextInterface $context + * @param UiComponentFactory $uiComponentFactory + * @param UrlInterface $urlBuilder + * @param InstagramConfig $config + * @param array $components + * @param array $data + */ public function __construct( ContextInterface $context, UiComponentFactory $uiComponentFactory, UrlInterface $urlBuilder, - InstagramHelper $helper, + InstagramConfig $config, array $components = [], array $data = [] ) { - $this->helper = $helper; - parent::__construct($context, $uiComponentFactory, $urlBuilder, $components, $data); + $this->config = $config; + parent::__construct( + $context, + $uiComponentFactory, + $urlBuilder, + $components, + $data + ); } /** @@ -47,7 +63,7 @@ public function prepareDataSource(array $dataSource) $storeId = $this->context->getFilterParam('store_id'); foreach ($dataSource['data']['items'] as &$item) { - if (isset($item['is_posted_to_instagram']) && $this->helper->isModuleEnabled()) { + if (isset($item['is_posted_to_instagram']) && $this->config->isEnabled()) { $item[$this->getData('name')]['post_instagram_action'] = [ 'href' => $this->urlBuilder->getUrl( static::URL_PATH_POST, diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index a4e316f..5775373 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -8,7 +8,7 @@ ghoster GhoSter_AutoInstagramPost::config - + @@ -56,17 +56,17 @@ - - + + - + Magento\Config\Model\Config\Source\Yesno 1 - + Magento\Config\Model\Config\Source\Yesno @@ -75,7 +75,7 @@ - + Magento\Config\Model\Config\Source\Yesno @@ -84,7 +84,7 @@ - + Magento\Config\Model\Config\Source\Yesno 1 @@ -102,8 +102,8 @@ 1 - - + + Instagram caption character limit: 2,200 characters
Instagram hashtag limit: 30 hashtags
Instagram bio character limit: 150 characters]]>
1 @@ -111,6 +111,37 @@
+ + + + + Magento\Config\Model\Config\Source\Yesno + + 1 + + + + + + 1 + + + + + + 1 + + Magento\Cron\Model\Config\Source\Frequency + GhoSter\AutoInstagramPost\Model\Config\Backend\Cron + + + + + 1 + + validate-zero-or-greater + + diff --git a/etc/config.xml b/etc/config.xml index bdcf7cb..f2108aa 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -3,18 +3,22 @@ - 0 + 0 - 1 + 1 - 0 + 0 1 1 - 0 + 0 + + 0 + 10 + diff --git a/etc/crontab.xml b/etc/crontab.xml new file mode 100644 index 0000000..a17ae8b --- /dev/null +++ b/etc/crontab.xml @@ -0,0 +1,8 @@ + + + + + crontab/default/jobs/catalog_product_alert/auto_instagram_post/cron_expr + + + From 877ab56d41d078e5ce127240203935fa94ca92d9 Mon Sep 17 00:00:00 2001 From: tuyennn Date: Fri, 29 Mar 2019 11:53:57 +0700 Subject: [PATCH 2/3] [TASK] Bug fix for default image processor --- Cron/SchedulePost.php | 94 ++++++++++++----------- Helper/Data.php | 47 ++++++++++-- Model/ImageProcessor.php | 62 +++++++++++---- Model/Instagram.php | 158 ++++++++++++++++++++++----------------- 4 files changed, 224 insertions(+), 137 deletions(-) diff --git a/Cron/SchedulePost.php b/Cron/SchedulePost.php index 339183c..4a62dbd 100644 --- a/Cron/SchedulePost.php +++ b/Cron/SchedulePost.php @@ -91,12 +91,13 @@ public function execute() try { $collection = $this->productCollection + ->addAttributeToSelect('*') ->addAttributeToFilter( - 'posted_toinstagram', + 'posted_to_instagram', [ 'or' => [ - 0 => ['is' => 0], - 1 => ['is' => new \Zend_Db_Expr('null')], + 0 => ['eq' => 0], + 1 => ['is' => new \Zend_Db_Expr('NULL')], ] ], 'left' @@ -104,67 +105,70 @@ public function execute() $collection->getSelect()->limit($limit); - if (!empty($this->account) - && isset($this->account['username']) - && isset($this->account['password'])) { - $this->getInstagram() - ->setUser( - $this->account['username'], - $this->account['password'] - ); - } + if($collection->count() > 0) { + if (!empty($this->account) + && isset($this->account['username']) + && isset($this->account['password'])) { + $this->getInstagram() + ->setUser( + $this->account['username'], + $this->account['password'] + ); + } - foreach ($collection as $product) { + foreach ($collection as $product) { - $image = $this->imageProcessor->processBaseImage($product); + $image = $this->imageProcessor->processBaseImage($product); - if ($image) { + if ($image) { - $caption = $this->instagramHelper - ->getInstagramPostDescription($product); + $caption = $this->instagramHelper + ->getInstagramPostDescription($product); - try { + try { - $result = $this->getInstagram() - ->uploadPhoto( - $image, - $caption - ); + $result = $this->getInstagram() + ->uploadPhoto( + $image, + $caption + ); - if (empty($result)) { - $this->logger->recordInstagramLog( - $product, - [], - InstagramItem::TYPE_ERROR - ); - } + if (empty($result)) { + $this->logger->recordInstagramLog( + $product, + [], + InstagramItem::TYPE_ERROR + ); + } - if ($result['status'] === Instagram::STATUS_FAIL) { - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_ERROR - ); + if ($result['status'] === Instagram::STATUS_FAIL) { + $this->logger->recordInstagramLog( + $product, + $result, + InstagramItem::TYPE_ERROR + ); - } + } - if ($result['status'] === Instagram::STATUS_OK) { - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_SUCCESS - ); + if ($result['status'] === Instagram::STATUS_OK) { + $this->logger->recordInstagramLog( + $product, + $result, + InstagramItem::TYPE_SUCCESS + ); - } + } - } catch (\Exception $e) { + } catch (\Exception $e) { + } } } } } catch (\Exception $e) { + } return; diff --git a/Helper/Data.php b/Helper/Data.php index 2f4db07..e32c6fc 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -119,14 +119,12 @@ public function getResizeImage( try { if (!file_exists($imageResized)) { - $image = $this->imageFactory->create(); - $image->open($imageDir); - $image->constrainOnly(true); - $image->keepAspectRatio(true); - $image->keepFrame(true); - $image->backgroundColor(array(255, 255, 255)); - $image->resize($width, $height); - $image->save($imageResized); + $this->_generateInstagramImage( + $imageResized, + $imageDir, + $width, + $height + ); } if (file_exists($imageResized)) { @@ -157,6 +155,39 @@ public function getResizeImage( } + /** + * Generate Image + * + * @param $imageResizedPath + * @param $imageDir + * @param $width + * @param $height + */ + private function _generateInstagramImage( + $imageResizedPath, + $imageDir, + $width, + $height + ){ + try { + + $image = $this->imageFactory->create(); + $image->open($imageDir); + $image->constrainOnly(true); + $image->keepAspectRatio(true); + $image->keepFrame(true); + $image->backgroundColor(array(255, 255, 255)); + $image->resize($width, $height); + $image->save($imageResizedPath); + + } catch (\Exception $e) { + + } + + return; + + } + /** * Convert Non JPG format * diff --git a/Model/ImageProcessor.php b/Model/ImageProcessor.php index d0e12ba..1be7a05 100644 --- a/Model/ImageProcessor.php +++ b/Model/ImageProcessor.php @@ -2,50 +2,69 @@ namespace GhoSter\AutoInstagramPost\Model; +use Magento\Catalog\Model\Product; +use Magento\Framework\App\Filesystem\DirectoryList; +use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; + class ImageProcessor { + /** + * @var InstagramConfig + */ + protected $config; + /** - * @var \GhoSter\AutoInstagramPost\Helper\Data + * @var InstagramHelper */ - protected $_helper; + protected $instagramHelper; /** - * @var \Magento\Framework\App\Filesystem\DirectoryList + * @var DirectoryList */ - protected $_directoryList; - - protected $_image; + protected $directoryList; + protected $productHasImage = false; + /** + * ImageProcessor constructor. + * + * @param Config $config + * @param InstagramHelper $instagramHelper + * @param DirectoryList $directoryList + */ public function __construct( - \GhoSter\AutoInstagramPost\Helper\Data $helper, - \Magento\Framework\App\Filesystem\DirectoryList $directoryList + InstagramConfig $config, + InstagramHelper $instagramHelper, + DirectoryList $directoryList ) { - $this->_helper = $helper; - $this->_directoryList = $directoryList; + $this->config = $config; + $this->instagramHelper = $instagramHelper; + $this->directoryList = $directoryList; } /** * Get Base Image from Product * - * @param $product \Magento\Catalog\Model\Product + * @param $product Product * @return string * @throws \Magento\Framework\Exception\FileSystemException */ public function getBaseImage($product) { - if ($product->getImage() !== 'no_selection') { $baseImage = $product->getImage(); } else { $baseImage = $product->getSmallImage(); } + $this->productHasImage = $product->getImage() || $product->getSmallImage(); + if (!$baseImage) { - return $this->_helper->getDefaultImage(); + return $this->config->getDefaultImage(); } return $baseImage; @@ -61,7 +80,15 @@ public function getBaseImage($product) public function processBaseImage($product) { $baseImage = $this->getBaseImage($product); - $baseDir = $this->_directoryList->getPath('media') . DIRECTORY_SEPARATOR . 'catalog' . DIRECTORY_SEPARATOR . 'product'; + + if($this->productHasImage) { + $baseDir = $this->directoryList->getPath('media') . + DIRECTORY_SEPARATOR . 'catalog' . + DIRECTORY_SEPARATOR . 'product'; + } else { + $baseDir = ''; + } + if ($baseImage) { $imageDir = $baseDir . $baseImage; @@ -81,7 +108,12 @@ public function processBaseImage($product) $imageSize = 800; } - return $this->_helper->getResizeImage($imageDir, $baseImage, $imageSize); + return $this->instagramHelper + ->getResizeImage( + $imageDir, + $baseImage, + $imageSize + ); } } diff --git a/Model/Instagram.php b/Model/Instagram.php index 883cb8d..5edc863 100644 --- a/Model/Instagram.php +++ b/Model/Instagram.php @@ -2,6 +2,17 @@ namespace GhoSter\AutoInstagramPost\Model; +use Magento\Framework\App\Filesystem\DirectoryList; +use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; +use Psr\Log\LoggerInterface; + +/** + * Class Instagram + * + * Rewrite Code From : https://github.com/mgp25/Instagram-API + * + * @package GhoSter\AutoInstagramPost\Model + */ class Instagram { const API_URL = 'https://i.instagram.com/api/v1/'; @@ -17,11 +28,11 @@ class Instagram protected $debug; // Debug protected $uuid; // UUID - protected $device_id; // Device ID - protected $username_id; // Username ID + protected $deviceId; // Device ID + protected $usernameId; // Username ID protected $token; // _csrftoken protected $isLoggedIn = false; // Session status - protected $rank_token; // Rank token + protected $rankToken; // Rank token protected $IGDataPath; // Data storage path protected $directoryList; protected $config; @@ -32,19 +43,15 @@ class Instagram /** * Default class constructor. * - * Debug on or off, false by default. - * @param $helper \GhoSter\AutoInstagramPost\Helper\Data - * Default folder to store data, you can change it. - * - * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList - * @param \GhoSter\AutoInstagramPost\Model\Config $config - * @param \Psr\Log\LoggerInterface $logger + * @param DirectoryList $directoryList + * @param InstagramConfig $config + * @param LoggerInterface $logger * @param array $data */ public function __construct( - \Magento\Framework\App\Filesystem\DirectoryList $directoryList, - \GhoSter\AutoInstagramPost\Model\Config $config, - \Psr\Log\LoggerInterface $logger, + DirectoryList $directoryList, + InstagramConfig $config, + LoggerInterface $logger, array $data = [] ) { @@ -53,7 +60,9 @@ public function __construct( if ($this->config->isEnabled()) { $account = $this->config->getAccountInformation(); - $this->device_id = $this->generateDeviceId(md5($account['username'] . $account['password'])); + $this->deviceId = $this->generateDeviceId( + md5($account['username'] . $account['password']) + ); $this->setUser($account['username'], $account['password']); } @@ -78,12 +87,13 @@ public function setUser($username, $password) $this->uuid = $this->generateUUID(true); - if ((file_exists($this->IGDataPath . "$this->username-cookies.dat")) && (file_exists($this->IGDataPath . "$this->username-userId.dat")) + if ((file_exists($this->IGDataPath . "$this->username-cookies.dat")) + && (file_exists($this->IGDataPath . "$this->username-userId.dat")) && (file_exists($this->IGDataPath . "$this->username-token.dat")) ) { $this->isLoggedIn = true; - $this->username_id = trim(file_get_contents($this->IGDataPath . "$username-userId.dat")); - $this->rank_token = $this->username_id . '_' . $this->uuid; + $this->usernameId = trim(file_get_contents($this->IGDataPath . "$username-userId.dat")); + $this->rankToken = $this->usernameId . '_' . $this->uuid; $this->token = trim(file_get_contents($this->IGDataPath . "$username-token.dat")); } } @@ -109,7 +119,7 @@ public function login($force = false) '_csrftoken' => $token[0], 'username' => $this->username, 'guid' => $this->uuid, - 'device_id' => $this->device_id, + 'deviceId' => $this->deviceId, 'password' => $this->password, 'login_attempt_count' => '0', ]; @@ -121,9 +131,9 @@ public function login($force = false) } $this->isLoggedIn = true; - $this->username_id = $login[1]['logged_in_user']['pk']; - file_put_contents($this->IGDataPath . $this->username . '-userId.dat', $this->username_id); - $this->rank_token = $this->username_id . '_' . $this->uuid; + $this->usernameId = $login[1]['logged_in_user']['pk']; + file_put_contents($this->IGDataPath . $this->username . '-userId.dat', $this->usernameId); + $this->rankToken = $this->usernameId . '_' . $this->uuid; preg_match('#Set-Cookie: csrftoken=([^;]+)#', $login[0], $match); $this->token = $match[1]; file_put_contents($this->IGDataPath . $this->username . '-token.dat', $this->token); @@ -136,7 +146,9 @@ public function login($force = false) } $check = $this->timelineFeed(); - if (isset($check['message']) && $check['message'] === 'login_required') { + if (isset($check['message']) + && $check['message'] === 'login_required' + ) { $this->login(true); } @@ -147,8 +159,8 @@ public function syncFeatures() { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, - 'id' => $this->username_id, + '_uid' => $this->usernameId, + 'id' => $this->usernameId, '_csrftoken' => $this->token, 'experiments' => self::EXPERIMENTS, ]); @@ -175,8 +187,8 @@ protected function expose() { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, - 'id' => $this->username_id, + '_uid' => $this->usernameId, + 'id' => $this->usernameId, '_csrftoken' => $this->token, 'experiment' => 'ig_android_profile_contextual_feed', ]); @@ -305,6 +317,14 @@ public function uploadPhoto($photo, $caption = null, $upload_id = null) return $configure; } + /** + * Upload Video + * + * @param $video + * @param null $caption + * @return mixed|void + * @throws \Exception + */ public function uploadVideo($video, $caption = null) { $videoData = file_get_contents($video); @@ -536,7 +556,7 @@ protected function configureVideo($upload_id, $video, $caption = '') ], '_csrftoken' => $this->token, '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'caption' => $caption, ]); @@ -572,7 +592,7 @@ protected function configure($upload_id, $photo, $caption = '') ], '_csrftoken' => $this->token, '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'caption' => $caption, ]); @@ -596,7 +616,7 @@ public function editMedia($mediaId, $captionText = '') { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'caption_text' => $captionText, ]); @@ -617,7 +637,7 @@ public function removeSelftag($mediaId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, ]); @@ -637,7 +657,7 @@ public function mediaInfo($mediaId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'media_id' => $mediaId, ]); @@ -658,7 +678,7 @@ public function deleteMedia($mediaId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'media_id' => $mediaId, ]); @@ -681,7 +701,7 @@ public function comment($mediaId, $commentText) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'comment_text' => $commentText, ]); @@ -704,7 +724,7 @@ public function deleteComment($mediaId, $captionText, $commentId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'caption_text' => $captionText, ]); @@ -729,7 +749,7 @@ public function changeProfilePicture($photo) $uData = json_encode([ '_csrftoken' => $this->token, '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, ]); $endpoint = self::API_URL . 'accounts/change_profile_picture/'; @@ -800,7 +820,7 @@ public function removeProfilePicture() { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, ]); @@ -817,7 +837,7 @@ public function setPrivateAccount() { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, ]); @@ -834,7 +854,7 @@ public function setPublicAccount() { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, ]); @@ -851,7 +871,7 @@ public function getProfileData() { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, ]); @@ -879,7 +899,7 @@ public function editProfile($url, $phone, $first_name, $biography, $email, $gend { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'external_url' => $url, 'phone_number' => $phone, @@ -915,7 +935,7 @@ public function getUsernameInfo($usernameId) */ public function getSelfUsernameInfo() { - return $this->getUsernameInfo($this->username_id); + return $this->getUsernameInfo($this->usernameId); } /** @@ -989,7 +1009,7 @@ public function getv2Inbox() */ public function getUserTags($usernameId) { - $tags = $this->request("usertags/$usernameId/feed/?rank_token=$this->rank_token&ranked_content=true&")[1]; + $tags = $this->request("usertags/$usernameId/feed/?rankToken=$this->rankToken&ranked_content=true&")[1]; if ($tags['status'] !== 'ok') { throw new \Exception($tags['message'] . "\n"); @@ -1008,7 +1028,7 @@ public function getUserTags($usernameId) */ public function getSelfUserTags() { - return $this->getUserTags($this->username_id); + return $this->getUserTags($this->usernameId); } /** @@ -1022,7 +1042,7 @@ public function getSelfUserTags() public function tagFeed($tag) { - $userFeed = $this->request("feed/tag/$tag/?rank_token=$this->rank_token&ranked_content=true&")[1]; + $userFeed = $this->request("feed/tag/$tag/?rankToken=$this->rankToken&ranked_content=true&")[1]; if ($userFeed['status'] !== 'ok') { throw new \Exception($userFeed['message'] . "\n"); @@ -1084,7 +1104,7 @@ public function getGeoMedia($usernameId) */ public function getSelfGeoMedia() { - return $this->getGeoMedia($this->username_id); + return $this->getGeoMedia($this->usernameId); } /** @@ -1099,7 +1119,7 @@ public function getSelfGeoMedia() public function fbUserSearch($query) { $query = rawurlencode($query); - $query = $this->request("fbsearch/topsearch/?context=blended&query=$query&rank_token=$this->rank_token")[1]; + $query = $this->request("fbsearch/topsearch/?context=blended&query=$query&rankToken=$this->rankToken")[1]; if ($query['status'] !== 'ok') { throw new \Exception($query['message'] . "\n"); @@ -1121,7 +1141,7 @@ public function fbUserSearch($query) */ public function searchUsers($query) { - $query = $this->request('users/search/?ig_sig_key_version=' . self::SIG_KEY_VERSION . "&is_typeahead=true&query=$query&rank_token=$this->rank_token")[1]; + $query = $this->request('users/search/?ig_sig_key_version=' . self::SIG_KEY_VERSION . "&is_typeahead=true&query=$query&rankToken=$this->rankToken")[1]; if ($query['status'] !== 'ok') { throw new \Exception($query['message'] . "\n"); @@ -1181,7 +1201,7 @@ public function syncFromAdressBook($contacts) */ public function searchTags($query) { - $query = $this->request("tags/search/?is_typeahead=true&q=$query&rank_token=$this->rank_token")[1]; + $query = $this->request("tags/search/?is_typeahead=true&q=$query&rankToken=$this->rankToken")[1]; if ($query['status'] !== 'ok') { throw new \Exception($query['message'] . "\n"); @@ -1202,7 +1222,7 @@ public function searchTags($query) public function getTimeline($maxid = null) { $timeline = $this->request( - "feed/timeline/?rank_token=$this->rank_token&ranked_content=true" + "feed/timeline/?rankToken=$this->rankToken&ranked_content=true" . (!is_null($maxid) ? "&max_id=" . $maxid : '') )[1]; @@ -1230,7 +1250,7 @@ public function getTimeline($maxid = null) public function getUserFeed($usernameId, $maxid = null, $minTimestamp = null) { $userFeed = $this->request( - "feed/user/$usernameId/?rank_token=$this->rank_token" + "feed/user/$usernameId/?rankToken=$this->rankToken" . (!is_null($maxid) ? "&max_id=" . $maxid : '') . (!is_null($minTimestamp) ? "&min_timestamp=" . $minTimestamp : '') . "&ranked_content=true" @@ -1258,9 +1278,9 @@ public function getUserFeed($usernameId, $maxid = null, $minTimestamp = null) public function getHashtagFeed($hashtagString, $maxid = null) { if (is_null($maxid)) { - $endpoint = "feed/tag/$hashtagString/?rank_token=$this->rank_token&ranked_content=true&"; + $endpoint = "feed/tag/$hashtagString/?rankToken=$this->rankToken&ranked_content=true&"; } else { - $endpoint = "feed/tag/$hashtagString/?max_id=" . $maxid . "&rank_token=$this->rank_token&ranked_content=true&"; + $endpoint = "feed/tag/$hashtagString/?max_id=" . $maxid . "&rankToken=$this->rankToken&ranked_content=true&"; } $hashtagFeed = $this->request($endpoint)[1]; @@ -1287,7 +1307,7 @@ public function getHashtagFeed($hashtagString, $maxid = null) public function searchLocation($query) { $query = rawurlencode($query); - $endpoint = "fbsearch/places/?rank_token=$this->rank_token&query=" . $query; + $endpoint = "fbsearch/places/?rankToken=$this->rankToken&query=" . $query; $locationFeed = $this->request($endpoint)[1]; @@ -1313,9 +1333,9 @@ public function searchLocation($query) public function getLocationFeed($locationId, $maxid = null) { if (is_null($maxid)) { - $endpoint = "feed/location/$locationId/?rank_token=$this->rank_token&ranked_content=true&"; + $endpoint = "feed/location/$locationId/?rankToken=$this->rankToken&ranked_content=true&"; } else { - $endpoint = "feed/location/$locationId/?max_id=" . $maxid . "&rank_token=$this->rank_token&ranked_content=true&"; + $endpoint = "feed/location/$locationId/?max_id=" . $maxid . "&rankToken=$this->rankToken&ranked_content=true&"; } $locationFeed = $this->request($endpoint)[1]; @@ -1337,7 +1357,7 @@ public function getLocationFeed($locationId, $maxid = null) */ public function getSelfUserFeed() { - return $this->getUserFeed($this->username_id); + return $this->getUserFeed($this->usernameId); } /** @@ -1349,7 +1369,7 @@ public function getSelfUserFeed() */ public function getPopularFeed() { - $popularFeed = $this->request("feed/popular/?people_teaser_supported=1&rank_token=$this->rank_token&ranked_content=true&")[1]; + $popularFeed = $this->request("feed/popular/?people_teaser_supported=1&rankToken=$this->rankToken&ranked_content=true&")[1]; if ($popularFeed['status'] !== 'ok') { throw new \Exception($popularFeed['message'] . "\n"); @@ -1371,7 +1391,7 @@ public function getPopularFeed() */ public function getUserFollowings($usernameId, $maxid = null) { - return $this->request("friendships/$usernameId/following/?max_id=$maxid&ig_sig_key_version=" . self::SIG_KEY_VERSION . "&rank_token=$this->rank_token")[1]; + return $this->request("friendships/$usernameId/following/?max_id=$maxid&ig_sig_key_version=" . self::SIG_KEY_VERSION . "&rankToken=$this->rankToken")[1]; } /** @@ -1385,7 +1405,7 @@ public function getUserFollowings($usernameId, $maxid = null) */ public function getUserFollowers($usernameId, $maxid = null) { - return $this->request("friendships/$usernameId/followers/?max_id=$maxid&ig_sig_key_version=" . self::SIG_KEY_VERSION . "&rank_token=$this->rank_token")[1]; + return $this->request("friendships/$usernameId/followers/?max_id=$maxid&ig_sig_key_version=" . self::SIG_KEY_VERSION . "&rankToken=$this->rankToken")[1]; } /** @@ -1396,7 +1416,7 @@ public function getUserFollowers($usernameId, $maxid = null) */ public function getSelfUserFollowers() { - return $this->getUserFollowers($this->username_id); + return $this->getUserFollowers($this->usernameId); } /** @@ -1407,7 +1427,7 @@ public function getSelfUserFollowers() */ public function getSelfUsersFollowing() { - return $this->request('friendships/following/?ig_sig_key_version=' . self::SIG_KEY_VERSION . "&rank_token=$this->rank_token")[1]; + return $this->request('friendships/following/?ig_sig_key_version=' . self::SIG_KEY_VERSION . "&rankToken=$this->rankToken")[1]; } /** @@ -1423,7 +1443,7 @@ public function like($mediaId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'media_id' => $mediaId, ]); @@ -1444,7 +1464,7 @@ public function unlike($mediaId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, '_csrftoken' => $this->token, 'media_id' => $mediaId, ]); @@ -1479,7 +1499,7 @@ public function setNameAndPhone($name = '', $phone = '') { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'first_name' => $name, 'phone_number' => $phone, '_csrftoken' => $this->token, @@ -1526,7 +1546,7 @@ public function follow($userId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'user_id' => $userId, '_csrftoken' => $this->token, ]); @@ -1546,7 +1566,7 @@ public function unfollow($userId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'user_id' => $userId, '_csrftoken' => $this->token, ]); @@ -1566,7 +1586,7 @@ public function block($userId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'user_id' => $userId, '_csrftoken' => $this->token, ]); @@ -1586,7 +1606,7 @@ public function unblock($userId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'user_id' => $userId, '_csrftoken' => $this->token, ]); @@ -1606,7 +1626,7 @@ public function userFriendship($userId) { $data = json_encode([ '_uuid' => $this->uuid, - '_uid' => $this->username_id, + '_uid' => $this->usernameId, 'user_id' => $userId, '_csrftoken' => $this->token, ]); From 551964ba6585132db5cd37632320f117f068b8fb Mon Sep 17 00:00:00 2001 From: tuyennn Date: Fri, 29 Mar 2019 14:51:56 +0700 Subject: [PATCH 3/3] [TASK] Add Worker for better performance --- Api/WorkerInterface.php | 20 +++ Controller/Adminhtml/Manage/MassPost.php | 116 ++----------- Controller/Adminhtml/Manage/Post.php | 140 +++------------- Cron/SchedulePost.php | 115 +------------ Helper/Data.php | 6 +- Model/Instagram/Worker.php | 197 +++++++++++++++++++++++ Model/Logger.php | 5 +- Observer/Catalog/ProductSaveAfter.php | 174 +++++--------------- 8 files changed, 309 insertions(+), 464 deletions(-) create mode 100644 Api/WorkerInterface.php create mode 100644 Model/Instagram/Worker.php diff --git a/Api/WorkerInterface.php b/Api/WorkerInterface.php new file mode 100644 index 0000000..991f48b --- /dev/null +++ b/Api/WorkerInterface.php @@ -0,0 +1,20 @@ +config = $config; - $this->helper = $helper; $this->productFactory = $productFactory; - $this->_instagram = $instagram; - $this->imageProcessor = $imageProcessor; - $this->_account = $this->config->getAccountInformation(); + $this->instagramWorker = $instagramWorker; $this->filter = $filter; $this->collectionFactory = $collectionFactory; - $this->logger = $logger; parent::__construct($context); } + /** + * @return \Magento\Backend\Model\View\Result\Redirect|\Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface + * @throws NotFoundException + */ public function execute() { if (!$this->getRequest()->isPost()) { @@ -116,58 +89,10 @@ public function execute() ->addAttributeToFilter('entity_id', ['in' => $productIds]); try { - if (!empty($this->_account) - && isset($this->_account['username']) - && isset($this->_account['password'])) { - $this->getInstagram()->setUser( - $this->_account['username'], - $this->_account['password'] - ); - } - - - if (!$this->getInstagram()->login()) { - $this->messageManager->addErrorMessage( - __('Unauthorized Instagram Account, check your user/password setting') - ); - } + $result = $this->instagramWorker->postInstagramByProductCollection($productCollection); - $productUploaded = $errorNumber = 0; - - foreach ($productCollection as $product) { - - $image = $this->imageProcessor->processBaseImage($product); - - if ($image) { - $caption = $this->helper->getInstagramPostDescription($product); - - $result = $this->getInstagram() - ->uploadPhoto( - $image, - $caption - ); - - if (empty($result)) { - $errorNumber++; - $this->logger->recordInstagramLog( - $product, - [], - InstagramItem::TYPE_ERROR - ); - } - - if (isset($result['status']) - && $result['status'] === Instagram::STATUS_OK - ) { - $productUploaded++; - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_SUCCESS - ); - } - } - } + $productUploaded = count($result); + $errorNumber = $productCollection->count() - $productUploaded; if ($errorNumber) { $this->messageManager->addComplexErrorMessage( @@ -201,15 +126,6 @@ public function execute() return $resultRedirect->setPath('*/*/'); } - /** - * @return Instagram - */ - public function getInstagram(): Instagram - { - return $this->_instagram; - } - - /** * Is the user allowed to view the blog post grid. * diff --git a/Controller/Adminhtml/Manage/Post.php b/Controller/Adminhtml/Manage/Post.php index 144687f..d414ccc 100644 --- a/Controller/Adminhtml/Manage/Post.php +++ b/Controller/Adminhtml/Manage/Post.php @@ -4,78 +4,38 @@ use Magento\Backend\App\Action; use Magento\Framework\Exception\LocalizedException; -use GhoSter\AutoInstagramPost\Model\Instagram; -use GhoSter\AutoInstagramPost\Model\Item as InstagramItem; use Magento\Catalog\Model\ProductFactory; -use GhoSter\AutoInstagramPost\Model\ImageProcessor; -use GhoSter\AutoInstagramPost\Model\Logger as InstagramLogger; -use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; -use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; +use Magento\Catalog\Model\Product; +use GhoSter\AutoInstagramPost\Model\Instagram; +use GhoSter\AutoInstagramPost\Model\Instagram\Worker as InstagramWorker; class Post extends Action { /** - * @var InstagramHelper - */ - protected $helper; - - /** @var InstagramConfig */ - protected $config; - - /** - * @var InstagramLogger + * @var InstagramWorker */ - protected $logger; - - /** - * @var array - */ - protected $_account; - - /** - * @var Instagram - */ - protected $_instagram; + protected $instagramWorker; /** * @var ProductFactory */ protected $productFactory; - /** - * @var \GhoSter\AutoInstagramPost\Model\ImageProcessor - */ - protected $imageProcessor; - - /** * Post constructor. * * @param Action\Context $context - * @param InstagramConfig $config - * @param InstagramHelper $helper * @param ProductFactory $productFactory - * @param Instagram $instagram - * @param ImageProcessor $imageProcessor - * @param InstagramLogger $logger + * @param InstagramWorker $instagramWorker */ public function __construct( Action\Context $context, - InstagramConfig $config, - InstagramHelper $helper, ProductFactory $productFactory, - Instagram $instagram, - ImageProcessor $imageProcessor, - InstagramLogger $logger + InstagramWorker $instagramWorker ) { - $this->config = $config; - $this->helper = $helper; $this->productFactory = $productFactory; - $this->_instagram = $instagram; - $this->imageProcessor = $imageProcessor; - $this->logger = $logger; - $this->_account = $this->config->getAccountInformation(); + $this->instagramWorker = $instagramWorker; parent::__construct($context); } @@ -86,71 +46,29 @@ public function execute() $id = $this->getRequest()->getParam('id'); if ($id) { - /** @var $product \Magento\Catalog\Model\Product */ + /** @var $product Product */ $product = $this->productFactory->create()->load($id); try { - $image = $this->imageProcessor->processBaseImage($product); - - if ($image) { - $caption = $this->helper->getInstagramPostDescription($product); - - if (!empty($this->_account) - && isset($this->_account['username']) - && isset($this->_account['password'])) { - $this->getInstagram() - ->setUser( - $this->_account['username'], - $this->_account['password'] - ); - } - - if (!$this->getInstagram()->login()) { - $this->messageManager->addErrorMessage(__('Unauthorized Instagram Account, check your user/password setting')); - } - - $result = $this->getInstagram() - ->uploadPhoto( - $image, - $caption - ); - - if (empty($result)) { - $this->messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); - } - - if (empty($result)) { - $this->logger->recordInstagramLog( - $product, - [], - InstagramItem::TYPE_ERROR - ); + $result = $this->instagramWorker->postInstagramByProduct($product); - $this->messageManager->addComplexErrorMessage( - 'InstagramError', - [ - 'instagram_link' => 'https://help.instagram.com/1631821640426723' - ] - ); - } - - if (isset($result['status']) - && $result['status'] === Instagram::STATUS_OK - ) { - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_SUCCESS - ); + if ($result['status'] === Instagram::STATUS_FAIL) { + $this->messageManager->addComplexErrorMessage( + 'InstagramError', + [ + 'instagram_link' => 'https://help.instagram.com/1631821640426723' + ] + ); + } - $this->messageManager->addComplexSuccessMessage( - 'InstagramSuccess', - [ - 'instagram_link' => 'https://www.instagram.com/p/' . $result['media']['code'] - ] - ); - } + if ($result['status'] === Instagram::STATUS_OK) { + $this->messageManager->addComplexSuccessMessage( + 'InstagramSuccess', + [ + 'instagram_link' => 'https://www.instagram.com/p/' . $result['media']['code'] + ] + ); } return $resultRedirect->setPath('*/*/'); @@ -169,14 +87,6 @@ public function execute() return $resultRedirect->setPath('*/*/'); } - /** - * @return Instagram - */ - public function getInstagram(): Instagram - { - return $this->_instagram; - } - /** * Is the user allowed to view the blog post grid. * diff --git a/Cron/SchedulePost.php b/Cron/SchedulePost.php index 4a62dbd..d4132e4 100644 --- a/Cron/SchedulePost.php +++ b/Cron/SchedulePost.php @@ -5,18 +5,11 @@ use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory; use GhoSter\AutoInstagramPost\Model\Instagram; -use GhoSter\AutoInstagramPost\Model\ImageProcessor; -use GhoSter\AutoInstagramPost\Model\Item as InstagramItem; -use GhoSter\AutoInstagramPost\Model\Logger as InstagramLogger; +use GhoSter\AutoInstagramPost\Model\Instagram\Worker as InstagramWorker; use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; -use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; class SchedulePost { - /** - * @var InstagramHelper - */ - protected $instagramHelper; /** * @var InstagramConfig @@ -24,25 +17,9 @@ class SchedulePost protected $config; /** - * @var InstagramLogger - */ - protected $logger; - - /** - * @var array - */ - protected $account; - - - /** - * @var Instagram - */ - protected $instagram; - - /** - * @var ImageProcessor + * @var InstagramWorker */ - protected $imageProcessor; + protected $instagramWorker; /** * @var ProductCollection @@ -52,28 +29,18 @@ class SchedulePost /** * SchedulePost constructor. - * @param InstagramHelper $instagramHelper * @param InstagramConfig $config - * @param Instagram $instagram - * @param ImageProcessor $imageProcessor - * @param InstagramLogger $logger + * @param InstagramWorker $instagramWorker * @param ProductCollectionFactory $productCollectionFactory */ public function __construct( - InstagramHelper $instagramHelper, InstagramConfig $config, - Instagram $instagram, - ImageProcessor $imageProcessor, - InstagramLogger $logger, + InstagramWorker $instagramWorker, ProductCollectionFactory $productCollectionFactory ) { - $this->instagramHelper = $instagramHelper; $this->config = $config; - $this->instagram = $instagram; - $this->imageProcessor = $imageProcessor; - $this->logger = $logger; - $this->account = $this->config->getAccountInformation(); + $this->instagramWorker = $instagramWorker; $this->productCollection = $productCollectionFactory->create(); } @@ -106,65 +73,8 @@ public function execute() $collection->getSelect()->limit($limit); if($collection->count() > 0) { - if (!empty($this->account) - && isset($this->account['username']) - && isset($this->account['password'])) { - $this->getInstagram() - ->setUser( - $this->account['username'], - $this->account['password'] - ); - } - - foreach ($collection as $product) { - - $image = $this->imageProcessor->processBaseImage($product); - - if ($image) { - - $caption = $this->instagramHelper - ->getInstagramPostDescription($product); - - try { - - $result = $this->getInstagram() - ->uploadPhoto( - $image, - $caption - ); - - if (empty($result)) { - $this->logger->recordInstagramLog( - $product, - [], - InstagramItem::TYPE_ERROR - ); - } - - if ($result['status'] === Instagram::STATUS_FAIL) { - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_ERROR - ); - - } - - if ($result['status'] === Instagram::STATUS_OK) { - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_SUCCESS - ); - - } - - - } catch (\Exception $e) { - - } - } - } + $this->instagramWorker + ->postInstagramByProductCollection($collection); } } catch (\Exception $e) { @@ -173,13 +83,4 @@ public function execute() return; } - - - /** - * @return Instagram - */ - public function getInstagram(): Instagram - { - return $this->instagram; - } } \ No newline at end of file diff --git a/Helper/Data.php b/Helper/Data.php index e32c6fc..f0b58ae 100644 --- a/Helper/Data.php +++ b/Helper/Data.php @@ -249,8 +249,8 @@ public function getCategoriesHashtagsHtml($product) /** @var $collection CategoryCollection */ $collection = $this->categoryCollectionFactory->create(); - $collection->addAttributeToSelect('name'); $collection->addAttributeToFilter('entity_id', $product->getCategoryIds()); + $collection->addNameToResult(); $i = 1; foreach ($collection as $category) { @@ -264,8 +264,8 @@ public function getCategoriesHashtagsHtml($product) } - if (!empty($hashTagsStripped)) { - foreach ($hashTagsStripped as $hashTag) { + if (!empty($hashTagsStrippedData)) { + foreach ($hashTagsStrippedData as $hashTag) { $html .= '#' . $hashTag . self::SPACE_STRING; } } diff --git a/Model/Instagram/Worker.php b/Model/Instagram/Worker.php new file mode 100644 index 0000000..4d42d4d --- /dev/null +++ b/Model/Instagram/Worker.php @@ -0,0 +1,197 @@ +config = $config; + $this->instagramHelper = $instagramHelper; + $this->instagram = $instagram; + $this->logger = $logger; + $this->imageProcessor = $imageProcessor; + $this->account = $this->config->getAccountInformation(); + + $this->setInstagramUser(); + + try { + $this->loginInstagram(); + } catch (\Exception $e) { + + } + } + + /** + * + * Post to instagram by Product + * + * @param Product $product + * @return array + * @throws \Magento\Framework\Exception\FileSystemException + */ + public function postInstagramByProduct(Product $product) + { + $image = $this->imageProcessor->processBaseImage($product); + + if ($image && $this->isLoggedIn) { + + try { + $caption = $this->instagramHelper->getInstagramPostDescription($product); + + $result = $this->getInstagram()->uploadPhoto($image, $caption); + + if ($this->recordLog) { + $this->_recordLog($result, $product); + } + + return $result; + + } catch (\Exception $e) { + + } + } + + return []; + } + + /** + * + * + * @param ProductCollection $collection + * @return array + * @throws \Magento\Framework\Exception\FileSystemException + */ + public function postInstagramByProductCollection(ProductCollection $collection) + { + $results = []; + + foreach ($collection as $product) { + $result = $this->postInstagramByProduct($product); + + if(!empty($result)) { + $results[] = $result; + } + } + + return $results; + } + + /** + * Set Instagram User + */ + public function setInstagramUser() + { + if (!empty($this->account) + && isset($this->account['username']) + && isset($this->account['password'])) { + $this->getInstagram() + ->setUser($this->account['username'], $this->account['password']); + } + } + + /** + * Do login + * + * @throws \Exception + */ + public function loginInstagram() + { + if (!$this->isLoggedIn) { + $this->isLoggedIn = $this->getInstagram()->login(); + } + + return $this->isLoggedIn; + } + + /** + * @param $result + * @param $product + * @throws \Exception + */ + private function _recordLog(&$result, $product) + { + if ($result['status'] === Instagram::STATUS_FAIL) { + $this->logger->recordInstagramLog( + $product, + $result, + InstagramItem::TYPE_ERROR + ); + } elseif ($result['status'] === Instagram::STATUS_OK) { + $this->logger->recordInstagramLog( + $product, + $result, + InstagramItem::TYPE_SUCCESS + ); + } + } + + /** + * @return Instagram + */ + public function getInstagram(): Instagram + { + return $this->instagram; + } + + +} \ No newline at end of file diff --git a/Model/Logger.php b/Model/Logger.php index 6f0ab15..3c1b55b 100644 --- a/Model/Logger.php +++ b/Model/Logger.php @@ -47,9 +47,12 @@ public function recordInstagramLog($product, $result, $type = null) if ($type == InstagramItem::TYPE_SUCCESS) { $product->setData('posted_to_instagram', 1); - $product->getResource()->saveAttribute($product, 'posted_to_instagram'); + } elseif ($type == InstagramItem::TYPE_ERROR) { + $product->setData('posted_to_instagram', 0); } + $product->getResource()->saveAttribute($product, 'posted_to_instagram'); + /** @var $item InstagramItem */ $item = $this->_itemFactory->create(); $item->setProductId($product->getId()); diff --git a/Observer/Catalog/ProductSaveAfter.php b/Observer/Catalog/ProductSaveAfter.php index 71c968e..67e4e29 100644 --- a/Observer/Catalog/ProductSaveAfter.php +++ b/Observer/Catalog/ProductSaveAfter.php @@ -2,14 +2,15 @@ namespace GhoSter\AutoInstagramPost\Observer\Catalog; +use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Message\ManagerInterface as MessageManager; +use Magento\Framework\App\Action\Context as ActionContext; +use Magento\Catalog\Model\Product; use GhoSter\AutoInstagramPost\Model\Instagram; -use GhoSter\AutoInstagramPost\Model\ImageProcessor; -use GhoSter\AutoInstagramPost\Model\Item as InstagramItem; -use GhoSter\AutoInstagramPost\Model\Logger as InstagramLogger; +use GhoSter\AutoInstagramPost\Model\Instagram\Worker as InstagramWorker; use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig; use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper; -use Psr\Log\LoggerInterface; class ProductSaveAfter implements ObserverInterface @@ -26,83 +27,25 @@ class ProductSaveAfter implements ObserverInterface protected $config; /** - * @var InstagramLogger - */ - protected $logger; - - /** - * @var \Magento\Framework\Message\ManagerInterface + * @var MessageManager */ protected $messageManager; - /** - * @var array - */ - protected $_account; - - - /** - * @var Instagram - */ - private $_instagram; - - /** - * @var \Magento\Framework\App\Filesystem\DirectoryList - */ - protected $_directoryList; + /** @var InstagramWorker */ + protected $instagramWorker; - /** - * @var \Magento\Catalog\Model\ResourceModel\Product\Action - */ - protected $_action; - /** - * Store manager - * - * @var \Magento\Store\Model\StoreManagerInterface - */ - protected $_storeManager; - - /** - * @var ImageProcessor - */ - protected $imageProcessor; - - /** - * ProductSaveAfter constructor. - * @param \Magento\Framework\App\Action\Context $context - * @param InstagramHelper $instagramHelper - * @param InstagramConfig $config - * @param Instagram $instagram - * @param ImageProcessor $imageProcessor - * @param InstagramLogger $logger - * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Catalog\Model\ResourceModel\Product\Action $action - */ public function __construct( - \Magento\Framework\App\Action\Context $context, + ActionContext $context, InstagramHelper $instagramHelper, InstagramConfig $config, - Instagram $instagram, - ImageProcessor $imageProcessor, - InstagramLogger $logger, - \Magento\Framework\App\Filesystem\DirectoryList $directoryList, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Catalog\Model\ResourceModel\Product\Action $action + InstagramWorker $instagramWorker ) { $this->instagramHelper = $instagramHelper; $this->config = $config; - $this->_instagram = $instagram; - $this->imageProcessor = $imageProcessor; - $this->logger = $logger; - $this->_directoryList = $directoryList; - - $this->_account = $this->config->getAccountInformation(); + $this->instagramWorker = $instagramWorker; $this->messageManager = $context->getMessageManager(); - $this->_storeManager = $storeManager; - $this->_action = $action; } @@ -110,11 +53,11 @@ public function __construct( /** * Execute observer * - * @param \Magento\Framework\Event\Observer $observer + * @param Observer $observer * @throws \Magento\Framework\Exception\FileSystemException */ public function execute( - \Magento\Framework\Event\Observer $observer + Observer $observer ) { if (!$this->config->isEnabled()) { @@ -125,85 +68,40 @@ public function execute( return; } - /** @var $product \Magento\Catalog\Model\Product */ + /** @var $product Product */ $product = $observer->getEvent()->getProduct(); if (!$product->getData('posted_to_instagram')) { - // Check and process exist image size - $image = $this->imageProcessor->processBaseImage($product); + try { - // Start to Send Image to Instagram - if ($image) { + $result = $this->instagramWorker->postInstagramByProduct($product); - $caption = $this->instagramHelper->getInstagramPostDescription($product); - - if (!empty($this->_account) - && isset($this->_account['username']) - && isset($this->_account['password'])) { - $this->getInstagram() - ->setUser( - $this->_account['username'], - $this->_account['password'] - ); + if ($result['status'] === Instagram::STATUS_FAIL) { + $this->messageManager->addComplexErrorMessage( + 'InstagramError', + [ + 'instagram_link' => 'https://help.instagram.com/1631821640426723' + ] + ); } - try { - - if (!$this->getInstagram()->login()) { - $this->messageManager->addErrorMessage(__('Unauthorized Instagram Account, check your user/password setting')); - } - - $result = $this->getInstagram()->uploadPhoto($image, $caption); - - if (empty($result)) { - $this->messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); - } - - if ($result['status'] === Instagram::STATUS_FAIL) { - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_ERROR - ); - - $this->messageManager->addComplexErrorMessage( - 'InstagramError', - [ - 'instagram_link' => 'https://help.instagram.com/1631821640426723' - ] - ); - } - - if ($result['status'] === Instagram::STATUS_OK) { - $this->logger->recordInstagramLog( - $product, - $result, - InstagramItem::TYPE_SUCCESS - ); - - $this->messageManager->addComplexSuccessMessage( - 'InstagramSuccess', - [ - 'instagram_link' => 'https://www.instagram.com/p/' . $result['media']['code'] - ] - ); - } - - - } catch (\Exception $e) { - $this->messageManager->addErrorMessage(__('Something went wrong while uploading to Instagram.')); + if ($result['status'] === Instagram::STATUS_OK) { + $this->messageManager->addComplexSuccessMessage( + 'InstagramSuccess', + [ + 'instagram_link' => 'https://www.instagram.com/p/' . $result['media']['code'] + ] + ); } + + } catch (\Exception $e) { + $this->messageManager + ->addErrorMessage( + __('Something went wrong while uploading to Instagram.') + ); } } } - - /** - * @return Instagram - */ - public function getInstagram(): Instagram - { - return $this->_instagram; - } }