AntonLV 2 лет назад
Родитель
Сommit
adac52c9c6

+ 58 - 24
inc/classes/BxDolAI.php

@@ -141,6 +141,7 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
             'active' => true
             'active' => true
         ]);
         ]);
     }
     }
+
     public function getAutomatorsScheduler()
     public function getAutomatorsScheduler()
     {
     {
         $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'schedulers', 'active' => true]);
         $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'schedulers', 'active' => true]);
@@ -151,6 +152,16 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
         return $aAutomators;
         return $aAutomators;
     }
     }
 
 
+    public function getAutomatorsWebhook($iProviderId)
+    {
+        $aAutomators = $this->_oDb->getAutomatorsBy(['sample' => 'webhooks', 'provider_id' => $iProviderId, 'active' => true]);
+        foreach($aAutomators as &$aAutomator)
+            if(!empty($aAutomator['params']))
+                $aAutomator['params'] = json_decode($aAutomator['params'], true);
+
+        return $aAutomators;
+    }
+
     public function callAutomator($sType, $aParams = [])
     public function callAutomator($sType, $aParams = [])
     {
     {
         $sMethod = '_callAutomator' . bx_gen_method_name($sType);
         $sMethod = '_callAutomator' . bx_gen_method_name($sType);
@@ -177,43 +188,66 @@ class BxDolAI extends BxDolFactory implements iBxDolSingleton
         
         
         $this->evalCode($aParams['automator'], true);
         $this->evalCode($aParams['automator'], true);
     }
     }
-    
-    
+
+    protected function _callAutomatorWebhook($aParams = [])
+    {
+        if(!isset($aParams['automator']))
+            return false;
+
+        $this->evalCode($aParams['automator'], true);
+    }
+
     public function evalCode($aAutomator, $isWriteLog = true, $aParams = null)
     public function evalCode($aAutomator, $isWriteLog = true, $aParams = null)
     {
     {
         ob_start();
         ob_start();
         set_error_handler("evalErrorHandler");
         set_error_handler("evalErrorHandler");
-        try{
-             $sCode = '';
-             if ($aAutomator['type'] == 'scheduler'){
-                 $sCode = $aAutomator['code'] . '; onCron();';
-             }
-             
-             if ($aAutomator['type'] == 'event'){
-                 $sCode = $aAutomator['code']. '; onAlert($aParams["alert"]->iObject , $aParams["alert"]->iSender , $aParams["alert"]->aExtras);';  
-             }
-             
-             
-             eval($sCode);
-            
+        try {
+            $sCode = '';
+            switch($aAutomator['type']) {
+                case BX_DOL_AI_AUTOMATOR_EVENT:
+                    $sCode = $aAutomator['code']. '; onAlert($aParams["alert"]->iObject , $aParams["alert"]->iSender , $aParams["alert"]->aExtras);';
+                    break;
+                
+                case BX_DOL_AI_AUTOMATOR_SCHEDULER:
+                    $sCode = $aAutomator['code'] . '; onCron();';
+                    break;
+
+                case BX_DOL_AI_AUTOMATOR_WEBHOOK:
+                    $sCode = $aAutomator['code'] . '; onHook();';
+                    break;
+            }
+
+            eval($sCode);
         }
         }
         catch (Exception $oException) {
         catch (Exception $oException) {
             if ($isWriteLog){
             if ($isWriteLog){
-                $this->writeLog($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
+                $this->log($oException->getFile() . ':' . $oException->getLine() . ' ' . $oException->getMessage());
             }
             }
             return $oException->getMessage();
             return $oException->getMessage();
-        } finally {
-             $sOutput = ob_get_clean();
-             if ($sOutput != '')
+        } 
+        finally {
+            $sOutput = ob_get_clean();
+            if($sOutput != '')
                 return "Eval error: " . $sOutput;
                 return "Eval error: " . $sOutput;
+
             restore_error_handler();
             restore_error_handler();
         }
         }
     }
     }
-    
-    private function writeLog($sString)
-	{
-        bx_log('sys_agents', $sString);
-	}
+
+    public function log($mixedContents, $sSection = '')
+    {
+        if(is_array($mixedContents))
+            $mixedContents = var_export($mixedContents, true);	
+        else if(is_object($mixedContents))
+            $mixedContents = json_encode($mixedContents);
+
+        if(empty($sSection))
+            $sSection = "Core";
+
+        $sTitle .= "\n";
+
+        bx_log('sys_agents', ":\n[" . $sSection . "] " . $mixedContents);
+    }
 }
 }
 
 
 class EvalException extends Exception {}
 class EvalException extends Exception {}

+ 4 - 4
inc/classes/BxDolAIModel.php

@@ -85,11 +85,9 @@ class BxDolAIModel extends BxDol
     /**
     /**
      * Internal methods.
      * Internal methods.
      */
      */
-    protected function _log($mixedError, $bUseLog = false)
+    protected function _log($mixedError, $bUseLog = true)
     {
     {
-        if($bUseLog)
-            bx_log('sys_agents', $mixedError);
-        else {
+        if(!$bUseLog) {
             $sMessage = 'Error occurred';
             $sMessage = 'Error occurred';
             if(is_string($mixedError))
             if(is_string($mixedError))
                 $sMessage = $mixedError;
                 $sMessage = $mixedError;
@@ -98,6 +96,8 @@ class BxDolAIModel extends BxDol
 
 
             throw new Exception($sMessage);
             throw new Exception($sMessage);
         }
         }
+        else
+            BxDolAI::getInstance()->log($mixedError, 'Models');
 
 
         return false;
         return false;
     }    
     }    

+ 1 - 0
inc/classes/BxDolAIModelGpt40.php

@@ -13,6 +13,7 @@ class BxDolAIModelGpt40 extends BxDolAIModel
 
 
     protected $_sEndpoint;
     protected $_sEndpoint;
     protected $_sEndpointRuns;
     protected $_sEndpointRuns;
+    protected $_sEndpointRunsCheck;
     protected $_sEndpointMessages;
     protected $_sEndpointMessages;
 
 
     public function __construct($aModel)
     public function __construct($aModel)

+ 10 - 4
inc/classes/BxDolAIProvider.php

@@ -109,13 +109,19 @@ class BxDolAIProvider extends BxDol
     /**
     /**
      * Internal methods.
      * Internal methods.
      */
      */
-    protected function _log($sMessage, $bUseLog = false)
+    protected function _log($mixedError, $bUseLog = true)
     {
     {
-        if($bUseLog) {
-            //TODO: Use bx_log here.
+        if(!$bUseLog) {
+            $sMessage = 'Error occurred';
+            if(is_string($mixedError))
+                $sMessage = $mixedError;
+            else if(is_array($mixedError) && isset($mixedError['message']))
+                $sMessage = $mixedError['message'];
+
+            throw new Exception($sMessage);
         }
         }
         else
         else
-            throw new Exception($sMessage);
+            BxDolAI::getInstance()->log($mixedError, 'Providers');
 
 
         return false;
         return false;
     }    
     }    

+ 22 - 7
inc/classes/BxDolAIProviderShopifyAdmin.php

@@ -77,13 +77,22 @@ class BxDolAIProviderShopifyAdmin extends BxDolAIProvider
 
 
     public function processActionWebhook()
     public function processActionWebhook()
     {
     {
-        /**
-         * TODO: 
-         * 1. Verify Webhook
-         * 2. Call automators which use this provider.
-         */
-
-        echo 'TODO: Webhook processing here';
+        $sHmacHeader = isset($_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256']) ? $_SERVER['HTTP_X_SHOPIFY_HMAC_SHA256'] : '';
+        $sData = @file_get_contents('php://input');
+        if(!$this->_verifyWebhook($sData, $sHmacHeader)) {
+            http_response_code(401);
+            return;
+        }
+
+        $oAi = BxDolAI::getInstance();
+
+        $aAutomators = $oAi->getAutomatorsWebhook($this->_iId);
+        foreach($aAutomators as $aAutomator)
+            $oAi->callAutomator(BX_DOL_AI_AUTOMATOR_WEBHOOK, [
+                'automator' => $aAutomator
+            ]);
+
+        http_response_code(200);
     }
     }
 
 
     public function call($sRequest, $aParams, $sMethod = 'post-json', $aHeaders = [])
     public function call($sRequest, $aParams, $sMethod = 'post-json', $aHeaders = [])
@@ -112,4 +121,10 @@ class BxDolAIProviderShopifyAdmin extends BxDolAIProvider
     {
     {
         return date("Y-m-d", $iTimestamp);
         return date("Y-m-d", $iTimestamp);
     }
     }
+
+    protected function _verifyWebhook($sData, $sHmacHeader)
+    {
+        $sHmacCalc = base64_encode(hash_hmac('sha256', $sData, $this->getOption('secret_key'), true));
+        return hash_equals($sHmacCalc, $sHmacHeader);
+    }
 }
 }

+ 25 - 2
inc/classes/BxDolAIQuery.php

@@ -141,6 +141,27 @@ class BxDolAIQuery extends BxDolDb
                 }
                 }
                 break;
                 break;
 
 
+            case 'webhooks':
+                $aMethod['params'][1] = [
+                    'type' => BX_DOL_AI_AUTOMATOR_WEBHOOK,
+                ];
+
+                $sWhereClause .= " AND `taa`.`type`=:type";
+
+                if(isset($aParams['provider_id'])) {
+                    $aMethod['params'][1]['provider_id'] = (int)$aParams['provider_id'];
+
+                    $sJoinClause = "INNER JOIN `sys_agents_automators_providers` AS `tap` ON `taa`.`id`=`tap`.`automator_id`";
+                    $sWhereClause .= " AND `tap`.`provider_id`=:provider_id";
+                }
+
+                if(isset($aParams['active'])) {
+                    $aMethod['params'][1]['active'] = (int)$aParams['active'];
+
+                    $sWhereClause .= " AND `taa`.`active`=:active";
+                }
+                break;
+
             case 'providers_by_id_pairs':
             case 'providers_by_id_pairs':
                 $aMethod['name'] = 'getPairs';
                 $aMethod['name'] = 'getPairs';
                 $aMethod['params'][1] = 'id';
                 $aMethod['params'][1] = 'id';
@@ -340,10 +361,12 @@ class BxDolAIQuery extends BxDolDb
 
 
     public function insertProviderValue($aParamsSet)
     public function insertProviderValue($aParamsSet)
     {
     {
-        if(empty($aParamsSet))
+        if(empty($aParamsSet) || !is_array($aParamsSet) || !isset($aParamsSet['value']))
             return false;
             return false;
 
 
-        return (int)$this->query("INSERT INTO `sys_agents_providers_values` SET " . $this->arrayToSQL($aParamsSet)) > 0 ? (int)$this->lastId() : false;
+        return (int)$this->query("INSERT INTO `sys_agents_providers_values` SET " . $this->arrayToSQL($aParamsSet) . " ON DUPLICATE KEY UPDATE `value`=:value", [
+            'value' => $aParamsSet['value']
+        ]) > 0 ? (int)$this->lastId() : false;
     }
     }
 
 
     public function updateProviderValue($aParamsSet, $aParamsWhere)
     public function updateProviderValue($aParamsSet, $aParamsWhere)

+ 2 - 3
studio/template/scripts/BxBaseStudioAgentsProviders.php

@@ -93,11 +93,10 @@ class BxBaseStudioAgentsProviders extends BxDolStudioAgentsProviders
 
 
             if(!empty($aProviderInfo['options']) && is_array($aProviderInfo['options']))
             if(!empty($aProviderInfo['options']) && is_array($aProviderInfo['options']))
                 foreach($aProviderInfo['options'] as $aOption)
                 foreach($aProviderInfo['options'] as $aOption)
-                    $this->_oDb->updateProviderValue([
-                        'value' => $oForm->getCleanValue($aOption['name'])
-                    ], [
+                    $this->_oDb->insertProviderValue([
                         'provider_id' => $iId, 
                         'provider_id' => $iId, 
                         'option_id' => $aOption['id'],
                         'option_id' => $aOption['id'],
+                        'value' => $oForm->getCleanValue($aOption['name'])
                     ]);
                     ]);
 
 
             return echoJson(['grid' => $this->getCode(false), 'blink' => $iId]);
             return echoJson(['grid' => $this->getCode(false), 'blink' => $iId]);