| 1 |
<?php |
| 2 |
|
| 3 |
namespace Getwid\AI; |
| 4 |
|
| 5 |
use WP_REST_Request; |
| 6 |
|
| 7 |
final class AI { |
| 8 |
|
| 9 |
private $api_url; |
| 10 |
private $namespace = 'getwid/ai/v1'; |
| 11 |
|
| 12 |
public function __construct() { |
| 13 |
|
| 14 |
$this->api_url = defined( 'GETWID_AI_API_URL' ) ? GETWID_AI_API_URL : 'https://api2.getmotopress.com'; |
| 15 |
|
| 16 |
add_action( 'rest_api_init', array( $this, 'register_rest_routes' ) ); |
| 17 |
|
| 18 |
$this->register_user_meta(); |
| 19 |
} |
| 20 |
|
| 21 |
public function register_user_meta() { |
| 22 |
|
| 23 |
register_meta( |
| 24 |
'user', |
| 25 |
'getwid_ai_accept_terms', |
| 26 |
[ |
| 27 |
'type' => 'boolean', |
| 28 |
'single' => true, |
| 29 |
'show_in_rest' => true |
| 30 |
] |
| 31 |
); |
| 32 |
} |
| 33 |
|
| 34 |
public function register_rest_routes() { |
| 35 |
|
| 36 |
register_rest_route( $this->namespace, '/chat', array( |
| 37 |
'methods' => 'POST', |
| 38 |
'callback' => array( $this, 'chat_callback' ), |
| 39 |
'permission_callback' => array( $this, 'permissions_check' ), |
| 40 |
'args' => array( |
| 41 |
'prompt' => array( |
| 42 |
'required' => true, |
| 43 |
'type' => 'string', |
| 44 |
'minLength' => 4 |
| 45 |
) |
| 46 |
) |
| 47 |
) ); |
| 48 |
} |
| 49 |
|
| 50 |
public function permissions_check() { |
| 51 |
|
| 52 |
if ( current_user_can( 'edit_posts' ) ) { |
| 53 |
return true; |
| 54 |
} |
| 55 |
|
| 56 |
return false; |
| 57 |
} |
| 58 |
|
| 59 |
public function chat_callback( WP_REST_Request $request ) { |
| 60 |
|
| 61 |
$ai_request = new AIRequest(); |
| 62 |
|
| 63 |
return $ai_request->stream( $this->api_url . '/api/getwid-ai/v1/chat', $request->get_params() ); |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
new AI(); |
| 68 |
|