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 @@
+_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..ebd52db 100644
--- a/Controller/Adminhtml/Manage/MassPost.php
+++ b/Controller/Adminhtml/Manage/MassPost.php
@@ -5,60 +5,33 @@
use Magento\Backend\App\Action;
use Magento\Framework\Exception\LocalizedException;
use GhoSter\AutoInstagramPost\Model\Instagram;
+use GhoSter\AutoInstagramPost\Model\Instagram\Worker as InstagramWorker;
use GhoSter\AutoInstagramPost\Model\Item as InstagramItem;
use Magento\Catalog\Model\ProductFactory;
use GhoSter\AutoInstagramPost\Model\ImageProcessor;
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
- */
- protected $helper;
-
- /**
- * @var Logger
- */
- protected $_logger;
-
+ /** @var InstagramConfig */
+ protected $config;
/**
- * @var array
+ * @var InstagramWorker
*/
- protected $_account;
-
- /**
- * @var Instagram
- */
- protected $_instagram;
-
- /**
- * @var \Magento\Framework\App\Filesystem\DirectoryList
- */
- protected $_directoryList;
-
- /**
- * Store manager
- *
- * @var \Magento\Store\Model\StoreManagerInterface
- */
- protected $_storeManager;
+ protected $instagramWorker;
/**
* @var ProductFactory
*/
protected $productFactory;
- /**
- * @var ImageProcessor
- */
- protected $imageProcessor;
-
/**
* MassActions filter
*
@@ -72,28 +45,34 @@ class MassPost extends Action
protected $collectionFactory;
+ /**
+ * MassPost constructor.
+ *
+ * @param Action\Context $context
+ * @param ProductFactory $productFactory
+ * @param InstagramWorker $instagramWorker
+ * @param Filter $filter
+ * @param CollectionFactory $collectionFactory
+ */
public function __construct(
Action\Context $context,
- \GhoSter\AutoInstagramPost\Helper\Data $helper,
ProductFactory $productFactory,
- Instagram $instagram,
- ImageProcessor $imageProcessor,
+ InstagramWorker $instagramWorker,
Filter $filter,
- CollectionFactory $collectionFactory,
- Logger $logger
- )
+ CollectionFactory $collectionFactory
+)
{
- $this->helper = $helper;
$this->productFactory = $productFactory;
- $this->_instagram = $instagram;
- $this->imageProcessor = $imageProcessor;
- $this->_account = $this->helper->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()) {
@@ -105,58 +84,15 @@ 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]);
try {
- if (!empty($this->_account)
- && isset($this->_account['username'])
- && isset($this->_account['password'])) {
- $this->_getInstagram()->setUser(
- $this->_account['username'],
- $this->_account['password']
- );
- }
+ $result = $this->instagramWorker->postInstagramByProductCollection($productCollection);
-
- if (!$this->_getInstagram()->login()) {
- $this->messageManager->addErrorMessage(__('Unauthorized Instagram Account, check your user/password setting'));
- }
-
- $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(
@@ -178,7 +114,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('*/*/');
@@ -187,17 +126,6 @@ public function execute()
return $resultRedirect->setPath('*/*/');
}
- /**
- * Get Instagram Client
- *
- * @return \GhoSter\AutoInstagramPost\Model\Instagram
- */
- private function _getInstagram()
- {
- 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 51e483e..d414ccc 100644
--- a/Controller/Adminhtml/Manage/Post.php
+++ b/Controller/Adminhtml/Manage/Post.php
@@ -4,45 +4,17 @@
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;
+use Magento\Catalog\Model\Product;
+use GhoSter\AutoInstagramPost\Model\Instagram;
+use GhoSter\AutoInstagramPost\Model\Instagram\Worker as InstagramWorker;
class Post extends Action
{
/**
- * @var \GhoSter\AutoInstagramPost\Helper\Data
- */
- protected $helper;
-
- /**
- * @var Logger
- */
- protected $_logger;
-
- /**
- * @var array
- */
- protected $_account;
-
- /**
- * @var Instagram
- */
- protected $_instagram;
-
- /**
- * @var \Magento\Framework\App\Filesystem\DirectoryList
- */
- protected $_directoryList;
-
- /**
- * Store manager
- *
- * @var \Magento\Store\Model\StoreManagerInterface
+ * @var InstagramWorker
*/
- protected $_storeManager;
+ protected $instagramWorker;
/**
* @var ProductFactory
@@ -50,26 +22,20 @@ class Post extends Action
protected $productFactory;
/**
- * @var \GhoSter\AutoInstagramPost\Model\ImageProcessor
+ * Post constructor.
+ *
+ * @param Action\Context $context
+ * @param ProductFactory $productFactory
+ * @param InstagramWorker $instagramWorker
*/
- protected $imageProcessor;
-
-
public function __construct(
Action\Context $context,
- \GhoSter\AutoInstagramPost\Helper\Data $helper,
ProductFactory $productFactory,
- Instagram $instagram,
- ImageProcessor $imageProcessor,
- Logger $logger
+ InstagramWorker $instagramWorker
)
{
- $this->helper = $helper;
$this->productFactory = $productFactory;
- $this->_instagram = $instagram;
- $this->imageProcessor = $imageProcessor;
- $this->_logger = $logger;
- $this->_account = $this->helper->getAccountInformation();
+ $this->instagramWorker = $instagramWorker;
parent::__construct($context);
}
@@ -80,67 +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('*/*/');
@@ -148,7 +76,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('*/*/');
@@ -156,17 +87,6 @@ public function execute()
return $resultRedirect->setPath('*/*/');
}
- /**
- * Get Instagram Client
- *
- * @return \GhoSter\AutoInstagramPost\Model\Instagram
- */
- private function _getInstagram()
- {
- 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..d4132e4
--- /dev/null
+++ b/Cron/SchedulePost.php
@@ -0,0 +1,86 @@
+config = $config;
+ $this->instagramWorker = $instagramWorker;
+ $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
+ ->addAttributeToSelect('*')
+ ->addAttributeToFilter(
+ 'posted_to_instagram',
+ [
+ 'or' => [
+ 0 => ['eq' => 0],
+ 1 => ['is' => new \Zend_Db_Expr('NULL')],
+ ]
+ ],
+ 'left'
+ );
+
+ $collection->getSelect()->limit($limit);
+
+ if($collection->count() > 0) {
+ $this->instagramWorker
+ ->postInstagramByProductCollection($collection);
+ }
+
+ } catch (\Exception $e) {
+
+ }
+
+ return;
+ }
+}
\ No newline at end of file
diff --git a/Helper/Data.php b/Helper/Data.php
index 67719e3..f0b58ae 100644
--- a/Helper/Data.php
+++ b/Helper/Data.php
@@ -3,403 +3,269 @@
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)) {
+ $this->_generateInstagramImage(
+ $imageResized,
+ $imageDir,
+ $width,
+ $height
+ );
+ }
- /**
- * 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;
- }
+ $this->_convertWrongFormatImage(
+ $imageResized,
+ $wrongImageFormat,
+ $extOriginal,
+ $quality
+ );
+ }
- return [
- 'username' => $this->getUsernameInfo($store),
- 'password' => $this->getPwdInfo($store)
- ];
- }
+ return $imageResized;
+ }
- /**
- * 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);
- }
+ return false;
+
+ } catch (\Magento\Framework\Exception\FileSystemException $e) {
+ $this->logger->critical($e);
+ return false;
+ }
- /**
- * 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);
}
/**
- * Get Default Image URL Path
+ * Generate Image
*
- * @param null $store
- * @return string
- * @throws \Magento\Framework\Exception\FileSystemException
+ * @param $imageResizedPath
+ * @param $imageDir
+ * @param $width
+ * @param $height
*/
- public function getDefaultImage($store = null)
- {
- $uploadDir = \GhoSter\AutoInstagramPost\Model\Config\Backend\Image::UPLOAD_DIR;
+ 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) {
- $image = $this->scopeConfig->getValue(
- self::XML_PATH_DEFAULT_IMAGE,
- \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
- $store);
-
- if (!$image) {
- return '';
}
- $imagePath = $this->directory_list->getPath('media')
- . DIRECTORY_SEPARATOR . $uploadDir
- . DIRECTORY_SEPARATOR . $image;
-
- return $imagePath;
- }
+ return;
- /**
- * 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
+ * Convert Non JPG format
*
- * @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
- *
- * @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->addAttributeToFilter('entity_id', $product->getCategoryIds());
+ $collection->addNameToResult();
- 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;
- }
-
- /**
- * Get Category Tags
- *
- * @param $_product \Magento\Catalog\Model\Product
- * @return string
- */
- public function getCategoriesHashtags($_product)
- {
-
- $hashTagsStripped = [];
- $html = '';
- if ($this->isEnableCategoryHashtag() && $this->isEnableHashtag()) {
+ } catch (\Exception $e) {
- $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)) {
- foreach ($hashTagsStripped as $hashTag) {
+ if (!empty($hashTagsStrippedData)) {
+ foreach ($hashTagsStrippedData as $hashTag) {
$html .= '#' . $hashTag . self::SPACE_STRING;
}
}
@@ -409,58 +275,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 +321,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/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 c1897de..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,14 +28,14 @@ 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 $directory_list;
- protected $helper;
+ protected $directoryList;
+ protected $config;
protected $logger;
@@ -32,34 +43,32 @@ 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 $directory_list
- * @param \GhoSter\AutoInstagramPost\Helper\Data $helper
- * @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 $directory_list,
- \GhoSter\AutoInstagramPost\Helper\Data $helper,
- \Psr\Log\LoggerInterface $logger,
+ DirectoryList $directoryList,
+ InstagramConfig $config,
+ LoggerInterface $logger,
array $data = []
)
{
$this->logger = $logger;
- $this->helper = $helper;
+ $this->config = $config;
- if ($this->helper->isModuleEnabled()) {
- $account = $this->helper->getAccountInformation();
- $this->device_id = $this->generateDeviceId(md5($account['username'] . $account['password']));
+ if ($this->config->isEnabled()) {
+ $account = $this->config->getAccountInformation();
+ $this->deviceId = $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;
}
@@ -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,
]);
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 966eb71..67e4e29 100644
--- a/Observer/Catalog/ProductSaveAfter.php
+++ b/Observer/Catalog/ProductSaveAfter.php
@@ -2,95 +2,50 @@
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;
+use GhoSter\AutoInstagramPost\Model\Instagram\Worker as InstagramWorker;
+use GhoSter\AutoInstagramPost\Model\Config as InstagramConfig;
+use GhoSter\AutoInstagramPost\Helper\Data as InstagramHelper;
+
class ProductSaveAfter implements ObserverInterface
{
/**
- * @var \GhoSter\AutoInstagramPost\Helper\Data
- */
- protected $_helper;
-
- /**
- * @var Logger
+ * @var InstagramHelper
*/
- protected $_logger;
+ protected $instagramHelper;
/**
- * @var \Magento\Framework\Message\ManagerInterface
+ * @var InstagramConfig
*/
- protected $_messageManager;
-
- /**
- * @var array
- */
- protected $_account;
-
+ protected $config;
/**
- * @var Instagram
+ * @var MessageManager
*/
- protected $_instagram;
+ protected $messageManager;
- /**
- * @var \Magento\Framework\App\Filesystem\DirectoryList
- */
- protected $_directoryList;
-
- /**
- * @var \Magento\Catalog\Model\ResourceModel\Product\Action
- */
- protected $_action;
-
- /**
- * Store manager
- *
- * @var \Magento\Store\Model\StoreManagerInterface
- */
- protected $_storeManager;
+ /** @var InstagramWorker */
+ protected $instagramWorker;
- /**
- * @var ImageProcessor
- */
- protected $imageProcessor;
- /**
- * ProductSaveAfter constructor.
- * @param \Magento\Framework\App\Action\Context $context
- * @param \GhoSter\AutoInstagramPost\Helper\Data $helper
- * @param Instagram $instagram
- * @param ImageProcessor $imageProcessor
- * @param Logger $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,
- Instagram $instagram,
- ImageProcessor $imageProcessor,
- Logger $logger,
- \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
- \Magento\Store\Model\StoreManagerInterface $storeManager,
- \Magento\Catalog\Model\ResourceModel\Product\Action $action
+ ActionContext $context,
+ InstagramHelper $instagramHelper,
+ InstagramConfig $config,
+ InstagramWorker $instagramWorker
)
{
- $this->_helper = $helper;
- $this->_instagram = $instagram;
- $this->imageProcessor = $imageProcessor;
- $this->_logger = $logger;
- $this->_directoryList = $directoryList;
-
- $this->_account = $this->_helper->getAccountInformation();
- $this->_messageManager = $context->getMessageManager();
- $this->_storeManager = $storeManager;
- $this->_action = $action;
+ $this->instagramHelper = $instagramHelper;
+ $this->config = $config;
+ $this->instagramWorker = $instagramWorker;
+ $this->messageManager = $context->getMessageManager();
}
@@ -98,102 +53,55 @@ 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->_helper->isModuleEnabled()) {
+ if (!$this->config->isEnabled()) {
return;
}
- if (!$this->_helper->isObserverEnabled()) {
+ if (!$this->config->isObserverEnabled()) {
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);
-
- // Start to Send Image to Instagram
- if ($image) {
+ try {
- $caption = $this->_helper->getInstagramPostDescription($product);
+ $result = $this->instagramWorker->postInstagramByProduct($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.')
+ );
}
}
}
-
- /**
- * Get Instagram Client
- *
- * @return \GhoSter\AutoInstagramPost\Model\Instagram
- */
- private function _getInstagram()
- {
- 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 @@
-