更新
This commit is contained in:
@@ -0,0 +1 @@
|
||||
deny from all
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
declare (strict_types = 1);
|
||||
|
||||
namespace app;
|
||||
|
||||
use think\Service;
|
||||
|
||||
/**
|
||||
* 应用服务类
|
||||
*/
|
||||
class AppService extends Service
|
||||
{
|
||||
public function register()
|
||||
{
|
||||
// 服务注册
|
||||
}
|
||||
|
||||
public function boot()
|
||||
{
|
||||
// 服务启动
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
declare (strict_types = 1);
|
||||
|
||||
namespace app;
|
||||
|
||||
use think\App;
|
||||
use think\exception\ValidateException;
|
||||
use think\Validate;
|
||||
|
||||
/**
|
||||
* 控制器基础类
|
||||
*/
|
||||
abstract class BaseController
|
||||
{
|
||||
/**
|
||||
* Request实例
|
||||
* @var \think\Request
|
||||
*/
|
||||
protected $request;
|
||||
|
||||
/**
|
||||
* 应用实例
|
||||
* @var \think\App
|
||||
*/
|
||||
protected $app;
|
||||
|
||||
/**
|
||||
* 是否批量验证
|
||||
* @var bool
|
||||
*/
|
||||
protected $batchValidate = false;
|
||||
|
||||
/**
|
||||
* 控制器中间件
|
||||
* @var array
|
||||
*/
|
||||
protected $middleware = [];
|
||||
|
||||
/**
|
||||
* 构造方法
|
||||
* @access public
|
||||
* @param App $app 应用对象
|
||||
*/
|
||||
public function __construct(App $app)
|
||||
{
|
||||
$this->app = $app;
|
||||
$this->request = $this->app->request;
|
||||
|
||||
// 控制器初始化
|
||||
$this->initialize();
|
||||
}
|
||||
|
||||
// 初始化
|
||||
protected function initialize()
|
||||
{}
|
||||
|
||||
/**
|
||||
* 验证数据
|
||||
* @access protected
|
||||
* @param array $data 数据
|
||||
* @param string|array $validate 验证器名或者验证规则数组
|
||||
* @param array $message 提示信息
|
||||
* @param bool $batch 是否批量验证
|
||||
* @return array|string|true
|
||||
* @throws ValidateException
|
||||
*/
|
||||
protected function validate(array $data, string|array $validate, array $message = [], bool $batch = false)
|
||||
{
|
||||
if (is_array($validate)) {
|
||||
$v = new Validate();
|
||||
$v->rule($validate);
|
||||
} else {
|
||||
if (strpos($validate, '.')) {
|
||||
// 支持场景
|
||||
[$validate, $scene] = explode('.', $validate);
|
||||
}
|
||||
$class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
|
||||
$v = new $class();
|
||||
if (!empty($scene)) {
|
||||
$v->scene($scene);
|
||||
}
|
||||
}
|
||||
|
||||
$v->message($message);
|
||||
|
||||
// 是否批量验证
|
||||
if ($batch || $this->batchValidate) {
|
||||
$v->batch(true);
|
||||
}
|
||||
|
||||
return $v->failException(true)->check($data);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
namespace app;
|
||||
|
||||
use think\db\exception\DataNotFoundException;
|
||||
use think\db\exception\ModelNotFoundException;
|
||||
use think\exception\Handle;
|
||||
use think\exception\HttpException;
|
||||
use think\exception\HttpResponseException;
|
||||
use think\exception\ValidateException;
|
||||
use think\Response;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 应用异常处理类
|
||||
*/
|
||||
class ExceptionHandle extends Handle
|
||||
{
|
||||
/**
|
||||
* 不需要记录信息(日志)的异常类列表
|
||||
* @var array
|
||||
*/
|
||||
protected $ignoreReport = [
|
||||
HttpException::class,
|
||||
HttpResponseException::class,
|
||||
ModelNotFoundException::class,
|
||||
DataNotFoundException::class,
|
||||
ValidateException::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* 记录异常信息(包括日志或者其它方式记录)
|
||||
*
|
||||
* @access public
|
||||
* @param Throwable $exception
|
||||
* @return void
|
||||
*/
|
||||
public function report(Throwable $exception): void
|
||||
{
|
||||
// 使用内置的方式记录异常日志
|
||||
parent::report($exception);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an exception into an HTTP response.
|
||||
*
|
||||
* @access public
|
||||
* @param \think\Request $request
|
||||
* @param Throwable $e
|
||||
* @return Response
|
||||
*/
|
||||
public function render($request, Throwable $e): Response
|
||||
{
|
||||
// 添加自定义异常处理机制
|
||||
|
||||
// 其他错误交给系统处理
|
||||
return parent::render($request, $e);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
namespace app;
|
||||
|
||||
// 应用请求对象类
|
||||
class Request extends \think\Request
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
<?php
|
||||
// 应用公共文件
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace app\controller;
|
||||
|
||||
use app\BaseController;
|
||||
|
||||
class Index extends BaseController
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return $this->serveSpa('index.html');
|
||||
}
|
||||
|
||||
private function serveSpa(string $file)
|
||||
{
|
||||
$path = rtrim(public_path($file), '/\\');
|
||||
if (!is_file($path)) {
|
||||
return response('前端尚未编译,请在项目根目录执行 npm run build', 503, [
|
||||
'Content-Type' => 'text/plain; charset=utf-8',
|
||||
]);
|
||||
}
|
||||
|
||||
return response(file_get_contents($path), 200, [
|
||||
'Content-Type' => 'text/html; charset=utf-8',
|
||||
]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
|
||||
namespace app\controller\api;
|
||||
|
||||
use app\model\User;
|
||||
use app\model\MembershipLevel;
|
||||
use app\model\Role;
|
||||
use app\service\JwtService;
|
||||
use app\service\SettingsService;
|
||||
use app\service\UserContextService;
|
||||
|
||||
class Auth extends BaseApi
|
||||
{
|
||||
public function guest()
|
||||
{
|
||||
$guestKey = strtolower(trim((string) $this->request->post('guest_key', '')));
|
||||
if (!preg_match('/^[a-f0-9]{64}$/', $guestKey)) {
|
||||
return $this->error('游客标识无效,请刷新页面重试', 422);
|
||||
}
|
||||
|
||||
// Only persist a one-way fingerprint; the random browser key remains the credential.
|
||||
$fingerprint = hash('sha256', $guestKey);
|
||||
$username = 'guest_' . substr($fingerprint, 0, 32);
|
||||
$user = User::where('username', $username)->find();
|
||||
|
||||
if (!$user) {
|
||||
$roleId = Role::where('slug', 'user')->value('id');
|
||||
$membershipId = MembershipLevel::where('slug', 'free')->value('id') ?: 1;
|
||||
|
||||
try {
|
||||
$user = User::create([
|
||||
'username' => $username,
|
||||
'email' => $username . '@guest.local',
|
||||
'password_hash' => password_hash(bin2hex(random_bytes(32)), PASSWORD_BCRYPT),
|
||||
'nickname' => '访客',
|
||||
'role' => 'user',
|
||||
'role_id' => $roleId ?: null,
|
||||
'membership_level_id' => $membershipId,
|
||||
'status' => 'active',
|
||||
]);
|
||||
} catch (\Throwable $exception) {
|
||||
// Two tabs may initialize the same browser guest at the same time.
|
||||
$user = User::where('username', $username)->find();
|
||||
if (!$user) {
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($user->status !== 'active') {
|
||||
return $this->error('游客访问暂不可用', 403);
|
||||
}
|
||||
|
||||
$token = JwtService::generateToken(['user_id' => $user->id]);
|
||||
|
||||
return $this->success([
|
||||
'token' => $token,
|
||||
'user' => $this->formatUser($user->id),
|
||||
], '已进入游客模式');
|
||||
}
|
||||
|
||||
public function register()
|
||||
{
|
||||
$allow = SettingsService::get('allow_register', true);
|
||||
if ($allow !== true && $allow !== 'true') {
|
||||
return $this->error('当前不允许注册');
|
||||
}
|
||||
|
||||
$input = $this->request->post();
|
||||
$username = trim($input['username'] ?? '');
|
||||
$email = trim($input['email'] ?? '');
|
||||
$password = $input['password'] ?? '';
|
||||
|
||||
if (strlen($username) < 3 || strlen($username) > 50) {
|
||||
return $this->error('用户名长度需 3-50 个字符');
|
||||
}
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
||||
return $this->error('邮箱格式不正确');
|
||||
}
|
||||
if (strlen($password) < 6) {
|
||||
return $this->error('密码至少 6 位');
|
||||
}
|
||||
|
||||
if (User::where('username', $username)->whereOr('email', $email)->find()) {
|
||||
return $this->error('用户名或邮箱已存在');
|
||||
}
|
||||
|
||||
$defaultRoleId = \app\model\Role::where('slug', 'user')->value('id');
|
||||
|
||||
$user = User::create([
|
||||
'username' => $username,
|
||||
'email' => $email,
|
||||
'password_hash' => password_hash($password, PASSWORD_BCRYPT),
|
||||
'nickname' => $username,
|
||||
'membership_level_id' => 1,
|
||||
'role_id' => $defaultRoleId ?: null,
|
||||
]);
|
||||
|
||||
$token = JwtService::generateToken(['user_id' => $user->id]);
|
||||
|
||||
return $this->success([
|
||||
'token' => $token,
|
||||
'user' => $this->formatUser($user->id),
|
||||
], '注册成功');
|
||||
}
|
||||
|
||||
public function login()
|
||||
{
|
||||
$input = $this->request->post();
|
||||
$account = trim($input['account'] ?? '');
|
||||
$password = $input['password'] ?? '';
|
||||
|
||||
if (!$account || !$password) {
|
||||
return $this->error('请输入账号和密码');
|
||||
}
|
||||
|
||||
$user = User::where(function ($query) use ($account) {
|
||||
$query->where('username', $account)->whereOr('email', $account);
|
||||
})->where('status', 'active')->find();
|
||||
|
||||
if (!$user || !password_verify($password, $user->password_hash)) {
|
||||
return $this->error('账号或密码错误', 401);
|
||||
}
|
||||
|
||||
$user->save(['last_login_at' => date('Y-m-d H:i:s')]);
|
||||
$token = JwtService::generateToken(['user_id' => $user->id]);
|
||||
|
||||
return $this->success([
|
||||
'token' => $token,
|
||||
'user' => $this->formatUser($user->id),
|
||||
], '登录成功');
|
||||
}
|
||||
|
||||
public function me()
|
||||
{
|
||||
return $this->success($this->authUser());
|
||||
}
|
||||
|
||||
public function updateProfile()
|
||||
{
|
||||
$user = $this->authUser();
|
||||
$nickname = trim($this->request->put('nickname', ''));
|
||||
|
||||
if ($nickname) {
|
||||
User::where('id', $user['id'])->update(['nickname' => $nickname]);
|
||||
}
|
||||
|
||||
return $this->success($this->formatUser($user['id']));
|
||||
}
|
||||
|
||||
public function logout()
|
||||
{
|
||||
return $this->success(null, '已退出');
|
||||
}
|
||||
|
||||
private function formatUser(int $userId): array
|
||||
{
|
||||
return UserContextService::formatPublicUser($userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace app\controller\api;
|
||||
|
||||
use app\BaseController;
|
||||
use think\response\Json;
|
||||
|
||||
class BaseApi extends BaseController
|
||||
{
|
||||
protected function success(mixed $data = null, string $message = 'success', int $httpCode = 200): Json
|
||||
{
|
||||
return json([
|
||||
'code' => 0,
|
||||
'message' => $message,
|
||||
'data' => $data,
|
||||
], $httpCode);
|
||||
}
|
||||
|
||||
protected function error(string $message, int $httpCode = 400, int $code = 1): Json
|
||||
{
|
||||
return json([
|
||||
'code' => $code,
|
||||
'message' => $message,
|
||||
'data' => null,
|
||||
], $httpCode);
|
||||
}
|
||||
|
||||
protected function authUser(): array
|
||||
{
|
||||
return $this->request->authUser ?? [];
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace app\controller\api;
|
||||
|
||||
use app\model\AiModel;
|
||||
use app\model\Conversation as ConversationModel;
|
||||
use app\model\Message;
|
||||
use app\service\ComfyUIService;
|
||||
use app\service\PermissionService;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
class Conversation extends BaseApi
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$user = $this->authUser();
|
||||
$page = max(1, (int) $this->request->get('page', 1));
|
||||
$limit = min(50, max(1, (int) $this->request->get('limit', 20)));
|
||||
|
||||
$query = ConversationModel::alias('c')
|
||||
->leftJoin('ai_models m', 'c.model_id = m.id')
|
||||
->where('c.user_id', $user['id'])
|
||||
->whereNull('c.deleted_at')
|
||||
->field('c.*,m.name as model_name,m.provider as model_provider')
|
||||
->order(['c.is_pinned' => 'desc', 'c.updated_at' => 'desc']);
|
||||
|
||||
$total = (clone $query)->count();
|
||||
$list = $query->page($page, $limit)->select();
|
||||
|
||||
return $this->success([
|
||||
'list' => $list,
|
||||
'total' => $total,
|
||||
'page' => $page,
|
||||
'limit' => $limit,
|
||||
]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$user = $this->authUser();
|
||||
PermissionService::checkConversationLimit($user);
|
||||
|
||||
$input = $this->request->post();
|
||||
$modelId = $input['model_id'] ?? null;
|
||||
if ($modelId !== null && $modelId !== '') {
|
||||
$modelId = (int) $modelId;
|
||||
if ($modelId <= 0) {
|
||||
$modelId = null;
|
||||
}
|
||||
} else {
|
||||
$modelId = null;
|
||||
}
|
||||
|
||||
$conversation = ConversationModel::create([
|
||||
'user_id' => $user['id'],
|
||||
'title' => trim($input['title'] ?? '新对话'),
|
||||
'model_id' => $modelId,
|
||||
]);
|
||||
|
||||
return $this->success($this->findConversation((int) $conversation->id, (int) $user['id']), '创建成功');
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
$user = $this->authUser();
|
||||
return $this->success($this->findConversation((int) $id, (int) $user['id']));
|
||||
}
|
||||
|
||||
public function update($id)
|
||||
{
|
||||
$user = $this->authUser();
|
||||
$conversation = ConversationModel::where('id', $id)
|
||||
->where('user_id', $user['id'])
|
||||
->whereNull('deleted_at')
|
||||
->find();
|
||||
|
||||
if (!$conversation) {
|
||||
return $this->error('会话不存在', 404);
|
||||
}
|
||||
|
||||
$input = $this->request->put();
|
||||
$data = [];
|
||||
if (isset($input['title'])) {
|
||||
$data['title'] = trim($input['title']);
|
||||
}
|
||||
if (isset($input['is_pinned'])) {
|
||||
$data['is_pinned'] = (int) $input['is_pinned'];
|
||||
}
|
||||
if (array_key_exists('model_id', $input)) {
|
||||
$mid = $input['model_id'];
|
||||
if ($mid === null || $mid === '') {
|
||||
$data['model_id'] = null;
|
||||
} else {
|
||||
$data['model_id'] = (int) $mid;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($data)) {
|
||||
return $this->error('无更新内容');
|
||||
}
|
||||
|
||||
$conversation->save($data);
|
||||
return $this->success($this->findConversation((int) $id, (int) $user['id']));
|
||||
}
|
||||
|
||||
public function delete($id)
|
||||
{
|
||||
$user = $this->authUser();
|
||||
$conversation = ConversationModel::where('id', $id)
|
||||
->where('user_id', $user['id'])
|
||||
->whereNull('deleted_at')
|
||||
->find();
|
||||
|
||||
if (!$conversation) {
|
||||
return $this->error('会话不存在', 404);
|
||||
}
|
||||
|
||||
$conversation->save(['deleted_at' => date('Y-m-d H:i:s')]);
|
||||
return $this->success(null, '删除成功');
|
||||
}
|
||||
|
||||
public function messages($id)
|
||||
{
|
||||
$user = $this->authUser();
|
||||
$this->findConversation((int) $id, (int) $user['id']);
|
||||
|
||||
$rows = Message::where('conversation_id', $id)
|
||||
->field('id,role,content,content_type,attachments,created_at')
|
||||
->order('created_at', 'asc')
|
||||
->select();
|
||||
|
||||
$list = [];
|
||||
foreach ($rows as $item) {
|
||||
$attachments = $item->attachments;
|
||||
if (is_string($attachments)) {
|
||||
$attachments = json_decode($attachments, true) ?: [];
|
||||
}
|
||||
if (!is_array($attachments)) {
|
||||
$attachments = [];
|
||||
}
|
||||
|
||||
// 刷新后恢复未完成的 Comfy 生图任务
|
||||
$stillPending = false;
|
||||
$pendingJob = ComfyUIService::findPendingJob($attachments);
|
||||
if ($pendingJob && $item->role === 'assistant') {
|
||||
$modelId = (int) ($pendingJob['model_id'] ?? 0);
|
||||
$model = $modelId > 0 ? AiModel::find($modelId) : null;
|
||||
if ($model) {
|
||||
$recovered = ComfyUIService::recoverPendingMessage([
|
||||
'id' => (int) $item->id,
|
||||
'content' => (string) $item->content,
|
||||
'attachments' => $attachments,
|
||||
], $model, (int) $user['id']);
|
||||
|
||||
$item->content = $recovered['content'];
|
||||
$item->attachments = $recovered['attachments'];
|
||||
$attachments = $recovered['attachments'];
|
||||
$stillPending = empty($recovered['finished']);
|
||||
|
||||
Message::where('id', $item->id)->update([
|
||||
'content' => $recovered['content'],
|
||||
'attachments' => json_encode($recovered['attachments'], JSON_UNESCAPED_UNICODE),
|
||||
]);
|
||||
} else {
|
||||
$stillPending = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($item->role === 'assistant' && trim((string) $item->content) === '') {
|
||||
if (empty($attachments) || !ComfyUIService::hasImageAttachments($attachments)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// 前端只展示真实媒体附件;pending 任务信息已体现在 content 文案中
|
||||
$visibleAttachments = array_values(array_filter(
|
||||
$attachments,
|
||||
fn ($a) => is_array($a) && ($a['type'] ?? '') !== ComfyUIService::JOB_TYPE
|
||||
));
|
||||
|
||||
$list[] = [
|
||||
'id' => $item->id,
|
||||
'role' => $item->role,
|
||||
'content' => $item->content,
|
||||
'content_type' => $item->content_type,
|
||||
'attachments' => $visibleAttachments,
|
||||
'pending_job' => $stillPending,
|
||||
'pending_image_count' => $stillPending ? (int) ($pendingJob['image_count'] ?? 0) : 0,
|
||||
'created_at' => $item->created_at,
|
||||
];
|
||||
}
|
||||
|
||||
return $this->success($list);
|
||||
}
|
||||
|
||||
private function findConversation(int $id, int $userId): array
|
||||
{
|
||||
$conversation = ConversationModel::alias('c')
|
||||
->leftJoin('ai_models m', 'c.model_id = m.id')
|
||||
->where('c.id', $id)
|
||||
->where('c.user_id', $userId)
|
||||
->whereNull('c.deleted_at')
|
||||
->field('c.*,m.name as model_name,m.provider as model_provider')
|
||||
->find();
|
||||
|
||||
if (!$conversation) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => '会话不存在',
|
||||
'data' => null,
|
||||
], 404));
|
||||
}
|
||||
|
||||
return $conversation->toArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace app\controller\api;
|
||||
|
||||
use app\model\AiModel;
|
||||
use app\service\AgentCatalog;
|
||||
use app\service\SettingsService;
|
||||
|
||||
class Settings extends BaseApi
|
||||
{
|
||||
public function features()
|
||||
{
|
||||
return $this->success(SettingsService::getFeatures());
|
||||
}
|
||||
|
||||
public function publicSettings()
|
||||
{
|
||||
$allow = SettingsService::get('allow_register', true);
|
||||
return $this->success([
|
||||
'site_name' => SettingsService::get('site_name', 'AI Chat'),
|
||||
'allow_register' => $allow === true || $allow === 'true',
|
||||
'features' => SettingsService::getFeatures(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function models()
|
||||
{
|
||||
$list = AiModel::where('enabled', 1)
|
||||
->field('id,name,provider,model_id,is_default,support_context,support_image')
|
||||
->order('sort_order,id')
|
||||
->select();
|
||||
|
||||
return $this->success($list);
|
||||
}
|
||||
|
||||
public function agents()
|
||||
{
|
||||
return $this->success(AgentCatalog::publicList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
namespace app\controller\api;
|
||||
|
||||
use app\model\UploadFile;
|
||||
use app\service\PermissionService;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
class Upload extends BaseApi
|
||||
{
|
||||
public function upload()
|
||||
{
|
||||
$user = $this->authUser();
|
||||
$file = $this->request->file('file');
|
||||
|
||||
if (!$file) {
|
||||
return $this->error('请选择文件');
|
||||
}
|
||||
|
||||
try {
|
||||
$ext = strtolower($file->extension() ?: pathinfo($file->getOriginalName(), PATHINFO_EXTENSION));
|
||||
$ext = $ext ?: 'bin';
|
||||
$mime = $this->resolveMime($file, $ext);
|
||||
$fileType = $this->detectFileType($mime, $ext);
|
||||
|
||||
if (!empty($user['is_guest']) && $fileType === 'image') {
|
||||
return $this->error('游客模式不支持发送图片,请登录后再上传', 403);
|
||||
}
|
||||
|
||||
if ($fileType === 'document' && !in_array($mime, config('upload.allowed_documents'), true)) {
|
||||
$mime = self::DOCUMENT_MIME_BY_EXT[$ext] ?? $mime;
|
||||
}
|
||||
|
||||
if (!PermissionService::canUpload($user, $fileType)) {
|
||||
return $this->error('您没有权限上传此类型文件或功能未开启', 403);
|
||||
}
|
||||
|
||||
$maxSize = PermissionService::getMaxUploadSizeMb($user) * 1024 * 1024;
|
||||
if ($file->getSize() > $maxSize) {
|
||||
return $this->error('文件大小超出限制');
|
||||
}
|
||||
|
||||
if (!$this->isAllowedMime($mime, $fileType, $ext)) {
|
||||
return $this->error('不支持的文件类型: ' . $mime);
|
||||
}
|
||||
|
||||
$originalName = $file->getOriginalName();
|
||||
$fileSize = $file->getSize();
|
||||
|
||||
$uploadPath = rtrim(config('upload.path'), '/\\');
|
||||
$this->ensureUploadDir($uploadPath);
|
||||
|
||||
$subdir = date('Y/m/d');
|
||||
$storedBase = uniqid('', true) . '.' . $ext;
|
||||
$storedName = $subdir . '/' . $storedBase;
|
||||
$fullDir = $uploadPath . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $subdir);
|
||||
|
||||
if (!is_dir($fullDir) && !mkdir($fullDir, 0755, true) && !is_dir($fullDir)) {
|
||||
return $this->error('无法创建上传目录,请检查 uploads 权限', 500);
|
||||
}
|
||||
|
||||
if (!is_writable($fullDir)) {
|
||||
return $this->error('上传目录不可写,请执行: chmod -R 775 uploads && chown -R www-data:www-data uploads', 500);
|
||||
}
|
||||
|
||||
$moved = $file->move($fullDir, $storedBase);
|
||||
if (!$moved) {
|
||||
return $this->error('文件保存失败: ' . ($file->getError() ?: '未知错误'), 500);
|
||||
}
|
||||
|
||||
$record = UploadFile::create([
|
||||
'user_id' => $user['id'],
|
||||
'original_name' => $originalName,
|
||||
'stored_name' => $storedBase,
|
||||
'file_path' => $storedName,
|
||||
'mime_type' => $mime,
|
||||
'file_size' => $fileSize,
|
||||
'file_type' => $fileType,
|
||||
]);
|
||||
|
||||
return $this->success([
|
||||
'id' => $record->id,
|
||||
'url' => '/api/uploads/' . rawurlencode($storedBase),
|
||||
'name' => $originalName,
|
||||
'type' => $fileType,
|
||||
'mime' => $mime,
|
||||
'size' => $fileSize,
|
||||
]);
|
||||
} catch (\think\exception\FileException $e) {
|
||||
return $this->error('文件保存失败: ' . $e->getMessage(), 500);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->error('上传失败: ' . $e->getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function serve($filename)
|
||||
{
|
||||
$filename = basename($filename);
|
||||
$upload = UploadFile::where('stored_name', $filename)
|
||||
->whereOr('file_path', 'like', '%/' . $filename)
|
||||
->find();
|
||||
|
||||
if (!$upload) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => '文件不存在',
|
||||
'data' => null,
|
||||
], 404));
|
||||
}
|
||||
|
||||
$path = rtrim(config('upload.path'), '/\\') . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $upload->file_path);
|
||||
if (!is_file($path)) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => '文件不存在',
|
||||
'data' => null,
|
||||
], 404));
|
||||
}
|
||||
|
||||
$mime = $upload->mime_type ?: (@mime_content_type($path) ?: 'application/octet-stream');
|
||||
|
||||
return response(file_get_contents($path), 200, [
|
||||
'Content-Type' => $mime,
|
||||
'Content-Length' => (string) filesize($path),
|
||||
'Cache-Control' => 'public, max-age=604800',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 文档扩展名 -> 常见但不同系统上可能检测出不一致的 MIME 兜底表。
|
||||
* .doc/.docx 等 Office 文档在不同服务器 fileinfo 版本下识别出的 MIME 差异很大,
|
||||
* 仅靠 MIME 白名单很容易误判为“不支持的文件类型”,因此这里用扩展名兜底放行。
|
||||
*/
|
||||
private const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
|
||||
|
||||
private const VIDEO_EXTENSIONS = ['mp4', 'webm', 'mov'];
|
||||
|
||||
private const DOCUMENT_EXTENSIONS = ['pdf', 'doc', 'docx', 'txt', 'md'];
|
||||
|
||||
private const IMAGE_MIME_BY_EXT = [
|
||||
'jpg' => 'image/jpeg',
|
||||
'jpeg' => 'image/jpeg',
|
||||
'png' => 'image/png',
|
||||
'gif' => 'image/gif',
|
||||
'webp' => 'image/webp',
|
||||
'bmp' => 'image/bmp',
|
||||
];
|
||||
|
||||
private const DOCUMENT_MIME_BY_EXT = [
|
||||
'pdf' => 'application/pdf',
|
||||
'doc' => 'application/msword',
|
||||
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'txt' => 'text/plain',
|
||||
'md' => 'text/markdown',
|
||||
];
|
||||
|
||||
private function resolveMime($file, string $ext): string
|
||||
{
|
||||
$mime = $file->getMime();
|
||||
if (!$mime && is_file($file->getPathname())) {
|
||||
$mime = @mime_content_type($file->getPathname()) ?: '';
|
||||
}
|
||||
|
||||
$mime = strtolower(trim((string) $mime));
|
||||
if ($mime === 'image/jpg') {
|
||||
$mime = 'image/jpeg';
|
||||
}
|
||||
|
||||
if ($mime === '' || $mime === 'application/octet-stream') {
|
||||
$mime = self::IMAGE_MIME_BY_EXT[$ext] ?? self::DOCUMENT_MIME_BY_EXT[$ext] ?? $mime;
|
||||
}
|
||||
|
||||
return $mime ?: 'application/octet-stream';
|
||||
}
|
||||
|
||||
private function ensureUploadDir(string $uploadPath): void
|
||||
{
|
||||
if (is_dir($uploadPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mkdir($uploadPath, 0755, true) && !is_dir($uploadPath)) {
|
||||
throw new \RuntimeException('无法创建 uploads 目录: ' . $uploadPath);
|
||||
}
|
||||
}
|
||||
|
||||
private function detectFileType(string $mime, string $ext = ''): string
|
||||
{
|
||||
$ext = strtolower($ext);
|
||||
|
||||
if (in_array($ext, self::IMAGE_EXTENSIONS, true)) {
|
||||
return 'image';
|
||||
}
|
||||
if (in_array($ext, self::VIDEO_EXTENSIONS, true)) {
|
||||
return 'video';
|
||||
}
|
||||
if (str_starts_with($mime, 'image/')) {
|
||||
return 'image';
|
||||
}
|
||||
if (str_starts_with($mime, 'video/')) {
|
||||
return 'video';
|
||||
}
|
||||
if (str_starts_with($mime, 'audio/')) {
|
||||
return 'audio';
|
||||
}
|
||||
if (in_array($mime, config('upload.allowed_documents'), true)) {
|
||||
return 'document';
|
||||
}
|
||||
if (in_array(strtolower($ext), self::DOCUMENT_EXTENSIONS, true)) {
|
||||
return 'document';
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
|
||||
private function isAllowedMime(string $mime, string $fileType, string $ext = ''): bool
|
||||
{
|
||||
$config = config('upload');
|
||||
return match ($fileType) {
|
||||
'image' => in_array($mime, $config['allowed_images'], true)
|
||||
|| in_array(strtolower($ext), self::IMAGE_EXTENSIONS, true),
|
||||
'video' => in_array($mime, $config['allowed_videos'], true)
|
||||
|| in_array(strtolower($ext), self::VIDEO_EXTENSIONS, true),
|
||||
'audio' => in_array($mime, $config['allowed_audios'], true),
|
||||
'document' => in_array($mime, $config['allowed_documents'], true)
|
||||
|| in_array(strtolower($ext), self::DOCUMENT_EXTENSIONS, true),
|
||||
default => false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
// 事件定义文件
|
||||
return [
|
||||
'bind' => [
|
||||
],
|
||||
|
||||
'listen' => [
|
||||
'AppInit' => [],
|
||||
'HttpRun' => [],
|
||||
'HttpEnd' => [],
|
||||
'LogLevel' => [],
|
||||
'LogWrite' => [],
|
||||
],
|
||||
|
||||
'subscribe' => [
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
// 全局中间件定义文件
|
||||
return [
|
||||
// 全局请求缓存
|
||||
// \think\middleware\CheckRequestCache::class,
|
||||
// 多语言加载
|
||||
// \think\middleware\LoadLangPack::class,
|
||||
// Session初始化
|
||||
// \think\middleware\SessionInit::class
|
||||
];
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace app\middleware;
|
||||
|
||||
use app\service\AdminScopeService;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
class AdminAuth
|
||||
{
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
$user = $request->authUser ?? null;
|
||||
if (!$user || !AdminScopeService::canAccessAdmin($user)) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => '无管理后台访问权限',
|
||||
'data' => null,
|
||||
], 403));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace app\middleware;
|
||||
|
||||
use app\service\JwtService;
|
||||
use think\Response;
|
||||
|
||||
class Cors
|
||||
{
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
|
||||
header('Access-Control-Allow-Headers: Content-Type, Authorization');
|
||||
|
||||
if ($request->method(true) === 'OPTIONS') {
|
||||
return Response::create('', 'html', 204);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace app\middleware;
|
||||
|
||||
use app\model\User;
|
||||
use app\service\JwtService;
|
||||
use app\service\UserContextService;
|
||||
use think\exception\HttpResponseException;
|
||||
use think\Response;
|
||||
|
||||
class JwtAuth
|
||||
{
|
||||
public function handle($request, \Closure $next)
|
||||
{
|
||||
$token = $request->header('Authorization', '');
|
||||
$payload = JwtService::verifyToken($token);
|
||||
|
||||
if (!$payload || empty($payload['user_id'])) {
|
||||
$this->abort('请先登录', 401);
|
||||
}
|
||||
|
||||
$user = User::with(['membership', 'roleModel', 'department'])->find($payload['user_id']);
|
||||
if (!$user || $user->status !== 'active') {
|
||||
$this->abort('请先登录', 401);
|
||||
}
|
||||
|
||||
$request->authUser = UserContextService::formatAuthUser($user);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
private function abort(string $message, int $httpCode = 400): void
|
||||
{
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => $message,
|
||||
'data' => null,
|
||||
], $httpCode));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class AiModel extends Model
|
||||
{
|
||||
protected $name = 'ai_models';
|
||||
protected $autoWriteTimestamp = true;
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = 'updated_at';
|
||||
|
||||
protected $type = [
|
||||
'extra_config' => 'json',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class Conversation extends Model
|
||||
{
|
||||
protected $name = 'conversations';
|
||||
protected $autoWriteTimestamp = true;
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = 'updated_at';
|
||||
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
public function aiModel()
|
||||
{
|
||||
return $this->belongsTo(AiModel::class, 'model_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
|
||||
|
||||
namespace app\model;
|
||||
|
||||
|
||||
|
||||
use think\Model;
|
||||
|
||||
|
||||
|
||||
class Department extends Model
|
||||
|
||||
{
|
||||
|
||||
protected $name = 'departments';
|
||||
|
||||
protected $autoWriteTimestamp = true;
|
||||
|
||||
protected $createTime = 'created_at';
|
||||
|
||||
protected $updateTime = 'updated_at';
|
||||
|
||||
|
||||
|
||||
public function parent()
|
||||
|
||||
{
|
||||
|
||||
return $this->belongsTo(self::class, 'parent_id');
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function children()
|
||||
|
||||
{
|
||||
|
||||
return $this->hasMany(self::class, 'parent_id');
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class MembershipLevel extends Model
|
||||
{
|
||||
protected $name = 'membership_levels';
|
||||
protected $autoWriteTimestamp = true;
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = 'updated_at';
|
||||
|
||||
protected $type = [
|
||||
'permissions' => 'json',
|
||||
'allowed_models' => 'json',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class Message extends Model
|
||||
{
|
||||
protected $name = 'messages';
|
||||
protected $autoWriteTimestamp = 'created_at';
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = false;
|
||||
|
||||
protected $type = [
|
||||
'attachments' => 'json',
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use app\service\PermissionCatalog;
|
||||
use think\Model;
|
||||
|
||||
class Role extends Model
|
||||
{
|
||||
protected $name = 'roles';
|
||||
protected $autoWriteTimestamp = true;
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = 'updated_at';
|
||||
|
||||
public static function defaultPermissions(): array
|
||||
{
|
||||
return PermissionCatalog::emptyPermissions();
|
||||
}
|
||||
|
||||
public function getPermissionsAttr($value): array
|
||||
{
|
||||
return PermissionCatalog::normalize(self::toPermArray($value));
|
||||
}
|
||||
|
||||
public function setPermissionsAttr($value): string
|
||||
{
|
||||
return json_encode(
|
||||
PermissionCatalog::normalize(self::toPermArray($value)),
|
||||
JSON_UNESCAPED_UNICODE
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* ThinkPHP 8 会把 JSON 列转成 \think\model\type\Json,需调用 value() 取出数组。
|
||||
*/
|
||||
private static function toPermArray(mixed $value): array
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_object($value) && method_exists($value, 'value')) {
|
||||
$data = $value->value();
|
||||
return is_array($data) ? $data : [];
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
$decoded = json_decode($value, true);
|
||||
return (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) ? $decoded : [];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class SysPermission extends Model
|
||||
{
|
||||
protected $name = 'sys_permissions';
|
||||
protected $autoWriteTimestamp = true;
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = 'updated_at';
|
||||
|
||||
public function children()
|
||||
{
|
||||
return $this->hasMany(self::class, 'parent_id')->order('sort_order')->order('id');
|
||||
}
|
||||
|
||||
public function parent()
|
||||
{
|
||||
return $this->belongsTo(self::class, 'parent_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class SystemSetting extends Model
|
||||
{
|
||||
protected $name = 'system_settings';
|
||||
protected $autoWriteTimestamp = 'updated_at';
|
||||
protected $updateTime = 'updated_at';
|
||||
protected $createTime = false;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class UploadFile extends Model
|
||||
{
|
||||
protected $name = 'uploads';
|
||||
protected $autoWriteTimestamp = 'created_at';
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = false;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class User extends Model
|
||||
{
|
||||
protected $name = 'users';
|
||||
protected $autoWriteTimestamp = true;
|
||||
protected $createTime = 'created_at';
|
||||
protected $updateTime = 'updated_at';
|
||||
|
||||
public function membership()
|
||||
{
|
||||
return $this->belongsTo(MembershipLevel::class, 'membership_level_id');
|
||||
}
|
||||
|
||||
public function roleModel()
|
||||
{
|
||||
return $this->belongsTo(Role::class, 'role_id');
|
||||
}
|
||||
|
||||
public function department()
|
||||
{
|
||||
return $this->belongsTo(Department::class, 'department_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use think\Model;
|
||||
|
||||
class UserDailyStat extends Model
|
||||
{
|
||||
protected $name = 'user_daily_stats';
|
||||
protected $autoWriteTimestamp = false;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
use app\ExceptionHandle;
|
||||
use app\Request;
|
||||
|
||||
// 容器Provider定义文件
|
||||
return [
|
||||
'think\Request' => Request::class,
|
||||
'think\exception\Handle' => ExceptionHandle::class,
|
||||
];
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
use app\AppService;
|
||||
|
||||
// 系统服务定义文件
|
||||
// 服务在完成全局初始化之后执行
|
||||
return [
|
||||
AppService::class,
|
||||
];
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use app\model\Role;
|
||||
use app\model\User;
|
||||
use app\service\DepartmentService as DeptSvc;
|
||||
use app\service\PermissionCatalog;
|
||||
|
||||
class AdminScopeService
|
||||
{
|
||||
public static function permissions(array $authUser): array
|
||||
{
|
||||
$perms = $authUser['role_permissions'] ?? [];
|
||||
if (!is_array($perms)) {
|
||||
$perms = [];
|
||||
}
|
||||
|
||||
return PermissionCatalog::normalize($perms);
|
||||
}
|
||||
|
||||
public static function hasPermission(array $authUser, string $key): bool
|
||||
{
|
||||
$perms = self::permissions($authUser);
|
||||
|
||||
// 超级管理员 / 旧 admin 角色:全部放行
|
||||
if (($authUser['role'] ?? '') === 'admin' && empty($authUser['role_id'])) {
|
||||
return true;
|
||||
}
|
||||
if (($authUser['role_slug'] ?? '') === 'super_admin') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return PermissionCatalog::hasCode($perms, $key);
|
||||
}
|
||||
|
||||
public static function hasAny(array $authUser, array $keys): bool
|
||||
{
|
||||
foreach ($keys as $key) {
|
||||
if (self::hasPermission($authUser, $key)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function canAccessAdmin(array $authUser): bool
|
||||
{
|
||||
if (($authUser['role'] ?? '') === 'admin') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return self::hasPermission($authUser, 'can_access_admin');
|
||||
}
|
||||
|
||||
public static function requirePermission(array $authUser, string $key): void
|
||||
{
|
||||
if (!self::hasPermission($authUser, $key)) {
|
||||
throw new \think\exception\HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => '无操作权限',
|
||||
'data' => null,
|
||||
], 403));
|
||||
}
|
||||
}
|
||||
|
||||
public static function requireAny(array $authUser, array $keys): void
|
||||
{
|
||||
if (!self::hasAny($authUser, $keys)) {
|
||||
throw new \think\exception\HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => '无操作权限',
|
||||
'data' => null,
|
||||
], 403));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]|null null 表示可见全部用户
|
||||
*/
|
||||
public static function visibleUserIds(array $authUser): ?array
|
||||
{
|
||||
if (self::hasPermission($authUser, 'btn:conv:view_all')
|
||||
|| self::hasPermission($authUser, 'can_view_all_conversations')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (self::hasPermission($authUser, 'btn:conv:view_subordinate')
|
||||
|| self::hasPermission($authUser, 'can_view_subordinate_conversations')) {
|
||||
$departmentId = (int) ($authUser['department_id'] ?? 0);
|
||||
if ($departmentId <= 0) {
|
||||
return [(int) $authUser['id']];
|
||||
}
|
||||
|
||||
$deptIds = DeptSvc::descendantIds($departmentId);
|
||||
$userIds = DeptSvc::userIdsInDepartments($deptIds);
|
||||
|
||||
return array_values(array_unique(array_map('intval', $userIds)));
|
||||
}
|
||||
|
||||
if (($authUser['role'] ?? '') === 'admin') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [(int) $authUser['id']];
|
||||
}
|
||||
|
||||
public static function canViewUser(array $authUser, int $targetUserId): bool
|
||||
{
|
||||
$visible = self::visibleUserIds($authUser);
|
||||
if ($visible === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return in_array($targetUserId, $visible, true);
|
||||
}
|
||||
|
||||
public static function canViewConversation(array $authUser, int $conversationUserId): bool
|
||||
{
|
||||
return self::canViewUser($authUser, $conversationUserId);
|
||||
}
|
||||
|
||||
public static function applyUserScope($query, array $authUser, string $alias = 'u')
|
||||
{
|
||||
$visible = self::visibleUserIds($authUser);
|
||||
if ($visible !== null) {
|
||||
$query->whereIn("{$alias}.id", $visible ?: [0]);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
public static function applyConversationScope($query, array $authUser, string $conversationAlias = 'c')
|
||||
{
|
||||
$visible = self::visibleUserIds($authUser);
|
||||
if ($visible !== null) {
|
||||
$query->whereIn("{$conversationAlias}.user_id", $visible ?: [0]);
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
public static function syncLegacyRoleField(int $userId, ?int $roleId): void
|
||||
{
|
||||
if (!$roleId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$role = Role::find($roleId);
|
||||
if (!$role) {
|
||||
return;
|
||||
}
|
||||
|
||||
$permissions = PermissionCatalog::normalize($role->permissions ?? []);
|
||||
$legacyRole = !empty($permissions['can_access_admin']) ? 'admin' : 'user';
|
||||
User::where('id', $userId)->update(['role' => $legacyRole]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,909 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
class AgentCatalog
|
||||
{
|
||||
public static function all(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'id' => 'auto',
|
||||
'name' => 'Agent',
|
||||
'short_name' => 'Agent',
|
||||
'description' => '自动识别任务并调用合适的语言或图片生成模型',
|
||||
'icon' => 'robot',
|
||||
'accent' => 'blue',
|
||||
'placeholder' => '描述你要完成的任务,Agent 会自动判断并执行',
|
||||
'supports_image' => true,
|
||||
'image_prompt' => 'High-quality purposeful image, coherent composition, clear visual hierarchy, refined lighting and color, faithful to the user request, professional art direction, no readable text, no letters, no Chinese characters, no title, no caption, no watermark.',
|
||||
'system_prompt' => '你是通用自主 Agent。先在内部识别用户的真实目标与任务类型,再选择合适的方法直接完成:规划类任务梳理目标、约束、依赖和执行步骤;代码类任务理解现有约束,定位根因,给出可靠实现与验证;写作类任务判断受众、场景、目标和语气,组织清晰自然的内容;分析类任务核对口径,区分事实、推断与假设,给出证据和建议。不要要求用户先选择任务分类,也不要无意义地复述分类结果。信息足够时直接推进,信息不足时只询问真正阻塞的关键问题。必须理解连续对话中的省略、指代和真实意图,不能只按当前一句做关键词匹配:如果前文正在讨论某个对象“长什么样”、外观、形态、颜色或场景,用户随后说“我看不到”“看不见”“我想看看”“给我看看”“展示一下”等,真实目标就是直接看到该对象的图片;应从最近对话提取主体和视觉特征并执行生图,绝不能回答自己是纯文本模型、建议用户另找绘图工具或继续用文字描述。解析“他、她、它、这个、那个”等代词时,最近一轮由用户明确提到的实体拥有最高优先级;代词的字形或性别绝不能自行把动物、物品、建筑等改成人类。新的知识询问、新主体介绍、图片识别和单纯情绪反馈默认是文本任务,绝不能因为前面生成过图片就继承旧主体或继续生图。“什么鬼”“不对”“胡说”“离谱”等短反馈通常是在质疑上一轮回答,应结合紧邻的助手回复承认偏差、重新核对或询问具体错误,不能把短语当成词条进行字面解释。图片任务必须遵守动作协议:当用户明确或隐含地希望看到、生成、重做或修改图片,评价上一张生成图并期待调整,或确认刚讨论的图片方案(例如“对”“就这样”“按方案三”)时,不要继续讲解或重复确认,只输出一行 JSON:{"action":"generate_image","prompt":"完整、独立、可直接用于生图的最终画面描述"}。prompt 必须以当前图片版本状态为基础,合并本轮要求并保留所有未被本轮明确推翻的历史修改,绝不能擅自退回更早版本的场景、主体、风格或构图;“太 X”通常表示降低 X,“不够 X”表示增强 X,不得反向理解。prompt 的视觉描述以英文为主;用户未要求画面含字时不得保留中文指令词,并必须明确 no text, no letters, no Chinese characters, no title, no caption, no watermark;用户明确给出标题、书名或画面文字时,必须将原文逐字保留为 EXACT_VISIBLE_TEXT: <<<原文>>>,禁止翻译、改写、漏字、换序或另造字符,此时禁止追加 no text/no title 等冲突要求。prompt 只能描述修改完成后真正可见的主体、环境、构图、风格、光线和色彩,不得引用、复述或翻译“生成一张图片”“重新优化”等命令和反馈原句。“在某个环节生成”“接着生成”“帮我生成”等流程、时序和操作措辞不是画面内容,禁止据此添加人物或场景;只有用户明确说画面包含某元素时才能加入。只有缺失会改变核心主体的关键信息且无法从上下文推断时,才简短追问一次。用户只是要求识图、分析图片、编写提示词或询问生成方法时,应正常回答,不得输出图片动作。系统会自动执行动作 JSON,绝不能把 JSON 当作回答展示给用户。用户询问能力时应明确说明可以生成图片,不要声称不支持。不得编造图片链接,也不得在系统没有返回真实图片附件时声称图片已经生成。',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function publicList(): array
|
||||
{
|
||||
return array_map(function (array $agent) {
|
||||
unset($agent['system_prompt'], $agent['supports_image'], $agent['image_prompt']);
|
||||
return $agent;
|
||||
}, self::all());
|
||||
}
|
||||
|
||||
public static function find(?string $id): ?array
|
||||
{
|
||||
if (!$id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (in_array($id, ['planner', 'engineer', 'writer', 'analyst'], true)) {
|
||||
$id = 'auto';
|
||||
}
|
||||
|
||||
foreach (self::all() as $agent) {
|
||||
if ($agent['id'] === $id) {
|
||||
return $agent;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function supportsImage(?array $agent): bool
|
||||
{
|
||||
return $agent !== null && ($agent['supports_image'] ?? false) === true;
|
||||
}
|
||||
|
||||
public static function buildImagePrompt(?array $agent, string $content): string
|
||||
{
|
||||
$content = trim($content);
|
||||
if (!self::supportsImage($agent)) {
|
||||
return $content;
|
||||
}
|
||||
|
||||
$direction = trim((string) ($agent['image_prompt'] ?? ''));
|
||||
if (str_contains($content, 'EXACT_VISIBLE_TEXT: <<<')) {
|
||||
$direction = 'High-quality purposeful image, coherent composition, clear visual hierarchy, refined lighting and color, faithful to the user request, professional art direction.';
|
||||
}
|
||||
return $direction === '' ? $content : $direction . "\n\n" . $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the private action envelope emitted by the language model. The model may
|
||||
* wrap it in a Markdown fence or use the legacy `task` key, so accept both forms.
|
||||
*/
|
||||
public static function parseImageAction(string $content): ?array
|
||||
{
|
||||
$content = trim($content);
|
||||
if ($content === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$candidates = [[
|
||||
'json' => $content,
|
||||
'wrapper' => '',
|
||||
]];
|
||||
if (preg_match_all('/```(?:json)?\s*([\s\S]*?)```/iu', $content, $fences, PREG_OFFSET_CAPTURE)) {
|
||||
foreach ($fences[1] as $index => $match) {
|
||||
$fullMatch = $fences[0][$index];
|
||||
$candidates[] = [
|
||||
'json' => $match[0],
|
||||
'wrapper' => substr($content, 0, $fullMatch[1])
|
||||
. substr($content, $fullMatch[1] + strlen($fullMatch[0])),
|
||||
];
|
||||
}
|
||||
}
|
||||
foreach (self::extractJsonObjects($content) as $object) {
|
||||
$candidates[] = $object;
|
||||
}
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
if (!self::allowsImageActionWrapper((string) ($candidate['wrapper'] ?? ''))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$json = trim((string) preg_replace(
|
||||
'/^```(?:json)?\s*|\s*```$/iu',
|
||||
'',
|
||||
trim((string) ($candidate['json'] ?? ''))
|
||||
));
|
||||
$payload = json_decode($json, true);
|
||||
if (!is_array($payload)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$action = mb_strtolower(trim((string) ($payload['action'] ?? $payload['task'] ?? $payload['tool'] ?? '')));
|
||||
$action = str_replace(['-', ' '], '_', $action);
|
||||
if (!in_array($action, ['generate_image', 'create_image', 'image_generation', 'draw_image'], true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$arguments = $payload['arguments'] ?? [];
|
||||
if (is_string($arguments)) {
|
||||
$arguments = json_decode($arguments, true) ?: [];
|
||||
}
|
||||
$prompt = trim((string) ($payload['prompt'] ?? (is_array($arguments) ? ($arguments['prompt'] ?? '') : '')));
|
||||
if ($prompt === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
return [
|
||||
'action' => 'generate_image',
|
||||
'prompt' => mb_substr($prompt, 0, 8000),
|
||||
];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The deterministic router has already approved an image operation, so a valid
|
||||
* action object may be recovered even when the model surrounded it with prose.
|
||||
*/
|
||||
public static function parseRoutedImageAction(string $content): ?array
|
||||
{
|
||||
foreach (self::extractJsonObjects($content) as $object) {
|
||||
$action = self::parseImageAction((string) ($object['json'] ?? ''));
|
||||
if ($action !== null) {
|
||||
return $action;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function extractJsonObjects(string $content): array
|
||||
{
|
||||
$objects = [];
|
||||
$length = strlen($content);
|
||||
$depth = 0;
|
||||
$start = null;
|
||||
$inString = false;
|
||||
$escaped = false;
|
||||
|
||||
for ($index = 0; $index < $length; $index++) {
|
||||
$char = $content[$index];
|
||||
if ($inString) {
|
||||
if ($escaped) {
|
||||
$escaped = false;
|
||||
} elseif ($char === '\\') {
|
||||
$escaped = true;
|
||||
} elseif ($char === '"') {
|
||||
$inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($char === '"') {
|
||||
$inString = true;
|
||||
} elseif ($char === '{') {
|
||||
if ($depth === 0) {
|
||||
$start = $index;
|
||||
}
|
||||
$depth++;
|
||||
} elseif ($char === '}' && $depth > 0) {
|
||||
$depth--;
|
||||
if ($depth === 0 && $start !== null) {
|
||||
$json = substr($content, $start, $index - $start + 1);
|
||||
$objects[] = [
|
||||
'json' => $json,
|
||||
'wrapper' => substr($content, 0, $start) . substr($content, $index + 1),
|
||||
];
|
||||
$start = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $objects;
|
||||
}
|
||||
|
||||
private static function allowsImageActionWrapper(string $wrapper): bool
|
||||
{
|
||||
$wrapper = trim((string) preg_replace('/[`\s,,。.!!::;;]+/u', ' ', $wrapper));
|
||||
if ($wrapper === '') {
|
||||
return true;
|
||||
}
|
||||
if (preg_match('/示例|格式|例如|假设|说明|解释|请勿|不要执行|仅供参考|example|format|do\s+not|don[\'’]t|reference/iu', $wrapper)) {
|
||||
return false;
|
||||
}
|
||||
if (mb_strlen($wrapper) > 320) {
|
||||
return false;
|
||||
}
|
||||
if (mb_strlen($wrapper) > 80) {
|
||||
return preg_match(
|
||||
'/(?:我将|将为你|将为您|现在为你|现在为您|接下来|马上|立即|正在)'
|
||||
. '[\s\S]{0,180}(?:执行|生成|创作|制作|绘制|生图|generate|create|draw|paint)/iu',
|
||||
$wrapper
|
||||
) === 1;
|
||||
}
|
||||
|
||||
return preg_match(
|
||||
'/(?:好的|收到|明白|可以|没问题|开始|马上|立即|现在|正在|将为你|下面开始|'
|
||||
. 'here\s+you\s+go|here\s+is|i[\'’]ll|i\s+will|we[\'’]ll|we\s+will|generating|creating)'
|
||||
. '[^。.!!??]{0,48}(?:执行|生成|创作|制作|绘制|生图|generate|create|draw|paint)?/iu',
|
||||
$wrapper
|
||||
) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect natural visual requests that omit words such as “图片” or “生成”.
|
||||
* Elliptical complaints like “我看不到” only count when recent dialogue is
|
||||
* actually about appearance, preventing code/document visibility issues from
|
||||
* being routed to the image model.
|
||||
*/
|
||||
public static function requestsContextualImageGeneration(string $content, array $history = []): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '' || self::requestsImageGeneration($content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// “看不懂” describes comprehension, not an inability to see an image.
|
||||
if (preg_match('/^(?:我)?(?:还是)?(?:看不懂|看不明白|没看懂|没有看懂)[了啊呀呢吗,,。!?!?\s]*$/u', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (preg_match('/(?:不要|不用|无需|别|不需要|只要文字|文字说明|不用图片|不要图片)/u', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$nonVisualTarget = '/(?:介绍|资料|知识|习性|毒性|分类|区别|原因|为什么|怎么|如何|教程|步骤|方法|代码|文档|表格|报表|数据|日志|报错|新闻|视频|电影|直播|实时|天气|预报|价格|股票|网页|页面|消息|聊天记录|文字|答案)/u';
|
||||
if (preg_match($nonVisualTarget, $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$directDisplay = '/^(?:请|麻烦)?(?:'
|
||||
. '(?:给|让)(?:我)?(?:看(?:看|到|见|一下)?|瞧瞧|展示(?:一下)?)'
|
||||
. '|(?:我)?(?:想|要|希望|想要)(?:看(?:看|到|见|一下)?|瞧瞧)'
|
||||
. '|(?:能否|能不能|可以|可不可以)?(?:给我|让我)?(?:看(?:看|到|见|一下)?|瞧瞧|展示(?:一下)?)'
|
||||
. ')\s*(?<target>[^,,。!?!?\n]{1,30}?)(?:的?(?:样子|图片|照片|图像))?(?:可以吗|行吗|好吗|呢)?$/u';
|
||||
if (preg_match($directDisplay, $content, $match)) {
|
||||
$target = trim((string) ($match['target'] ?? ''));
|
||||
$resolvedTarget = self::normalizeVisualSubject($target);
|
||||
if ($resolvedTarget !== '' && !preg_match($nonVisualTarget, $resolvedTarget)) {
|
||||
return true;
|
||||
}
|
||||
if (self::resolveContextualImageSubject($content, $history) !== '') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
$appearanceQuestion = '/^(?:他|她|它|他们|她们|它们|这个|那个|这|那|该对象|该东西|[^,,。!?!?\n]{1,24})?'
|
||||
. '(?:长啥样|长什么样(?:子)?|是什么样子|外观(?:怎样|如何|是什么样)?)'
|
||||
. '[啊呀呢吗么,,。!?!?\s]*$/u';
|
||||
if (preg_match($appearanceQuestion, $content)
|
||||
&& self::resolveContextualImageSubject($content, $history) !== '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (preg_match('/^(?:那)?也(?:给我|让我)?(?:看看|看一下|瞧瞧|展示一下)[了啊吧呀呢,,。!?!?\s]*$/u', $content)
|
||||
&& self::resolveContextualImageSubject($content, $history) !== '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$naturalContextualDisplay = '/^(?:'
|
||||
. '(?:给我?)?瞅一眼|有照片吗|(?:他|她|它|这个|那个)有(?:图|照片)吗|'
|
||||
. '(?:这个|那个)?也想(?:看看|瞧瞧)|我也想(?:看看|瞧瞧)|'
|
||||
. '也来(?:一)?张(?:他|她|它|这个|那个)(?:的)?|'
|
||||
. '(?:两(?:个|位|只)|俩)都(?:给我|让我)?(?:看看|瞧瞧|展示一下)|'
|
||||
. '(?:那)?也展示一下'
|
||||
. ')[了啊吧呀呢呗,,。!?!?\s]*$/u';
|
||||
if (preg_match($naturalContextualDisplay, $content)
|
||||
&& self::resolveContextualImageSubject($content, $history) !== '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$appearanceThenDisplay = '/^(?:他|她|它|他们|她们|它们|这个|那个|这|那|该对象|该东西|[^,,。!?!?\n]{1,24})?'
|
||||
. '(?:长啥样|长什么样|是什么样子|外观(?:怎样|如何|是什么样)?)'
|
||||
. '[,,、\s]*(?:我)?(?:想|要|希望|想要)?(?:看(?:看|到|见|一下)?|瞧瞧|展示(?:一下)?)'
|
||||
. '[了啊呀呢吗??。!!]*$/u';
|
||||
if (preg_match($appearanceThenDisplay, $content)
|
||||
&& self::resolveContextualImageSubject($content, $history) !== '') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$ellipticalDisplay = '/^(?:我)?(?:还是|但|可是|就是|现在)?\s*'
|
||||
. '(?:看不到|看不见|没看到|没有看到|想看(?:看|到)?|想瞧瞧|给我看看|让我看看|展示一下|直接展示|有图吗|图片呢|图呢|能看吗|能看到吗)'
|
||||
. '[了啊呀呢吗??。!!]*$/u';
|
||||
if (!preg_match($ellipticalDisplay, $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$contextParts = [];
|
||||
$history = array_slice($history, -12);
|
||||
foreach ($history as $index => $message) {
|
||||
$messageContent = trim((string) ($message['content'] ?? ''));
|
||||
$isCurrentMessage = $index === array_key_last($history)
|
||||
&& ($message['role'] ?? '') === 'user'
|
||||
&& mb_strtolower($messageContent) === $content;
|
||||
if ($messageContent !== '' && !$isCurrentMessage) {
|
||||
$contextParts[] = $messageContent;
|
||||
}
|
||||
}
|
||||
$context = implode("\n", $contextParts);
|
||||
if ($context === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return preg_match(
|
||||
'/(?:长什么样|什么样子|外观|外形|形态|样貌|造型|轮廓|颜色|纹理|头部|身体|眼睛|四肢|翅膀|鳞片|毛发|姿态|构图|场景|风景|天空|动物|人物|建筑|物体|照片|图片|图像|画面|视觉|写实|卡通)/u',
|
||||
$context
|
||||
) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the concrete entity behind a contextual visual request. Pronouns are
|
||||
* never accepted as subjects; the latest explicit user entity wins.
|
||||
*/
|
||||
public static function resolveContextualImageSubject(string $content, array $history = []): string
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$currentPatterns = [
|
||||
'/^(?<subject>[^,,。!?!?\n]{1,24}?)(?:长啥样|长什么样|是什么样子|外观(?:怎样|如何|是什么样)?)/u',
|
||||
'/(?:给我|让我|我想|我希望|我想要|想|要|希望)(?:看(?:看|到|见|一下)?|瞧瞧|展示(?:一下)?)\s*(?<subject>[^,,。!?!?\n]{1,30})/u',
|
||||
];
|
||||
foreach ($currentPatterns as $pattern) {
|
||||
if (preg_match($pattern, $content, $match)) {
|
||||
$subject = self::normalizeVisualSubject((string) ($match['subject'] ?? ''));
|
||||
if ($subject !== '') {
|
||||
return $subject;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$history = array_slice($history, -12);
|
||||
$priorMessages = [];
|
||||
foreach ($history as $index => $message) {
|
||||
$messageContent = mb_strtolower(trim((string) ($message['content'] ?? '')));
|
||||
$isCurrentMessage = $index === array_key_last($history)
|
||||
&& ($message['role'] ?? '') === 'user'
|
||||
&& $messageContent === $content;
|
||||
if ($messageContent !== '' && !$isCurrentMessage) {
|
||||
$priorMessages[] = [
|
||||
'role' => (string) ($message['role'] ?? ''),
|
||||
'content' => $messageContent,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
for ($index = count($priorMessages) - 1; $index >= 0; $index--) {
|
||||
$message = $priorMessages[$index];
|
||||
if ($message['role'] !== 'user') {
|
||||
continue;
|
||||
}
|
||||
$patterns = [
|
||||
'/^(?:不是[^,,。!?!?\n]{1,20}[,,]?\s*)?(?:我说的是|我要的是|应该是)\s*(?<subject>[^,,。!?!?\n]{1,24})/u',
|
||||
'/(?:你知道|你了解|认识|了解一下|讲讲|介绍一下)\s*(?<subject>[^,,。!?!?\n]{1,24}?)(?:吗|么|呢|吧|?|\?|。|!|!)?$/u',
|
||||
'/^(?:那|那么|至于)\s*(?<subject>[^,,。!?!?\n]{1,24}?)\s*(?:呢|怎么样|又如何)?[,,。!?!?\s]*$/u',
|
||||
'/^(?<subject>[^,,。!?!?\n]{1,24}?)(?:长啥样|长什么样|是什么样子|的?(?:外观|外形|形态|样貌|造型))/u',
|
||||
'/(?:想看|看看|展示|生成|画|绘制)\s*(?<subject>[^,,。!?!?\n]{1,24})/u',
|
||||
];
|
||||
foreach ($patterns as $pattern) {
|
||||
if (preg_match($pattern, $message['content'], $match)) {
|
||||
$subject = self::normalizeVisualSubject((string) ($match['subject'] ?? ''));
|
||||
if ($subject !== '') {
|
||||
if (self::isAmbiguousReferencedSubject($subject, $content)) {
|
||||
return '';
|
||||
}
|
||||
return $subject;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for ($index = count($priorMessages) - 1; $index >= 0; $index--) {
|
||||
$message = $priorMessages[$index];
|
||||
if ($message['role'] !== 'assistant') {
|
||||
continue;
|
||||
}
|
||||
if (preg_match(
|
||||
'/^(?:知道|了解|当然知道|当然了解)?[。,.!!\s]*(?<subject>[\p{Han}a-z0-9·_-]{1,24}?)(?:是|属于|通常|一般|具有|有)/iu',
|
||||
$message['content'],
|
||||
$match
|
||||
)) {
|
||||
$subject = self::normalizeVisualSubject((string) ($match['subject'] ?? ''));
|
||||
if ($subject !== '') {
|
||||
if (self::isAmbiguousReferencedSubject($subject, $content)) {
|
||||
return '';
|
||||
}
|
||||
return $subject;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
private static function normalizeVisualSubject(string $subject): string
|
||||
{
|
||||
$subject = mb_strtolower(trim($subject));
|
||||
$subject = preg_replace('/^[“”‘’"\'《》〈〉【】\[\]()()\s]+|[“”‘’"\'《》〈〉【】\[\]()()\s]+$/u', '', $subject);
|
||||
$subject = preg_replace(
|
||||
'/^(?:请|麻烦)?(?:给我|让我|我想|我希望|我想要|想|要|希望)(?:看(?:看|到|见|一下)?|瞧瞧|展示(?:一下)?)?/u',
|
||||
'',
|
||||
$subject
|
||||
);
|
||||
$subject = preg_replace('/^(?:关于|有关|这个|那个|这种|那种|一个|一种|一只|一位|该)/u', '', $subject);
|
||||
$subject = preg_replace('/(?:的?(?:样子|图片|照片|图像)|长啥样|长什么样|是什么样子|可以吗|行吗|好吗|呢|吗)$/u', '', $subject);
|
||||
$subject = trim((string) $subject);
|
||||
|
||||
if ($subject === '' || mb_strlen($subject) > 24) {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/^(?:看|看看|看一下|瞧瞧|展示|展示一下)$/u', $subject)) {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/^(?:那)?(?:他|她|它|他们|她们|它们|这个|那个|这|那|玩意儿|东西|对象|该对象|该东西)(?:长|是|外观)?$/u', $subject)) {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/^(?:他|她|它|他们|她们|它们|这个|那个|这|那|其|对象|东西|该对象|该东西)$/u', $subject)) {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/(?:介绍|资料|知识|习性|毒性|分类|区别|原因|教程|步骤|方法|代码|文档|表格|报表|数据|日志|报错|新闻|视频|电影|直播|实时|天气|预报|价格|股票|网页|页面|消息|聊天记录|文字|答案|php|javascript|java|python)/iu', $subject)) {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/(?:不要|不用|生成|执行|系统|提示词|prompt|json|模型|工具)/iu', $subject)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $subject;
|
||||
}
|
||||
|
||||
private static function isAmbiguousReferencedSubject(string $subject, string $content): bool
|
||||
{
|
||||
$hasMultipleCandidates = preg_match('/(?:和|与|、|以及|还有|及)/u', $subject) === 1;
|
||||
if (!$hasMultipleCandidates) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$usesPluralReference = preg_match('/(?:他们|她们|它们|两(?:个|位|只)|都|一起|全部)/u', $content) === 1;
|
||||
$usesSingularReference = preg_match('/(?:他|她|它)(?!们)|(?:这个|那个|这位|那位)/u', $content) === 1
|
||||
|| preg_match('/^(?:我)?(?:想|要|希望)?(?:看看|看一下|瞧瞧)[了啊吧呀呢,,。!?!?\s]*$/u', $content) === 1;
|
||||
|
||||
return $usesSingularReference && !$usesPluralReference;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect instructions that require the pixels of an existing image. The
|
||||
* controller only enables this route when a user image or generated image
|
||||
* is actually available, so ordinary text such as “删除这一段” is unaffected.
|
||||
*/
|
||||
public static function requestsImageEditing(string $content): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (self::requestsImageEnhancement($content)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (preg_match('/(?:分析|解释|识别|读取|描述|评价|为什么|是什么|是谁|教程|方法|怎么做)/u', $content)
|
||||
&& !preg_match('/(?:修改|处理|修复|重绘|去掉|移除|擦除|删除|替换|换成|改成)/u', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return preg_match(
|
||||
'/(?:img2img|image\s*to\s*image|inpaint|图生图|局部重绘|局部修复|图片编辑|处理这张图|修改这张图|'
|
||||
. '(?:去|移除|擦除|抹掉|删除|去掉|清除)[^,,。!?!?\n]{0,16}(?:水印|logo|标志|文字|字幕|人物|路人|物体|东西|瑕疵|污点|反光|背景)|'
|
||||
. '(?:水印|logo|标志|文字|字幕|人物|路人|物体|东西|瑕疵|污点|反光)[^,,。!?!?\n]{0,12}(?:去|移除|擦除|抹掉|删除|去掉|清除)|'
|
||||
. '(?:换|替换|修改|改变|改成)[^,,。!?!?\n]{0,10}(?:背景|天空|衣服|颜色|风格|人物|物体)|'
|
||||
. '(?:抠图|扩图|补图|修图|精修|老照片修复|照片修复|画质修复|修复[^,,。!?!?\n]{0,10}(?:照片|图片|画面)|上色|去噪|锐化|无损放大|增强清晰度)|'
|
||||
. '(?:(?:去除|移除|删除|擦除|清除)[^,,。!?!?\n]{0,6}(?:不彻底|不干净|有残留)|'
|
||||
. '(?:没|没有|未)(?:去|删|清|擦)[^,,。!?!?\n]{0,6}(?:干净|掉|完)|'
|
||||
. '(?:还|仍然|依然)(?:有|在)[^,,。!?!?\n]{0,6}(?:水印|残留))|'
|
||||
. '(?:把|将)[^,,。!?!?\n]{1,24}(?:换成|改成|变成|去(?:除|掉)(?:了)?|移除(?:了)?|删除(?:了)?|擦掉(?:了)?|修复))'
|
||||
. '/iu',
|
||||
$content
|
||||
) === 1;
|
||||
}
|
||||
|
||||
public static function requestsImageEnhancement(string $content): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return false;
|
||||
}
|
||||
if (preg_match('/(?:怎么|如何|为什么|教程|方法|原理|能不能介绍|请解释)/u', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return preg_match(
|
||||
'/(?:变|变得|弄|调|处理)(?:成|得)?(?:更)?清晰|'
|
||||
. '(?:更|再)清晰(?:一?点|一些)?|清晰(?:一?点|一些)|'
|
||||
. '提高清晰度|增强清晰度|高清化|变高清|提升画质|改善画质|'
|
||||
. '超分(?:辨率)?|无损放大|锐化(?:一下)?/u',
|
||||
$content
|
||||
) === 1;
|
||||
}
|
||||
|
||||
public static function imageEditMode(string $content): string
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
|
||||
return preg_match(
|
||||
'/(?:inpaint|局部|遮罩|蒙版|修补|补全|修复|不彻底|不干净|有残留|没去干净|'
|
||||
. '(?:去|移除|擦除|擦掉|抹掉|删除|去掉|清除)|'
|
||||
. '(?:换|替换|修改|改变|改成)[^,,。!?!?\n]{0,10}(?:背景|天空|衣服|人物|物体))/iu',
|
||||
$content
|
||||
) === 1 ? 'inpaint' : 'img2img';
|
||||
}
|
||||
|
||||
public static function requestsBackgroundRemoval(string $content): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return false;
|
||||
}
|
||||
if (preg_match('/(?:怎么|如何|教程|方法|原理|能不能介绍|请解释)/u', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Do not treat "补全/相邻/周围背景" (inpaint fill language) as cutout.
|
||||
return preg_match(
|
||||
'/(?:抠图|抠出[^,,。!?!?\n]{0,16}(?:主体|人物|商品|物体)|'
|
||||
. '(?:移除|去除|删除|去掉|清除)\s*(?:图片|照片|整图|图像|这张图)?(?:中|里)?(?:的|了)?背景|'
|
||||
. '(?:把|将)背景(?:移除|去除|删除|去掉|清除)|'
|
||||
. '(?:背景透明|透明背景|透明底|transparent\s+background|remove\s+(?:the\s+)?background))/iu',
|
||||
$content
|
||||
) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve cutout / watermark intent. Explicit workbench image_tool wins over content heuristics.
|
||||
*
|
||||
* @return array{is_background_removal: bool, is_watermark_removal: bool}
|
||||
*/
|
||||
public static function resolveImageEditFlags(string $content, string $imageTool = ''): array
|
||||
{
|
||||
$imageTool = trim($imageTool);
|
||||
if ($imageTool === 'cutout') {
|
||||
return ['is_background_removal' => true, 'is_watermark_removal' => false];
|
||||
}
|
||||
if ($imageTool === 'watermark') {
|
||||
return ['is_background_removal' => false, 'is_watermark_removal' => true];
|
||||
}
|
||||
if ($imageTool !== '') {
|
||||
// Other explicit tools (erase/replace/...) must never be misrouted to cutout.
|
||||
$isWatermarkRemoval = $imageTool === 'erase' && self::requestsWatermarkRemoval($content);
|
||||
|
||||
return ['is_background_removal' => false, 'is_watermark_removal' => $isWatermarkRemoval];
|
||||
}
|
||||
|
||||
$isBackgroundRemoval = self::requestsBackgroundRemoval($content);
|
||||
$isWatermarkRemoval = self::requestsWatermarkRemoval($content);
|
||||
if ($isBackgroundRemoval && $isWatermarkRemoval) {
|
||||
// Phrases like "去掉水印并补全背景" are watermark jobs, not cutout.
|
||||
$isBackgroundRemoval = false;
|
||||
}
|
||||
|
||||
return [
|
||||
'is_background_removal' => $isBackgroundRemoval,
|
||||
'is_watermark_removal' => $isWatermarkRemoval,
|
||||
];
|
||||
}
|
||||
|
||||
public static function requestsWatermarkRemoval(string $content): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (preg_match(
|
||||
'/(?:(?:去除|移除|删除|擦除|清除)[^,,。!?!?\n]{0,6}(?:不彻底|不干净|有残留)|'
|
||||
. '(?:没|没有|未)(?:去|删|清|擦)[^,,。!?!?\n]{0,6}(?:干净|掉|完)|'
|
||||
. '(?:还|仍然|依然)(?:有|在)[^,,。!?!?\n]{0,6}(?:水印|残留))/u',
|
||||
$content
|
||||
)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return preg_match(
|
||||
'/(?:(?:去(?:除|掉)?|移除|删除|擦除|擦掉|抹掉|清除)[^,,。!?!?\n]{0,16}(?:水印|watermark)|'
|
||||
. '(?:水印|watermark)[^,,。!?!?\n]{0,16}(?:去(?:除|掉)?|移除|删除|擦除|擦掉|抹掉|清除|remove|erase)|'
|
||||
. '(?:remove|erase)[^,.!?\n]{0,16}watermark)/iu',
|
||||
$content
|
||||
) === 1;
|
||||
}
|
||||
|
||||
public static function imageTextRemovalTarget(string $content): ?string
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$hasRemoval = preg_match(
|
||||
'/(?:(?:去(?:除|掉)?|移除|删除|擦除|擦掉|抹掉|清除)(?:了)?|'
|
||||
. '(?:不要|不保留|隐藏)[^,,。!?!?\n]{0,8}(?:文字|文本|字样|署名|作者|作者名|标题|书名))/u',
|
||||
$content
|
||||
) === 1;
|
||||
if (!$hasRemoval) {
|
||||
return null;
|
||||
}
|
||||
if (preg_match('/(?:作者|作者名|署名|笔名)/u', $content)) {
|
||||
return 'author';
|
||||
}
|
||||
if (preg_match('/(?:标题|书名|主标题|副标题)/u', $content)) {
|
||||
return 'title';
|
||||
}
|
||||
if (preg_match('/(?:所有|全部|整张|画面中|图中)?[^,,。!?!?\n]{0,6}(?:文字|文本|字样|字幕)/u', $content)) {
|
||||
return 'all_text';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function requestsImageRevision(string $content): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$textOnlyTarget = preg_match('/文案|文章|代码|方案|报告|表格|数据|提示词|prompt/u', $content) === 1;
|
||||
$imageReference = preg_match('/图片|图像|画面|插画|海报|封面|头像|照片|背景|构图|人物|角色/u', $content) === 1;
|
||||
$strongRevision = '/(?:重新|再次|再)(?:生成|制作|创作|做|画|绘制|渲染|优化|调整|修改|来|出图|生图)|重做|重画|换(?:一|个)?张|再来(?:一|个)?张|重新来/u';
|
||||
if (preg_match($strongRevision, $content)) {
|
||||
if ($textOnlyTarget && !$imageReference) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (preg_match('/为什么|怎么|怎么办|如何|是什么|描述|分析|评价|解释|识别|读取|建议|方法/u', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$correctionRevision = '/^(?:不对|不是|错了|搞错了|认错了|画错了|这不是|我说的是|我要的是|应该是)'
|
||||
. '[^。!?!?\n]{0,36}(?:我说的是|我要的是|应该是|不是|而是|是|换成|改成|画成)'
|
||||
. '[^。!?!?\n]{1,30}/u';
|
||||
if (preg_match($correctionRevision, $content)) {
|
||||
return !$textOnlyTarget || $imageReference;
|
||||
}
|
||||
|
||||
$visualTarget = '(?:图片|图像|画面|主体|人物|角色|背景|构图|镜头|光线|色彩|颜色|风格|姿势|动作|表情|服装|材质|细节|比例|胸围|胸部|肌肉|脸|眼睛|头发|毛发|鬃毛|毛|角|翅膀|尾巴|身体|天空|草地|招牌|文字|字|尺寸|分辨率)';
|
||||
$editAction = '(?:调整|修改|优化|改(?:成|为)?|换(?:成|为|个)?|变成|做成|画成|调(?:成|整)?|增加|减少|加强|弱化|放大|缩小|加大|减小|删掉|去掉|别加|不要|取消|保留|保持|替换|修正)';
|
||||
$qualityTarget = '(?:大|小|长|短|亮|暗|高|低|多|少|宽|窄|强|弱|胖|瘦|饱满|明显|真实|自然|写实|卡通|清晰|模糊|拥挤|空旷|空|荒凉|生动|僵硬|单调|鲜艳|饱和|假|胸围|胸部|肌肉|细节|比例)';
|
||||
$contextualRevision = '/^(?:请|麻烦)?(?:把|将)?[^,,。!?!?\n]{0,14}'
|
||||
. '(?:改(?:成|为)?|换(?:成|为|个)?|变成|做成|画成|调(?:成|整)?)'
|
||||
. '[^,,。!?!?\n]{1,24}/u';
|
||||
|
||||
if (preg_match($contextualRevision, $content)) {
|
||||
return !$textOnlyTarget || $imageReference;
|
||||
}
|
||||
|
||||
$shortVisualRevision = preg_match(
|
||||
'/^(?:请|麻烦)?(?:'
|
||||
. $visualTarget . '(?:往|向)(?:左|右|上|下|前|后)(?:移|挪)?(?:一点|点|一些|些)?'
|
||||
. '|' . $visualTarget . '(?:拉远|拉近|推近|后退|前移)(?:一点|点|一些|些)?'
|
||||
. '|' . $visualTarget . '(?:再|更|稍微)?(?:淡|浓|亮堂|明亮|柔和|鲜艳|自然)(?:一点|点|一些|些)?'
|
||||
. '|(?:再|更|稍微)?(?:亮堂|明亮|柔和|自然)(?:一点|点|一些|些)?'
|
||||
. '|别这么(?:挤|拥挤|塑料|假|僵硬|空|暗|亮)'
|
||||
. '|更有(?:电影|故事|层次|空间|氛围|质感|生命)感'
|
||||
. ')[了啊吧呀呢,,。!?!?\s]*$/u',
|
||||
$content
|
||||
) === 1;
|
||||
if ($shortVisualRevision) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return preg_match('/' . $editAction . '[^,,。!?!?\n]{0,16}' . $visualTarget . '/u', $content) === 1
|
||||
|| preg_match('/' . $visualTarget . '[^,,。!?!?\n]{0,16}' . $editAction . '/u', $content) === 1
|
||||
|| preg_match('/(?:不够|太|需要更|想要更)[^,,。!?!?\n]{0,16}' . $qualityTarget . '/u', $content) === 1
|
||||
|| preg_match('/' . $visualTarget . '[^,,。!?!?\n]{0,12}(?:再|更)[^,,。!?!?\n]{0,8}(?:一点|点|一些|' . $qualityTarget . ')/u', $content) === 1
|
||||
|| preg_match('/^(?:请|麻烦)?(?:再|更|稍微)' . $qualityTarget . '(?:一点|点|一些|些)?[了啊吧呀呢,,。!?!?\s]*$/u', $content) === 1;
|
||||
}
|
||||
|
||||
public static function referencesPriorImagePlan(string $content): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
return preg_match('/(?:按照|按|根据|采用|选择|就用|使用|照着)[^,,。!?!?\n]{0,20}(?:方案|选项|建议|上面|前面|刚才|你说的|这个|那个)/u', $content) === 1
|
||||
|| preg_match('/(?:方案|选项)\s*(?:第)?[一二三四五六七八九十\d]+[^,,。!?!?\n]{0,12}(?:生成|制作|做|画|执行|来一张)/u', $content) === 1
|
||||
|| preg_match('/^\s*(?:就用|选择|采用)?\s*(?:方案|选项)\s*(?:第)?[一二三四五六七八九十\d]+\s*$/u', $content) === 1
|
||||
|| preg_match('/(?:就这样|按这个|照这个|用这个|照你说的)[^,,。!?!?\n]{0,12}(?:生成|制作|做|画|来|执行)/u', $content) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A short confirmation only means "generate it" when the immediately preceding
|
||||
* assistant turn actually offered a concrete image plan. This keeps replies such
|
||||
* as "对" from inheriting an unrelated image much earlier in the conversation.
|
||||
*/
|
||||
public static function confirmsContextualImagePlan(string $content, array $history = []): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
$simpleConfirmation = preg_match(
|
||||
'/^(?:对|好|好的|可以|行|就这样|按这个|照这个|用这个|开始吧|生成吧|做吧|画吧)[了啊吧呀呢,,。!?!?\s]*$/u',
|
||||
$content
|
||||
) === 1;
|
||||
$selectionConfirmation = mb_strlen($content) <= 36
|
||||
&& !preg_match('/(?:不行|不要|别|先不|为什么|怎么|哪一个|哪个好|吗|么|\?|?)/u', $content)
|
||||
&& preg_match('/(?:第?[一二三四五六七八九十\d]+(?:个|套|种|版|号|方案|方向)?|方案|方向|选项|这个|那个|它|你说的)/u', $content)
|
||||
&& preg_match('/(?:挺好|不错|可以|就|选|用|照|按|采用|确定|来|做|生成)/u', $content);
|
||||
$naturalConfirmation = preg_match(
|
||||
'/^(?:那?就)?(?:按|照|用|采用)?(?:你说的|这个|那个|它|这样|这么|这些建议|刚才的建议)'
|
||||
. '(?:来|改|调整|优化|做|生成|执行)?[了啊吧呀呢,,。!?!?\s]*$/u',
|
||||
$content
|
||||
) === 1;
|
||||
$bareSelection = preg_match(
|
||||
'/^(?:(?:第)?[一二三四五六七八九十\d]+(?:个|套|种|版|号|方案|方向)|最后(?:一个|一套|一种|一版|那个))'
|
||||
. '[了啊吧呀呢,,。!?!?\s]*$/u',
|
||||
$content
|
||||
) === 1;
|
||||
$contextualExecution = preg_match(
|
||||
'/^(?:听你的|你推荐的那个|开始干吧|行[,,]?照办|可以[,,]?动手|嗯?[,,]?就这么弄|'
|
||||
. '好[,,]?修一下|执行吧|就这么办)[了啊吧呀呢,,。!?!?\s]*$/u',
|
||||
$content
|
||||
) === 1;
|
||||
if (!$simpleConfirmation
|
||||
&& !$selectionConfirmation
|
||||
&& !$naturalConfirmation
|
||||
&& !$bareSelection
|
||||
&& !$contextualExecution) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$history = array_slice($history, -12);
|
||||
for ($index = count($history) - 1; $index >= 0; $index--) {
|
||||
$message = $history[$index];
|
||||
$messageContent = trim((string) ($message['content'] ?? ''));
|
||||
if (($message['role'] ?? '') === 'user' && mb_strtolower($messageContent) === $content) {
|
||||
continue;
|
||||
}
|
||||
if (($message['role'] ?? '') !== 'assistant' || $messageContent === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attachments = $message['attachments'] ?? [];
|
||||
if (is_string($attachments)) {
|
||||
$attachments = json_decode($attachments, true) ?: [];
|
||||
}
|
||||
foreach ((array) $attachments as $attachment) {
|
||||
if (is_array($attachment) && ($attachment['type'] ?? '') === 'image') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
$hasVisualPlan = preg_match(
|
||||
'/(?:图片|图像|插画|海报|封面|头像|画面|视觉|构图|风格|场景|生图|出图|生成|制作|绘制|方案|方向)/u',
|
||||
$messageContent
|
||||
) === 1;
|
||||
$offersExecution = preg_match(
|
||||
'/(?:选择|确认|采用|生成|制作|绘制|开始|要哪|哪个|哪一个|告诉我|可以吗|怎么样)/u',
|
||||
$messageContent
|
||||
) === 1;
|
||||
|
||||
return $hasVisualPlan && $offersExecution;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Conservative Agent router: only creation intent triggers ComfyUI; image analysis and prompt-writing stay on the LLM.
|
||||
*/
|
||||
public static function requestsImageGeneration(string $content): bool
|
||||
{
|
||||
$content = mb_strtolower(trim($content));
|
||||
if ($content === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$imageTarget = '(?:图片|图像|插画|海报|封面|头像|壁纸|配图|宣传图|广告图|商品图|产品图|场景图|人物图|背景图|电商图|主图|详情图|效果图|概念图|示意图|流程图|架构图|思维导图|图表|照片|视觉稿|视觉图|logo|标志|图标|banner|image|picture|illustration|poster|cover|wallpaper|photo|artwork|icon)';
|
||||
$drawAction = '(?<![插漫油图绘字壁年版国动彩])画(?!面|质|风|布|廊|家|作|册|笔|纸|框|室|展)';
|
||||
$creationAction = '(?:生成|创建|生图|出图|' . $drawAction . '|绘制|创作|制作|设计|渲染|generate|create|draw|paint|render|design|make)';
|
||||
$directImageAction = '(?:生图|出图|绘图|作图|制图|' . $drawAction . '|绘制|paint\b|draw\s+(?!a\s+conclusion\b|conclusions?\b))';
|
||||
$directRequest = '(?:(?:^|给我|帮我|请|来)(?:直接|马上|立即|现在|重新|再)?'
|
||||
. $directImageAction . '|(?:把|将)[^,,。!?!?\n]{1,12}(?:' . $drawAction . '|绘制|绘图|重画))';
|
||||
|
||||
// Pronoun-only “来张它的” needs conversation context and must not discard history.
|
||||
if (preg_match('/^(?:也)?来(?:一)?张(?:他|她|它|他们|她们|它们|这个|那个|刚才那个)(?:的)?[了啊吧呀呢,,。!?!?\s]*$/u', $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$explicitDeferral = '/(?:别急着|先别|暂时(?:先)?不|暂不|目前(?:先)?不|先不要)[^。!?!?\n]{0,10}'
|
||||
. '(?:生成|制作|创作|绘制|生图|出图)|先[^。!?!?\n]{0,20}'
|
||||
. '(?:讨论|分析|规划|构思|方案|方向|建议)[^。!?!?\n]{0,24}'
|
||||
. '(?:确认后|之后|以后|再)(?:生成|制作|创作|绘制|生图|出图)/u';
|
||||
if (preg_match($explicitDeferral, $content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$capabilityQuestion = '/(?:你|模型|agent|ai|助手)?[^,,。!?!?\n]{0,5}'
|
||||
. '(?:会不会|能不能|能否|是否(?:可以|能够|支持)|会|能|可以|支持)'
|
||||
. '[^,,。!?!?\n]{0,16}(?:' . $directImageAction . '|'
|
||||
. $creationAction . '[^,,。!?!?\n]{0,10}' . $imageTarget . '|'
|
||||
. $imageTarget . '[^,,。!?!?\n]{0,10}' . $creationAction . ')'
|
||||
. '[^,,。!?!?\n]{0,4}(?:吗|么|不|?|\?)?$/iu';
|
||||
$concreteBrief = '/(?:一|两|二|三|几|多)?(?:张|幅|个|只|位|套|枚|款|版)'
|
||||
. '|(?:主体|场景|背景|风格|构图|镜头|光线|颜色|色彩|姿势|动作|材质)[::为是]?/u';
|
||||
$englishCapabilityQuestion = '/\b(?:(?:can|could)\s+you|do\s+you\s+support|are\s+you\s+able\s+to)\s+'
|
||||
. '(?:generate|create|draw|paint|make|image\s+generation)[^.!?\n]{0,16}'
|
||||
. '(?:images?|pictures?|illustrations?|artwork)?\s*\??$/iu';
|
||||
$englishConcreteBrief = '/\b(?:of|showing|featuring|depicting|with|in\s+the\s+style\s+of)\b/iu';
|
||||
$isCapabilityOnly = static function (string $text) use (
|
||||
$capabilityQuestion,
|
||||
$concreteBrief,
|
||||
$englishCapabilityQuestion,
|
||||
$englishConcreteBrief
|
||||
): bool {
|
||||
return (preg_match($capabilityQuestion, $text) && !preg_match($concreteBrief, $text))
|
||||
|| (preg_match($englishCapabilityQuestion, $text) && !preg_match($englishConcreteBrief, $text));
|
||||
};
|
||||
if ($isCapabilityOnly($content)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (preg_match(
|
||||
'/(?:解释|介绍|说明|讲讲)[^,,。!?!?\n]{0,16}(?:图片生成|图像生成|生图)'
|
||||
. '[^,,。!?!?\n]{0,12}(?:原理|机制|技术|能力|流程)/u',
|
||||
$content
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$negatedRequest = '/(?:不要|不用|无需|别|禁止|避免|不需要|do\s+not|don[\'’]t)[^,,。!?!?\n]{0,8}'
|
||||
. '(?:' . $directImageAction . '|' . $creationAction . '[^,,。!?!?\n]{0,12}' . $imageTarget . ')/iu';
|
||||
$metaRequest = '/(?:'
|
||||
. '(?:如何|怎么|怎样|教程|方法|步骤|是否支持|支不支持|会不会)[^,,。!?!?\n]{0,20}(?:'
|
||||
. $directImageAction . '|' . $creationAction . '[^,,。!?!?\n]{0,12}' . $imageTarget . ')'
|
||||
. '|(?:告诉|说明|介绍|解释|列出|给出|讲讲|想知道)[^,,。!?!?\n]{0,10}'
|
||||
. '(?:' . $directImageAction . '|' . $creationAction . '[^,,。!?!?\n]{0,12}' . $imageTarget . ')'
|
||||
. '[^,,。!?!?\n]{0,10}(?:步骤|教程|方法|流程)'
|
||||
. '|(?:' . $directImageAction . '|' . $creationAction . '[^,,。!?!?\n]{0,12}' . $imageTarget . ')'
|
||||
. '[^,,。!?!?\n]{0,8}(?:步骤|教程|方法|流程)(?:是什么|有哪些|怎么|如何|呢|吗|?|\?)?'
|
||||
. '|(?:解释|说明|介绍|讨论|询问|查看|输出|给出)[^,,。!?!?\n]{0,16}'
|
||||
. '(?:生图|出图|生成图片|图片生成)[^,,。!?!?\n]{0,14}(?:动作|协议|格式|json|工具|接口|示例)'
|
||||
. '|(?:生图|出图|生成图片|图片生成)[^,,。!?!?\n]{0,12}'
|
||||
. '(?:是什么|怎么用|动作|协议|格式|json|模型|工具|接口|能力)'
|
||||
. '|(?:写|撰写|优化|润色|翻译|改写|分析|解释|提供|给出)[^,,。!?!?\n]{0,16}'
|
||||
. '(?:生图|生成图片|图片生成)[^,,。!?!?\n]{0,10}(?:提示词|prompt)'
|
||||
. ')/iu';
|
||||
$deferredRequest = '/(?:只|先|暂时|目前)(?:讨论|分析|规划|构思|给建议|写提示词|不生成|不要生成|先不生成|暂不生成|不执行|不要执行)/u';
|
||||
$visualScene = '(?:头像|壁纸|海报|封面|主图|夜景|日落|日出|风景|城市|书房|客厅|卧室|花园|海边|沙漠|森林|雪山|草原|天空|极光|人物|人像|女孩|男孩|动物|猫|狗|龙)';
|
||||
$colloquialVisualRequest = '/^(?:请|麻烦)?(?:给|帮)?(?:我)?'
|
||||
. '(?:整|来|出|做)(?:一|两|三)?(?:个|张|幅|套)?'
|
||||
. '[^,,。!?!?\n]{0,18}' . $visualScene . '(?:看看|瞧瞧)?[了啊吧呀呢,,。!?!?\s]*$/u';
|
||||
$patterns = [
|
||||
'/' . $creationAction . '[^,,。!?!?\n]{0,18}' . $imageTarget . '/iu',
|
||||
'/' . $imageTarget . '[^,,。!?!?\n]{0,12}' . $creationAction . '/iu',
|
||||
'/' . $directRequest . '/iu',
|
||||
$colloquialVisualRequest,
|
||||
'/(?:给我|帮我|来|生成|创建|创作|制作|做|出)[^,,。!?!?\n]{0,8}(?:一|两|三|几|多)?张(?!表(?:格)?)/u',
|
||||
'/^\s*\/(?:image|imagine|draw)\b/iu',
|
||||
];
|
||||
|
||||
$clauses = preg_split('/(?:但是|改为|改成|而是|然后|随后|并且|但|并)|[,,。!?!?;;\n]+/u', $content) ?: [$content];
|
||||
$decision = false;
|
||||
foreach ($clauses as $clause) {
|
||||
if ($clause === '') {
|
||||
continue;
|
||||
}
|
||||
if ($isCapabilityOnly($clause)
|
||||
|| preg_match($negatedRequest, $clause)
|
||||
|| preg_match($metaRequest, $clause)
|
||||
|| preg_match($deferredRequest, $clause)) {
|
||||
$decision = false;
|
||||
continue;
|
||||
}
|
||||
foreach ($patterns as $pattern) {
|
||||
if (preg_match($pattern, $clause)) {
|
||||
$decision = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $decision;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
/**
|
||||
* HTTP 请求不宜再阻塞时抛出:任务仍在 ComfyUI 中,消息保持 pending,稍后可恢复。
|
||||
*/
|
||||
class ComfyJobDeferredException extends \RuntimeException
|
||||
{
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
|
||||
|
||||
namespace app\service;
|
||||
|
||||
|
||||
|
||||
use app\model\Department;
|
||||
|
||||
use app\model\User;
|
||||
|
||||
|
||||
|
||||
class DepartmentService
|
||||
|
||||
{
|
||||
|
||||
/**
|
||||
|
||||
* 获取部门及其所有下级部门 ID(含自身)。
|
||||
|
||||
*
|
||||
|
||||
* @return int[]
|
||||
|
||||
*/
|
||||
|
||||
public static function descendantIds(int $departmentId): array
|
||||
|
||||
{
|
||||
|
||||
$all = Department::field('id,parent_id')->select()->toArray();
|
||||
|
||||
$childrenMap = [];
|
||||
|
||||
foreach ($all as $row) {
|
||||
|
||||
$parentId = (int) ($row['parent_id'] ?? 0);
|
||||
|
||||
$childrenMap[$parentId][] = (int) $row['id'];
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
$result = [];
|
||||
|
||||
$stack = [$departmentId];
|
||||
|
||||
while ($stack) {
|
||||
|
||||
$current = array_pop($stack);
|
||||
|
||||
if (in_array($current, $result, true)) {
|
||||
|
||||
continue;
|
||||
|
||||
}
|
||||
|
||||
$result[] = $current;
|
||||
|
||||
foreach ($childrenMap[$current] ?? [] as $childId) {
|
||||
|
||||
$stack[] = $childId;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
return $result;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 构建带层级缩进的部门树(扁平列表,供下拉选择)。
|
||||
|
||||
*/
|
||||
|
||||
public static function treeOptions(): array
|
||||
|
||||
{
|
||||
|
||||
$rows = Department::order('sort_order')->order('id')->select()->toArray();
|
||||
|
||||
$childrenMap = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
|
||||
$parentId = (int) ($row['parent_id'] ?? 0);
|
||||
|
||||
$childrenMap[$parentId][] = $row;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
$options = [];
|
||||
|
||||
self::walkTree($childrenMap, 0, 0, $options);
|
||||
|
||||
|
||||
|
||||
return $options;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static function walkTree(array $childrenMap, int $parentId, int $depth, array &$options): void
|
||||
|
||||
{
|
||||
|
||||
foreach ($childrenMap[$parentId] ?? [] as $row) {
|
||||
|
||||
$prefix = $depth > 0 ? str_repeat(' ', $depth) . '└ ' : '';
|
||||
|
||||
$options[] = [
|
||||
|
||||
'id' => (int) $row['id'],
|
||||
|
||||
'name' => $row['name'],
|
||||
|
||||
'parent_id' => $row['parent_id'] ? (int) $row['parent_id'] : null,
|
||||
|
||||
'label' => $prefix . $row['name'],
|
||||
|
||||
'depth' => $depth,
|
||||
|
||||
];
|
||||
|
||||
self::walkTree($childrenMap, (int) $row['id'], $depth + 1, $options);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 获取某部门及下级部门内的所有用户 ID。
|
||||
|
||||
*
|
||||
|
||||
* @return int[]
|
||||
|
||||
*/
|
||||
|
||||
public static function userIdsInDepartments(array $departmentIds): array
|
||||
|
||||
{
|
||||
|
||||
if (empty($departmentIds)) {
|
||||
|
||||
return [];
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
return User::whereIn('department_id', $departmentIds)->column('id');
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use app\model\AiModel;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
/**
|
||||
* Dify 应用 API 接入服务。
|
||||
*
|
||||
* Dify 使用的是自己的一套接口协议,跟 OpenAI 的 /chat/completions 完全不同:
|
||||
* - 发送消息:POST {api_base_url}/chat-messages
|
||||
* - 上传文件:POST {api_base_url}/files/upload
|
||||
* - 会话上下文由 Dify 自己维护(通过 conversation_id 串联),不需要像 OpenAI 那样
|
||||
* 每次把完整的历史消息数组传过去,只需要传当前这一句 query + 上一次返回的 conversation_id。
|
||||
*
|
||||
* 参考文档:https://docs.dify.ai/api-reference
|
||||
*/
|
||||
class DifyService
|
||||
{
|
||||
public static function chat(AiModel $model, string $query, array $files, ?string $conversationId, string $userId): array
|
||||
{
|
||||
$url = rtrim($model->api_base_url, '/') . '/chat-messages';
|
||||
$payload = self::buildPayload($query, $files, $conversationId, $userId, false);
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload),
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . $model->api_key,
|
||||
],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 120,
|
||||
CURLOPT_CONNECTTIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($response === false) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => 'Dify 请求失败: ' . ($curlError ?: '网络错误'),
|
||||
'data' => null,
|
||||
], 502));
|
||||
}
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
$detail = self::parseErrorBody($response) ?: ('HTTP ' . $httpCode);
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => self::humanizeError('Dify 请求失败: ' . $detail . self::urlHint($httpCode)),
|
||||
'data' => null,
|
||||
], 502));
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
if (!$data) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => 'Dify 响应解析失败',
|
||||
'data' => null,
|
||||
], 502));
|
||||
}
|
||||
|
||||
return [
|
||||
'answer' => $data['answer'] ?? '',
|
||||
'conversation_id' => $data['conversation_id'] ?? null,
|
||||
'tokens' => $data['metadata']['usage']['total_tokens'] ?? 0,
|
||||
];
|
||||
}
|
||||
|
||||
public static function streamChat(
|
||||
AiModel $model,
|
||||
string $query,
|
||||
array $files,
|
||||
?string $conversationId,
|
||||
string $userId,
|
||||
callable $onChunk,
|
||||
callable $onDone,
|
||||
?callable $onError = null
|
||||
): void {
|
||||
$url = rtrim($model->api_base_url, '/') . '/chat-messages';
|
||||
$payload = self::buildPayload($query, $files, $conversationId, $userId, true);
|
||||
|
||||
$errorBody = '';
|
||||
$httpCode = 0;
|
||||
$finalConversationId = $conversationId;
|
||||
$finalTokens = 0;
|
||||
$eventError = null;
|
||||
$streamBuffer = '';
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload),
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . $model->api_key,
|
||||
],
|
||||
CURLOPT_RETURNTRANSFER => false,
|
||||
CURLOPT_HEADERFUNCTION => function ($ch, $header) use (&$httpCode) {
|
||||
if (preg_match('/^HTTP\/\d+\.\d+\s+(\d+)/', $header, $m)) {
|
||||
$httpCode = (int) $m[1];
|
||||
}
|
||||
return strlen($header);
|
||||
},
|
||||
CURLOPT_WRITEFUNCTION => function ($ch, $data) use (
|
||||
&$errorBody,
|
||||
&$httpCode,
|
||||
$onChunk,
|
||||
&$finalConversationId,
|
||||
&$finalTokens,
|
||||
&$eventError,
|
||||
&$streamBuffer
|
||||
) {
|
||||
if ($httpCode >= 400) {
|
||||
$errorBody .= $data;
|
||||
return strlen($data);
|
||||
}
|
||||
|
||||
// cURL may split one SSE data line across arbitrary network chunks.
|
||||
$streamBuffer .= $data;
|
||||
$lines = preg_split('/\r?\n/', $streamBuffer) ?: [];
|
||||
$streamBuffer = (string) (array_pop($lines) ?? '');
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
if ($line === '' || !str_starts_with($line, 'data:')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$json = json_decode(substr($line, 5), true);
|
||||
if (!$json) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$event = $json['event'] ?? '';
|
||||
|
||||
if (!empty($json['conversation_id'])) {
|
||||
$finalConversationId = $json['conversation_id'];
|
||||
}
|
||||
|
||||
if ($event === 'error') {
|
||||
$eventError = $json['message'] ?? 'Dify 返回错误';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($event, ['message', 'agent_message'], true)) {
|
||||
$delta = $json['answer'] ?? '';
|
||||
if ($delta !== '') {
|
||||
$onChunk($delta);
|
||||
}
|
||||
}
|
||||
|
||||
if ($event === 'message_end') {
|
||||
$finalTokens = $json['metadata']['usage']['total_tokens'] ?? $finalTokens;
|
||||
}
|
||||
}
|
||||
|
||||
return strlen($data);
|
||||
},
|
||||
CURLOPT_TIMEOUT => 120,
|
||||
CURLOPT_CONNECTTIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
try {
|
||||
$result = curl_exec($ch);
|
||||
|
||||
if ($result === false) {
|
||||
$message = 'Dify 请求失败: ' . curl_error($ch);
|
||||
$onError ? $onError($message) : null;
|
||||
return;
|
||||
}
|
||||
|
||||
if ($httpCode >= 400) {
|
||||
$detail = self::parseErrorBody($errorBody) ?: ('HTTP ' . $httpCode);
|
||||
$onError ? $onError(self::humanizeError('Dify 请求失败: ' . $detail . self::urlHint($httpCode))) : null;
|
||||
return;
|
||||
}
|
||||
|
||||
if ($eventError) {
|
||||
$onError ? $onError(self::humanizeError('Dify 请求失败: ' . $eventError)) : null;
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
curl_close($ch);
|
||||
}
|
||||
|
||||
$onDone($finalConversationId, $finalTokens);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把本地已上传的文件转发上传到 Dify(Dify 需要自己的 upload_file_id 才能在
|
||||
* chat-messages 里引用文件),失败时返回 null,调用方应做优雅降级处理。
|
||||
*/
|
||||
public static function uploadFile(AiModel $model, string $path, string $mime, string $originalName, string $userId): ?string
|
||||
{
|
||||
[$fileId] = self::uploadFileWithDetail($model, $path, $mime, $originalName, $userId);
|
||||
return $fileId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件到 Dify,失败时返回 [null, errorMessage]
|
||||
*/
|
||||
public static function uploadFileWithDetail(AiModel $model, string $path, string $mime, string $originalName, string $userId): array
|
||||
{
|
||||
if (!is_file($path)) {
|
||||
return [null, '本地文件不存在'];
|
||||
}
|
||||
|
||||
$url = rtrim($model->api_base_url, '/') . '/files/upload';
|
||||
$safeName = self::safeUploadFilename($originalName, $path, $mime);
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => [
|
||||
'file' => curl_file_create($path, $mime, $safeName),
|
||||
'user' => $userId,
|
||||
],
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Authorization: Bearer ' . $model->api_key,
|
||||
],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 60,
|
||||
CURLOPT_CONNECTTIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($response === false) {
|
||||
return [null, '网络错误: ' . ($curlError ?: '无法连接 Dify')];
|
||||
}
|
||||
|
||||
if ($httpCode !== 200 && $httpCode !== 201) {
|
||||
$detail = self::parseErrorBody($response) ?: ('HTTP ' . $httpCode);
|
||||
return [null, $detail];
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
$fileId = $data['id'] ?? ($data['data']['id'] ?? null);
|
||||
|
||||
return $fileId ? [$fileId, null] : [null, 'Dify 未返回 file_id'];
|
||||
}
|
||||
|
||||
private static function safeUploadFilename(string $originalName, string $path, string $mime): string
|
||||
{
|
||||
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION) ?: pathinfo($path, PATHINFO_EXTENSION));
|
||||
if ($ext === '') {
|
||||
$ext = match (true) {
|
||||
str_starts_with($mime, 'image/png') => 'png',
|
||||
str_starts_with($mime, 'image/gif') => 'gif',
|
||||
str_starts_with($mime, 'image/webp') => 'webp',
|
||||
default => 'jpg',
|
||||
};
|
||||
}
|
||||
|
||||
return 'upload_' . uniqid('', true) . '.' . $ext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试 Dify 应用连接是否正常
|
||||
*/
|
||||
public static function testConnection(array $config): array
|
||||
{
|
||||
$apiBaseUrl = rtrim($config['api_base_url'] ?? '', '/');
|
||||
$apiKey = $config['api_key'] ?? '';
|
||||
|
||||
if (!$apiBaseUrl) {
|
||||
throw new \InvalidArgumentException('请填写 API 地址(Dify 应用的 API Base URL,如 https://api.dify.ai/v1)');
|
||||
}
|
||||
if (!$apiKey) {
|
||||
throw new \InvalidArgumentException('请填写 API Key(在 Dify 应用的"访问 API"页面获取)');
|
||||
}
|
||||
|
||||
$url = $apiBaseUrl . '/chat-messages';
|
||||
$payload = [
|
||||
'inputs' => new \stdClass(),
|
||||
'query' => '请只回复:测试成功',
|
||||
'response_mode' => 'blocking',
|
||||
'conversation_id' => '',
|
||||
'user' => 'connection-test',
|
||||
];
|
||||
|
||||
$start = microtime(true);
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload),
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . $apiKey,
|
||||
],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 30,
|
||||
CURLOPT_CONNECTTIMEOUT => 10,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
$latencyMs = (int) round((microtime(true) - $start) * 1000);
|
||||
|
||||
if ($response === false) {
|
||||
throw new \RuntimeException('连接失败: ' . ($curlError ?: '网络不可达'));
|
||||
}
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
$detail = self::parseErrorBody($response) ?: ('HTTP ' . $httpCode);
|
||||
throw new \RuntimeException('API 返回错误: ' . $detail . self::urlHint($httpCode));
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
if (!$data) {
|
||||
throw new \RuntimeException('响应解析失败,请确认接口地址正确');
|
||||
}
|
||||
|
||||
$reply = $data['answer'] ?? '';
|
||||
if ($reply === '') {
|
||||
throw new \RuntimeException('接口连接成功,但未返回有效内容');
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'latency_ms' => $latencyMs,
|
||||
'reply' => $reply,
|
||||
'model' => 'dify',
|
||||
'tokens' => $data['metadata']['usage']['total_tokens'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
private static function buildPayload(string $query, array $files, ?string $conversationId, string $userId, bool $streaming): array
|
||||
{
|
||||
$payload = [
|
||||
// 注意:必须用 stdClass 而不是 [],PHP 的空数组 json_encode 后是 "[]",
|
||||
// 但 Dify(Pydantic)要求 inputs 必须是字典 "{}",否则会报
|
||||
// "Input should be a valid dictionary" 的校验错误
|
||||
'inputs' => new \stdClass(),
|
||||
'query' => $query,
|
||||
'response_mode' => $streaming ? 'streaming' : 'blocking',
|
||||
'conversation_id' => $conversationId ?: '',
|
||||
'user' => $userId,
|
||||
];
|
||||
|
||||
if ($files) {
|
||||
$payload['files'] = $files;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
private static function urlHint(int $httpCode): string
|
||||
{
|
||||
if ($httpCode === 404) {
|
||||
return '(请确认 API 地址填写的是 Dify 的 API 根路径,如 https://api.dify.ai/v1 或自部署的 http://your-host/v1,Dify 使用 /chat-messages 接口,不是 OpenAI 的 /chat/completions)';
|
||||
}
|
||||
if ($httpCode === 401) {
|
||||
return '(请确认 API Key 是在 Dify 应用"访问 API"页面获取的密钥,而不是账号登录密码或 OpenAI Key)';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
private static function parseErrorBody(?string $body): ?string
|
||||
{
|
||||
if (!$body) {
|
||||
return null;
|
||||
}
|
||||
$json = json_decode($body, true);
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
return $json['message'] ?? null;
|
||||
}
|
||||
return trim($body) ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 Dify 插件/模型层的英文错误转为可操作的中文提示
|
||||
*/
|
||||
public static function humanizeError(string $message): string
|
||||
{
|
||||
if (str_contains($message, "Unsupported chat content part type: 'file'")
|
||||
|| str_contains($message, 'Unsupported chat content part type')) {
|
||||
return 'Dify 模型层仍不接受 file 类型。请确认 Dify 应用已开启文档上传,且 files.type 使用 document(不是 file)。'
|
||||
. ' 原始错误:' . mb_substr($message, 0, 180);
|
||||
}
|
||||
|
||||
if (str_contains($message, 'PluginInvokeError')) {
|
||||
return 'Dify 插件调用失败,请检查 Dify 应用内模型供应商配置是否与图片输入兼容。'
|
||||
. ' 详情:' . mb_substr($message, 0, 300);
|
||||
}
|
||||
|
||||
return $message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
/**
|
||||
* 从常见文档格式提取纯文本,供 Dify 等不支持 file 附件的接口使用。
|
||||
*/
|
||||
class DocumentTextService
|
||||
{
|
||||
private const MAX_CHARS = 12000;
|
||||
|
||||
/** @var string|null 最近一次 extract 失败原因(供上层展示) */
|
||||
private static ?string $lastFailure = null;
|
||||
|
||||
public static function extract(string $path, string $mime = '', string $filename = ''): ?string
|
||||
{
|
||||
self::$lastFailure = null;
|
||||
|
||||
if (!is_file($path) || !is_readable($path)) {
|
||||
self::$lastFailure = 'file_unreadable';
|
||||
return null;
|
||||
}
|
||||
|
||||
$ext = strtolower(pathinfo($filename ?: $path, PATHINFO_EXTENSION));
|
||||
$mime = strtolower($mime);
|
||||
|
||||
$text = match (true) {
|
||||
in_array($ext, ['txt', 'md'], true) || str_starts_with($mime, 'text/') => self::readPlainText($path),
|
||||
$ext === 'docx' || str_contains($mime, 'wordprocessingml') => self::extractDocx($path),
|
||||
$ext === 'pdf' || str_contains($mime, 'pdf') => self::extractPdf($path),
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($text === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$text = self::normalize($text);
|
||||
|
||||
if ($text === '') {
|
||||
if (self::$lastFailure === null) {
|
||||
self::$lastFailure = 'empty_content';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return mb_substr($text, 0, self::MAX_CHARS);
|
||||
}
|
||||
|
||||
public static function unsupportedReason(string $filename, string $mime = ''): string
|
||||
{
|
||||
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
|
||||
|
||||
if (self::$lastFailure === 'exec_disabled') {
|
||||
return 'PHP 禁用了 exec 函数,无法调用 pdftotext。请在 php.ini 的 disable_functions 中移除 exec';
|
||||
}
|
||||
|
||||
if (self::$lastFailure === 'pdftotext_missing') {
|
||||
return '未找到 pdftotext 命令。请在**运行 PHP 的服务器**(不是 Dify 容器)执行:apt install poppler-utils';
|
||||
}
|
||||
|
||||
if (self::$lastFailure === 'pdftotext_failed') {
|
||||
return 'pdftotext 执行失败,请检查 PDF 是否损坏或 uploads 目录是否可读';
|
||||
}
|
||||
|
||||
if (self::$lastFailure === 'empty_content' && ($ext === 'pdf' || str_contains($mime, 'pdf'))) {
|
||||
return 'PDF 未提取到文字,可能是扫描版图片 PDF,请改用可复制文字的 PDF 或粘贴文字';
|
||||
}
|
||||
|
||||
if ($ext === 'doc' || str_contains($mime, 'msword')) {
|
||||
return '旧版 .doc 暂不支持自动解析,请另存为 .docx 或复制文字发送';
|
||||
}
|
||||
|
||||
if ($ext === 'pdf' || str_contains($mime, 'pdf')) {
|
||||
return 'PDF 文字提取失败,请在运行 PHP 的服务器安装 poppler-utils(pdftotext)';
|
||||
}
|
||||
|
||||
if (!class_exists(\ZipArchive::class) && ($ext === 'docx' || str_contains($mime, 'wordprocessingml'))) {
|
||||
return 'PHP 未启用 zip 扩展,无法解析 .docx,请安装 php-zip';
|
||||
}
|
||||
|
||||
return '未能提取文档文字,请改用 .txt / .docx 或粘贴文字内容';
|
||||
}
|
||||
|
||||
private static function readPlainText(string $path): ?string
|
||||
{
|
||||
$content = @file_get_contents($path);
|
||||
if ($content === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!mb_check_encoding($content, 'UTF-8')) {
|
||||
$content = mb_convert_encoding($content, 'UTF-8', 'GB18030,UTF-8,ASCII');
|
||||
}
|
||||
|
||||
return $content;
|
||||
}
|
||||
|
||||
private static function extractDocx(string $path): ?string
|
||||
{
|
||||
if (!class_exists(\ZipArchive::class)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$zip = new \ZipArchive();
|
||||
if ($zip->open($path) !== true) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$xml = $zip->getFromName('word/document.xml');
|
||||
$zip->close();
|
||||
|
||||
if (!$xml) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$xml = preg_replace('/<w:tab[^>]*\/>/', "\t", $xml);
|
||||
$xml = preg_replace('/<\/w:p>/', "\n", $xml);
|
||||
$xml = preg_replace('/<\/w:tr>/', "\n", $xml);
|
||||
|
||||
$text = strip_tags($xml);
|
||||
|
||||
return html_entity_decode($text, ENT_QUOTES | ENT_XML1, 'UTF-8');
|
||||
}
|
||||
|
||||
private static function extractPdf(string $path): ?string
|
||||
{
|
||||
if (!function_exists('exec')) {
|
||||
self::$lastFailure = 'exec_disabled';
|
||||
return null;
|
||||
}
|
||||
|
||||
$binary = self::resolvePdftotextBinary();
|
||||
if ($binary === null) {
|
||||
self::$lastFailure = 'pdftotext_missing';
|
||||
return null;
|
||||
}
|
||||
|
||||
$out = tempnam(sys_get_temp_dir(), 'pdftxt_');
|
||||
if (!$out) {
|
||||
self::$lastFailure = 'pdftotext_failed';
|
||||
return null;
|
||||
}
|
||||
|
||||
$cmd = escapeshellarg($binary) . ' -enc UTF-8 -layout '
|
||||
. escapeshellarg($path) . ' ' . escapeshellarg($out) . ' 2>&1';
|
||||
exec($cmd, $_, $code);
|
||||
|
||||
$text = ($code === 0 && is_file($out)) ? @file_get_contents($out) : false;
|
||||
@unlink($out);
|
||||
|
||||
if ($text === false) {
|
||||
self::$lastFailure = 'pdftotext_failed';
|
||||
return null;
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* PHP-FPM 进程的 PATH 常不含 /usr/bin,需显式探测可执行文件路径。
|
||||
*/
|
||||
private static function resolvePdftotextBinary(): ?string
|
||||
{
|
||||
$candidates = [
|
||||
'/usr/bin/pdftotext',
|
||||
'/usr/local/bin/pdftotext',
|
||||
'pdftotext',
|
||||
];
|
||||
|
||||
foreach ($candidates as $bin) {
|
||||
if (str_starts_with($bin, '/')) {
|
||||
if (is_executable($bin)) {
|
||||
return $bin;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (self::commandExists($bin)) {
|
||||
return $bin;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function commandExists(string $command): bool
|
||||
{
|
||||
if (!function_exists('exec')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$check = stripos(PHP_OS, 'WIN') === 0 ? 'where' : 'command -v';
|
||||
exec($check . ' ' . escapeshellarg($command) . ' 2>/dev/null', $output, $code);
|
||||
|
||||
return $code === 0 && !empty($output);
|
||||
}
|
||||
|
||||
private static function normalize(string $text): string
|
||||
{
|
||||
$text = str_replace(["\r\n", "\r"], "\n", $text);
|
||||
$text = preg_replace("/[ \t]+\n/", "\n", $text);
|
||||
$text = preg_replace("/\n{3,}/", "\n\n", $text);
|
||||
|
||||
return trim($text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
class JwtService
|
||||
{
|
||||
public static function generateToken(array $payload): string
|
||||
{
|
||||
$secret = config('jwt.secret');
|
||||
$expire = config('jwt.expire');
|
||||
|
||||
$header = self::base64UrlEncode(json_encode(['typ' => 'JWT', 'alg' => 'HS256']));
|
||||
$payload['exp'] = time() + $expire;
|
||||
$payload['iat'] = time();
|
||||
$body = self::base64UrlEncode(json_encode($payload));
|
||||
$signature = self::base64UrlEncode(hash_hmac('sha256', "{$header}.{$body}", $secret, true));
|
||||
|
||||
return "{$header}.{$body}.{$signature}";
|
||||
}
|
||||
|
||||
public static function verifyToken(?string $token): ?array
|
||||
{
|
||||
if (!$token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (str_starts_with($token, 'Bearer ')) {
|
||||
$token = substr($token, 7);
|
||||
}
|
||||
|
||||
$parts = explode('.', $token);
|
||||
if (count($parts) !== 3) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$header, $body, $signature] = $parts;
|
||||
$secret = config('jwt.secret');
|
||||
$expected = self::base64UrlEncode(hash_hmac('sha256', "{$header}.{$body}", $secret, true));
|
||||
|
||||
if (!hash_equals($expected, $signature)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$payload = json_decode(self::base64UrlDecode($body), true);
|
||||
if (!$payload || ($payload['exp'] ?? 0) < time()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
private static function base64UrlEncode(string $data): string
|
||||
{
|
||||
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
private static function base64UrlDecode(string $data): string
|
||||
{
|
||||
return base64_decode(strtr($data, '-_', '+/'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use app\model\AiModel;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
class OpenAIService
|
||||
{
|
||||
public static function getModel(?int $modelId = null): AiModel
|
||||
{
|
||||
if ($modelId) {
|
||||
$model = AiModel::where('id', $modelId)->where('enabled', 1)->find();
|
||||
} else {
|
||||
$model = AiModel::where('is_default', 1)->where('enabled', 1)->find();
|
||||
}
|
||||
|
||||
if (!$model) {
|
||||
$model = AiModel::where('enabled', 1)->order('sort_order')->find();
|
||||
}
|
||||
|
||||
if (!$model) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => '未配置可用的 AI 模型',
|
||||
'data' => null,
|
||||
], 500));
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
public static function getLanguageModel(?int $preferredModelId = null): AiModel
|
||||
{
|
||||
$model = null;
|
||||
if ($preferredModelId) {
|
||||
$model = AiModel::where('id', $preferredModelId)
|
||||
->where('enabled', 1)
|
||||
->where('provider', '<>', 'comfy')
|
||||
->find();
|
||||
}
|
||||
|
||||
if (!$model) {
|
||||
$model = AiModel::where('enabled', 1)
|
||||
->where('provider', '<>', 'comfy')
|
||||
->order('is_default', 'desc')
|
||||
->order('sort_order')
|
||||
->find();
|
||||
}
|
||||
|
||||
if (!$model) {
|
||||
self::throwUnavailableModel('未配置可用的语言模型,Agent 暂时无法处理文本任务');
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
public static function getImageModel(?int $preferredModelId = null): AiModel
|
||||
{
|
||||
$model = null;
|
||||
if ($preferredModelId) {
|
||||
$model = AiModel::where('id', $preferredModelId)
|
||||
->where('enabled', 1)
|
||||
->where('provider', 'comfy')
|
||||
->find();
|
||||
}
|
||||
|
||||
if (!$model) {
|
||||
$model = AiModel::where('enabled', 1)
|
||||
->where('provider', 'comfy')
|
||||
->order('is_default', 'desc')
|
||||
->order('sort_order')
|
||||
->find();
|
||||
}
|
||||
|
||||
if (!$model) {
|
||||
self::throwUnavailableModel('未配置可用的图片生成模型,Agent 暂时无法生成图片');
|
||||
}
|
||||
|
||||
return $model;
|
||||
}
|
||||
|
||||
private static function throwUnavailableModel(string $message): void
|
||||
{
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => $message,
|
||||
'data' => null,
|
||||
], 503));
|
||||
}
|
||||
|
||||
/**
|
||||
* frequency_penalty / presence_penalty 是 OpenAI 协议标准参数,vLLM/SGLang 等
|
||||
* OpenAI 兼容服务通常都支持。部分自部署模型(尤其是 OCR/文档解析类模型)在纯文本
|
||||
* 对话场景下容易陷入重复输出循环,通过这两个参数可以有效抑制。仅在管理员配置了
|
||||
* 非零值时才带上,避免影响已经正常工作的模型。
|
||||
*/
|
||||
private static function penaltyParams(AiModel $model): array
|
||||
{
|
||||
$params = [];
|
||||
$frequencyPenalty = (float) ($model->frequency_penalty ?? 0);
|
||||
$presencePenalty = (float) ($model->presence_penalty ?? 0);
|
||||
|
||||
if ($frequencyPenalty !== 0.0) {
|
||||
$params['frequency_penalty'] = $frequencyPenalty;
|
||||
}
|
||||
if ($presencePenalty !== 0.0) {
|
||||
$params['presence_penalty'] = $presencePenalty;
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
public static function streamChat(AiModel $model, array $messages, callable $onChunk, ?callable $onError = null): void
|
||||
{
|
||||
$url = rtrim($model->api_base_url, '/') . '/chat/completions';
|
||||
$payload = array_merge([
|
||||
'model' => $model->model_id,
|
||||
'messages' => $messages,
|
||||
'stream' => true,
|
||||
'max_tokens' => (int) $model->max_tokens,
|
||||
'temperature' => (float) $model->temperature,
|
||||
], self::penaltyParams($model));
|
||||
|
||||
$errorBody = '';
|
||||
$httpCode = 0;
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload),
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . $model->api_key,
|
||||
],
|
||||
CURLOPT_RETURNTRANSFER => false,
|
||||
CURLOPT_HEADERFUNCTION => function ($ch, $header) use (&$httpCode) {
|
||||
if (preg_match('/^HTTP\/\d+\.\d+\s+(\d+)/', $header, $m)) {
|
||||
$httpCode = (int) $m[1];
|
||||
}
|
||||
return strlen($header);
|
||||
},
|
||||
CURLOPT_WRITEFUNCTION => function ($ch, $data) use (&$errorBody, &$httpCode, $onChunk) {
|
||||
if ($httpCode >= 400) {
|
||||
$errorBody .= $data;
|
||||
return strlen($data);
|
||||
}
|
||||
|
||||
$lines = explode("\n", $data);
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
if ($line === '' || $line === 'data: [DONE]') {
|
||||
continue;
|
||||
}
|
||||
if (str_starts_with($line, 'data: ')) {
|
||||
$json = json_decode(substr($line, 6), true);
|
||||
if ($json) {
|
||||
if (!empty($json['error']['message'])) {
|
||||
throw new \RuntimeException($json['error']['message']);
|
||||
}
|
||||
$onChunk($json);
|
||||
}
|
||||
}
|
||||
}
|
||||
return strlen($data);
|
||||
},
|
||||
CURLOPT_TIMEOUT => 120,
|
||||
CURLOPT_CONNECTTIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
try {
|
||||
$result = curl_exec($ch);
|
||||
if ($result === false) {
|
||||
$message = 'AI 请求失败: ' . curl_error($ch);
|
||||
if ($onError) {
|
||||
$onError($message);
|
||||
} else {
|
||||
self::sseEvent('error', ['message' => $message]);
|
||||
}
|
||||
curl_close($ch);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($httpCode >= 400) {
|
||||
$detail = self::parseErrorBody($errorBody) ?: ('HTTP ' . $httpCode);
|
||||
$message = 'AI 请求失败: ' . $detail;
|
||||
if ($onError) {
|
||||
$onError($message);
|
||||
} else {
|
||||
self::sseEvent('error', ['message' => $message]);
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
if ($onError) {
|
||||
$onError($e->getMessage());
|
||||
} else {
|
||||
self::sseEvent('error', ['message' => $e->getMessage()]);
|
||||
}
|
||||
} finally {
|
||||
curl_close($ch);
|
||||
}
|
||||
}
|
||||
|
||||
public static function chat(AiModel $model, array $messages): array
|
||||
{
|
||||
$url = rtrim($model->api_base_url, '/') . '/chat/completions';
|
||||
$payload = array_merge([
|
||||
'model' => $model->model_id,
|
||||
'messages' => $messages,
|
||||
'stream' => false,
|
||||
'max_tokens' => (int) $model->max_tokens,
|
||||
'temperature' => (float) $model->temperature,
|
||||
], self::penaltyParams($model));
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload),
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . $model->api_key,
|
||||
],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 120,
|
||||
CURLOPT_CONNECTTIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
$detail = self::parseErrorBody($response) ?: ('HTTP ' . $httpCode);
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => 'AI 请求失败: ' . $detail,
|
||||
'data' => null,
|
||||
], 502));
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
if (!$data) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => 'AI 响应解析失败',
|
||||
'data' => null,
|
||||
], 502));
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试模型连接是否正常
|
||||
* @return array{success: bool, latency_ms: int, reply: string, model: string}
|
||||
*/
|
||||
public static function testConnection(array $config): array
|
||||
{
|
||||
$apiBaseUrl = rtrim($config['api_base_url'] ?? '', '/');
|
||||
$modelId = trim($config['model_id'] ?? '');
|
||||
$apiKey = $config['api_key'] ?? '';
|
||||
|
||||
if (!$apiBaseUrl || !$modelId) {
|
||||
throw new \InvalidArgumentException('请填写 API 地址和 Model ID');
|
||||
}
|
||||
|
||||
$url = $apiBaseUrl . '/chat/completions';
|
||||
$payload = [
|
||||
'model' => $modelId,
|
||||
'messages' => [
|
||||
['role' => 'user', 'content' => '请只回复:测试成功'],
|
||||
],
|
||||
'stream' => false,
|
||||
'max_tokens' => 32,
|
||||
'temperature' => (float) ($config['temperature'] ?? 0.7),
|
||||
];
|
||||
|
||||
$headers = ['Content-Type: application/json'];
|
||||
if ($apiKey !== '') {
|
||||
$headers[] = 'Authorization: Bearer ' . $apiKey;
|
||||
}
|
||||
|
||||
$start = microtime(true);
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload),
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 30,
|
||||
CURLOPT_CONNECTTIMEOUT => 10,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
$latencyMs = (int) round((microtime(true) - $start) * 1000);
|
||||
|
||||
if ($response === false) {
|
||||
throw new \RuntimeException('连接失败: ' . ($curlError ?: '网络不可达'));
|
||||
}
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
$detail = self::parseErrorBody($response) ?: ('HTTP ' . $httpCode);
|
||||
throw new \RuntimeException('API 返回错误: ' . $detail);
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
if (!$data) {
|
||||
throw new \RuntimeException('响应解析失败,请确认接口为 OpenAI 兼容格式');
|
||||
}
|
||||
|
||||
$reply = self::extractMessageContent($data);
|
||||
if ($reply === '') {
|
||||
throw new \RuntimeException('接口连接成功,但未返回有效内容');
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'latency_ms' => $latencyMs,
|
||||
'reply' => $reply,
|
||||
'model' => $modelId,
|
||||
'tokens' => $data['usage']['total_tokens'] ?? null,
|
||||
];
|
||||
}
|
||||
|
||||
public static function extractStreamDelta(array $chunk): string
|
||||
{
|
||||
$choice = $chunk['choices'][0] ?? [];
|
||||
$delta = $choice['delta'] ?? [];
|
||||
$message = $choice['message'] ?? [];
|
||||
|
||||
$content = $delta['content']
|
||||
?? $delta['reasoning_content']
|
||||
?? $message['content']
|
||||
?? '';
|
||||
|
||||
return is_string($content) ? $content : '';
|
||||
}
|
||||
|
||||
public static function extractMessageContent(array $result): string
|
||||
{
|
||||
$choice = $result['choices'][0] ?? [];
|
||||
$message = $choice['message'] ?? [];
|
||||
|
||||
$content = $message['content']
|
||||
?? $message['reasoning_content']
|
||||
?? $choice['text']
|
||||
?? '';
|
||||
|
||||
return is_string($content) ? trim($content) : '';
|
||||
}
|
||||
|
||||
public static function sseHeaders(): void
|
||||
{
|
||||
header('Content-Type: text/event-stream; charset=utf-8');
|
||||
header('Cache-Control: no-cache, no-transform');
|
||||
header('Connection: keep-alive');
|
||||
header('X-Accel-Buffering: no');
|
||||
}
|
||||
|
||||
public static function sseEvent(string $event, mixed $data): void
|
||||
{
|
||||
// 用户关闭页面后仍继续后台等待,不再往已断开的连接写数据
|
||||
if (connection_aborted()) {
|
||||
return;
|
||||
}
|
||||
|
||||
echo "event: {$event}\n";
|
||||
echo 'data: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
|
||||
if (ob_get_level() > 0) {
|
||||
@ob_flush();
|
||||
}
|
||||
@flush();
|
||||
}
|
||||
|
||||
private static function parseErrorBody(?string $body): ?string
|
||||
{
|
||||
if (!$body) {
|
||||
return null;
|
||||
}
|
||||
$json = json_decode($body, true);
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
return $json['error']['message'] ?? $json['message'] ?? null;
|
||||
}
|
||||
return trim($body) ?: null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use app\model\SysPermission;
|
||||
use think\facade\Db;
|
||||
|
||||
/**
|
||||
* 后台权限目录:目录(dir) / 菜单(menu) / 按钮(btn)
|
||||
* 优先从 sys_permissions 表读取,表不存在时回退内置定义。
|
||||
*/
|
||||
class PermissionCatalog
|
||||
{
|
||||
public static function builtinTree(): array
|
||||
{
|
||||
return [
|
||||
[
|
||||
'code' => 'dir:overview',
|
||||
'name' => '概览',
|
||||
'type' => 'dir',
|
||||
'children' => [
|
||||
[
|
||||
'code' => 'menu:dashboard',
|
||||
'name' => '数据概览',
|
||||
'type' => 'menu',
|
||||
'path' => '/dashboard',
|
||||
'icon' => '📊',
|
||||
'children' => [],
|
||||
],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'dir:org',
|
||||
'name' => '组织架构',
|
||||
'type' => 'dir',
|
||||
'children' => [
|
||||
[
|
||||
'code' => 'menu:users',
|
||||
'name' => '用户管理',
|
||||
'type' => 'menu',
|
||||
'path' => '/users',
|
||||
'icon' => '👥',
|
||||
'children' => [
|
||||
['code' => 'btn:user:create', 'name' => '新增用户', 'type' => 'btn'],
|
||||
['code' => 'btn:user:edit', 'name' => '编辑用户', 'type' => 'btn'],
|
||||
['code' => 'btn:user:reset_password', 'name' => '重置密码', 'type' => 'btn'],
|
||||
['code' => 'btn:user:delete', 'name' => '删除用户', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'menu:departments',
|
||||
'name' => '部门管理',
|
||||
'type' => 'menu',
|
||||
'path' => '/departments',
|
||||
'icon' => '🏢',
|
||||
'children' => [
|
||||
['code' => 'btn:dept:create', 'name' => '新增部门', 'type' => 'btn'],
|
||||
['code' => 'btn:dept:edit', 'name' => '编辑部门', 'type' => 'btn'],
|
||||
['code' => 'btn:dept:delete', 'name' => '删除部门', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'menu:roles',
|
||||
'name' => '角色管理',
|
||||
'type' => 'menu',
|
||||
'path' => '/roles',
|
||||
'icon' => '🛡️',
|
||||
'children' => [
|
||||
['code' => 'btn:role:create', 'name' => '新增角色', 'type' => 'btn'],
|
||||
['code' => 'btn:role:edit', 'name' => '编辑角色', 'type' => 'btn'],
|
||||
['code' => 'btn:role:delete', 'name' => '删除角色', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'dir:business',
|
||||
'name' => '业务数据',
|
||||
'type' => 'dir',
|
||||
'children' => [
|
||||
[
|
||||
'code' => 'menu:conversations',
|
||||
'name' => '会话管理',
|
||||
'type' => 'menu',
|
||||
'path' => '/conversations',
|
||||
'icon' => '💬',
|
||||
'children' => [
|
||||
['code' => 'btn:conv:view_all', 'name' => '查看全部会话', 'type' => 'btn'],
|
||||
['code' => 'btn:conv:view_subordinate', 'name' => '查看下级部门会话', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'menu:memberships',
|
||||
'name' => '会员等级',
|
||||
'type' => 'menu',
|
||||
'path' => '/memberships',
|
||||
'icon' => '⭐',
|
||||
'children' => [
|
||||
['code' => 'btn:membership:create', 'name' => '新增会员等级', 'type' => 'btn'],
|
||||
['code' => 'btn:membership:edit', 'name' => '编辑会员等级', 'type' => 'btn'],
|
||||
['code' => 'btn:membership:delete', 'name' => '删除会员等级', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'dir:system',
|
||||
'name' => '系统管理',
|
||||
'type' => 'dir',
|
||||
'children' => [
|
||||
[
|
||||
'code' => 'menu:models',
|
||||
'name' => 'AI 模型',
|
||||
'type' => 'menu',
|
||||
'path' => '/models',
|
||||
'icon' => '🤖',
|
||||
'children' => [
|
||||
['code' => 'btn:model:create', 'name' => '新增模型', 'type' => 'btn'],
|
||||
['code' => 'btn:model:edit', 'name' => '编辑模型', 'type' => 'btn'],
|
||||
['code' => 'btn:model:delete', 'name' => '删除模型', 'type' => 'btn'],
|
||||
['code' => 'btn:model:test', 'name' => '测试连接', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'menu:permissions',
|
||||
'name' => '权限管理',
|
||||
'type' => 'menu',
|
||||
'path' => '/permissions',
|
||||
'icon' => '🔑',
|
||||
'children' => [
|
||||
['code' => 'btn:perm:create', 'name' => '新增权限', 'type' => 'btn'],
|
||||
['code' => 'btn:perm:edit', 'name' => '编辑权限', 'type' => 'btn'],
|
||||
['code' => 'btn:perm:delete', 'name' => '删除权限', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
[
|
||||
'code' => 'menu:settings',
|
||||
'name' => '系统设置',
|
||||
'type' => 'menu',
|
||||
'path' => '/settings',
|
||||
'icon' => '🔧',
|
||||
'children' => [
|
||||
['code' => 'btn:settings:save', 'name' => '保存设置', 'type' => 'btn'],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function tree(): array
|
||||
{
|
||||
try {
|
||||
if (!self::tableReady()) {
|
||||
return self::builtinTree();
|
||||
}
|
||||
|
||||
$rows = SysPermission::order('sort_order')->order('id')->select()->toArray();
|
||||
if (!$rows) {
|
||||
return self::builtinTree();
|
||||
}
|
||||
|
||||
return self::buildTreeFromRows($rows);
|
||||
} catch (\Throwable $e) {
|
||||
return self::builtinTree();
|
||||
}
|
||||
}
|
||||
|
||||
public static function flatList(): array
|
||||
{
|
||||
try {
|
||||
if (!self::tableReady()) {
|
||||
return self::flattenBuiltin();
|
||||
}
|
||||
return SysPermission::order('sort_order')->order('id')->select()->toArray();
|
||||
} catch (\Throwable $e) {
|
||||
return self::flattenBuiltin();
|
||||
}
|
||||
}
|
||||
|
||||
private static function tableReady(): bool
|
||||
{
|
||||
static $ready = null;
|
||||
if ($ready !== null) {
|
||||
return $ready;
|
||||
}
|
||||
try {
|
||||
$db = Db::getConfig('database') ?: env('DB_NAME', 'ai_chat');
|
||||
$rows = Db::query(
|
||||
'SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? LIMIT 1',
|
||||
[$db, 'sys_permissions']
|
||||
);
|
||||
$ready = !empty($rows);
|
||||
} catch (\Throwable $e) {
|
||||
$ready = false;
|
||||
}
|
||||
return $ready;
|
||||
}
|
||||
|
||||
private static function buildTreeFromRows(array $rows): array
|
||||
{
|
||||
$byParent = [];
|
||||
foreach ($rows as $row) {
|
||||
$pid = $row['parent_id'] ? (int) $row['parent_id'] : 0;
|
||||
$byParent[$pid][] = $row;
|
||||
}
|
||||
|
||||
$mapNode = function (array $row) use (&$mapNode, $byParent) {
|
||||
$children = [];
|
||||
foreach ($byParent[(int) $row['id']] ?? [] as $child) {
|
||||
$children[] = $mapNode($child);
|
||||
}
|
||||
return [
|
||||
'id' => (int) $row['id'],
|
||||
'code' => $row['code'],
|
||||
'name' => $row['name'],
|
||||
'type' => $row['type'],
|
||||
'path' => $row['path'] ?? '',
|
||||
'icon' => $row['icon'] ?? '',
|
||||
'parent_id' => $row['parent_id'] ? (int) $row['parent_id'] : null,
|
||||
'sort_order' => (int) ($row['sort_order'] ?? 0),
|
||||
'is_system' => (int) ($row['is_system'] ?? 0),
|
||||
'children' => $children,
|
||||
];
|
||||
};
|
||||
|
||||
$tree = [];
|
||||
foreach ($byParent[0] ?? [] as $root) {
|
||||
$tree[] = $mapNode($root);
|
||||
}
|
||||
return $tree;
|
||||
}
|
||||
|
||||
private static function flattenBuiltin(): array
|
||||
{
|
||||
$list = [];
|
||||
$walk = function (array $nodes, $parentId = null) use (&$walk, &$list) {
|
||||
foreach ($nodes as $i => $node) {
|
||||
$id = count($list) + 1;
|
||||
$list[] = [
|
||||
'id' => $id,
|
||||
'type' => $node['type'],
|
||||
'code' => $node['code'],
|
||||
'name' => $node['name'],
|
||||
'parent_id' => $parentId,
|
||||
'path' => $node['path'] ?? null,
|
||||
'icon' => $node['icon'] ?? null,
|
||||
'sort_order' => $i,
|
||||
'is_system' => 1,
|
||||
];
|
||||
if (!empty($node['children'])) {
|
||||
$walk($node['children'], $id);
|
||||
}
|
||||
}
|
||||
};
|
||||
$walk(self::builtinTree());
|
||||
return $list;
|
||||
}
|
||||
|
||||
public static function emptyPermissions(): array
|
||||
{
|
||||
$perms = [
|
||||
'can_access_admin' => false,
|
||||
'dirs' => [],
|
||||
'menus' => [],
|
||||
'buttons' => [],
|
||||
];
|
||||
foreach (self::legacyKeys() as $key) {
|
||||
$perms[$key] = false;
|
||||
}
|
||||
return $perms;
|
||||
}
|
||||
|
||||
public static function fullPermissions(): array
|
||||
{
|
||||
$dirs = [];
|
||||
$menus = [];
|
||||
$buttons = [];
|
||||
|
||||
foreach (self::tree() as $dir) {
|
||||
$dirs[] = $dir['code'];
|
||||
foreach ($dir['children'] ?? [] as $menu) {
|
||||
$menus[] = $menu['code'];
|
||||
foreach ($menu['children'] ?? [] as $btn) {
|
||||
$buttons[] = $btn['code'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$perms = [
|
||||
'can_access_admin' => true,
|
||||
'dirs' => $dirs,
|
||||
'menus' => $menus,
|
||||
'buttons' => $buttons,
|
||||
];
|
||||
foreach (self::legacyKeys() as $key) {
|
||||
$perms[$key] = true;
|
||||
}
|
||||
return $perms;
|
||||
}
|
||||
|
||||
public static function legacyKeys(): array
|
||||
{
|
||||
return [
|
||||
'can_manage_users',
|
||||
'can_manage_roles',
|
||||
'can_manage_departments',
|
||||
'can_view_all_conversations',
|
||||
'can_view_subordinate_conversations',
|
||||
'can_manage_models',
|
||||
'can_manage_settings',
|
||||
'can_manage_memberships',
|
||||
'can_manage_permissions',
|
||||
];
|
||||
}
|
||||
|
||||
public static function normalize(array $input): array
|
||||
{
|
||||
$base = self::emptyPermissions();
|
||||
$dirs = array_values(array_unique(array_filter((array) ($input['dirs'] ?? []))));
|
||||
$menus = array_values(array_unique(array_filter((array) ($input['menus'] ?? []))));
|
||||
$buttons = array_values(array_unique(array_filter((array) ($input['buttons'] ?? []))));
|
||||
|
||||
if (empty($menus) && empty($buttons) && empty($dirs)) {
|
||||
[$dirs, $menus, $buttons] = self::fromLegacy($input);
|
||||
}
|
||||
|
||||
$perms = array_merge($base, [
|
||||
'can_access_admin' => !empty($input['can_access_admin']),
|
||||
'dirs' => $dirs,
|
||||
'menus' => $menus,
|
||||
'buttons' => $buttons,
|
||||
]);
|
||||
|
||||
return self::syncLegacyFlags($perms);
|
||||
}
|
||||
|
||||
public static function syncLegacyFlags(array $perms): array
|
||||
{
|
||||
$menus = $perms['menus'] ?? [];
|
||||
$buttons = $perms['buttons'] ?? [];
|
||||
|
||||
$perms['can_manage_users'] = in_array('menu:users', $menus, true);
|
||||
$perms['can_manage_roles'] = in_array('menu:roles', $menus, true);
|
||||
$perms['can_manage_departments'] = in_array('menu:departments', $menus, true);
|
||||
$perms['can_manage_models'] = in_array('menu:models', $menus, true);
|
||||
$perms['can_manage_settings'] = in_array('menu:settings', $menus, true);
|
||||
$perms['can_manage_memberships'] = in_array('menu:memberships', $menus, true);
|
||||
$perms['can_manage_permissions'] = in_array('menu:permissions', $menus, true);
|
||||
$perms['can_view_all_conversations'] = in_array('btn:conv:view_all', $buttons, true);
|
||||
$perms['can_view_subordinate_conversations'] = in_array('btn:conv:view_subordinate', $buttons, true);
|
||||
|
||||
if (in_array('menu:conversations', $menus, true)
|
||||
&& empty($perms['can_view_all_conversations'])
|
||||
&& empty($perms['can_view_subordinate_conversations'])) {
|
||||
$perms['can_view_subordinate_conversations'] = true;
|
||||
if (!in_array('btn:conv:view_subordinate', $buttons, true)) {
|
||||
$perms['buttons'][] = 'btn:conv:view_subordinate';
|
||||
}
|
||||
}
|
||||
|
||||
return $perms;
|
||||
}
|
||||
|
||||
private static function fromLegacy(array $input): array
|
||||
{
|
||||
$dirs = [];
|
||||
$menus = [];
|
||||
$buttons = [];
|
||||
|
||||
$map = [
|
||||
'can_manage_users' => ['dir:org', 'menu:users', ['btn:user:create', 'btn:user:edit', 'btn:user:reset_password', 'btn:user:delete']],
|
||||
'can_manage_departments' => ['dir:org', 'menu:departments', ['btn:dept:create', 'btn:dept:edit', 'btn:dept:delete']],
|
||||
'can_manage_roles' => ['dir:org', 'menu:roles', ['btn:role:create', 'btn:role:edit', 'btn:role:delete']],
|
||||
'can_manage_memberships' => ['dir:business', 'menu:memberships', ['btn:membership:create', 'btn:membership:edit', 'btn:membership:delete']],
|
||||
'can_manage_models' => ['dir:system', 'menu:models', ['btn:model:create', 'btn:model:edit', 'btn:model:delete', 'btn:model:test']],
|
||||
'can_manage_settings' => ['dir:system', 'menu:settings', ['btn:settings:save']],
|
||||
'can_manage_permissions' => ['dir:system', 'menu:permissions', ['btn:perm:create', 'btn:perm:edit', 'btn:perm:delete']],
|
||||
];
|
||||
|
||||
foreach ($map as $key => [$dir, $menu, $btns]) {
|
||||
if (!empty($input[$key])) {
|
||||
$dirs[] = $dir;
|
||||
$menus[] = $menu;
|
||||
$buttons = array_merge($buttons, $btns);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($input['can_view_all_conversations']) || !empty($input['can_view_subordinate_conversations'])) {
|
||||
$dirs[] = 'dir:business';
|
||||
$menus[] = 'menu:conversations';
|
||||
if (!empty($input['can_view_all_conversations'])) {
|
||||
$buttons[] = 'btn:conv:view_all';
|
||||
}
|
||||
if (!empty($input['can_view_subordinate_conversations'])) {
|
||||
$buttons[] = 'btn:conv:view_subordinate';
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($input['can_access_admin'])) {
|
||||
$dirs[] = 'dir:overview';
|
||||
$menus[] = 'menu:dashboard';
|
||||
}
|
||||
|
||||
return [
|
||||
array_values(array_unique($dirs)),
|
||||
array_values(array_unique($menus)),
|
||||
array_values(array_unique($buttons)),
|
||||
];
|
||||
}
|
||||
|
||||
public static function hasCode(array $perms, string $code): bool
|
||||
{
|
||||
if ($code === 'can_access_admin') {
|
||||
return !empty($perms['can_access_admin']);
|
||||
}
|
||||
if (str_starts_with($code, 'dir:')) {
|
||||
return in_array($code, $perms['dirs'] ?? [], true);
|
||||
}
|
||||
if (str_starts_with($code, 'menu:')) {
|
||||
return in_array($code, $perms['menus'] ?? [], true);
|
||||
}
|
||||
if (str_starts_with($code, 'btn:')) {
|
||||
return in_array($code, $perms['buttons'] ?? [], true);
|
||||
}
|
||||
return !empty($perms[$code]);
|
||||
}
|
||||
|
||||
public static function menuMeta(): array
|
||||
{
|
||||
$items = [];
|
||||
foreach (self::tree() as $dir) {
|
||||
foreach ($dir['children'] ?? [] as $menu) {
|
||||
$items[] = [
|
||||
'id' => $menu['id'] ?? null,
|
||||
'code' => $menu['code'],
|
||||
'name' => $menu['name'],
|
||||
'path' => $menu['path'] ?? '',
|
||||
'icon' => $menu['icon'] ?? '',
|
||||
'dir' => $dir['code'],
|
||||
'dirName' => $dir['name'],
|
||||
];
|
||||
}
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use app\model\UserDailyStat;
|
||||
use think\exception\HttpResponseException;
|
||||
|
||||
class PermissionService
|
||||
{
|
||||
public static function checkDailyLimit(array $user): void
|
||||
{
|
||||
$today = date('Y-m-d');
|
||||
$stats = UserDailyStat::where('user_id', $user['id'])
|
||||
->where('stat_date', $today)
|
||||
->find();
|
||||
|
||||
$count = (int) ($stats->message_count ?? 0);
|
||||
if ($count >= (int) $user['max_messages_per_day']) {
|
||||
self::abort('今日消息数量已达上限', 429);
|
||||
}
|
||||
}
|
||||
|
||||
public static function incrementDailyCount(int $userId): void
|
||||
{
|
||||
$today = date('Y-m-d');
|
||||
$stats = UserDailyStat::where('user_id', $userId)
|
||||
->where('stat_date', $today)
|
||||
->find();
|
||||
|
||||
if ($stats) {
|
||||
$stats->inc('message_count')->save();
|
||||
} else {
|
||||
UserDailyStat::create([
|
||||
'user_id' => $userId,
|
||||
'stat_date' => $today,
|
||||
'message_count' => 1,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public static function checkConversationLimit(array $user): void
|
||||
{
|
||||
$count = \app\model\Conversation::where('user_id', $user['id'])
|
||||
->whereNull('deleted_at')
|
||||
->count();
|
||||
|
||||
if ($count >= (int) $user['max_conversations']) {
|
||||
self::abort('会话数量已达上限', 429);
|
||||
}
|
||||
}
|
||||
|
||||
public static function canUpload(array $user, string $type): bool
|
||||
{
|
||||
if (!empty($user['is_guest']) && $type === 'image') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$permissions = $user['membership_permissions'] ?? [];
|
||||
$map = [
|
||||
'image' => ['upload_image', 'can_upload_image'],
|
||||
'video' => ['upload_video', 'can_upload_video'],
|
||||
'document' => ['upload_file', 'can_upload_file'],
|
||||
'audio' => ['voice', 'can_use_voice'],
|
||||
];
|
||||
|
||||
if (!isset($map[$type])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
[$featureKey, $permKey] = $map[$type];
|
||||
if (!SettingsService::isFeatureEnabled($featureKey)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !empty($permissions[$permKey]);
|
||||
}
|
||||
|
||||
public static function getMaxUploadSizeMb(array $user): int
|
||||
{
|
||||
return min((int) $user['max_upload_size_mb'], (int) config('upload.max_size_mb'));
|
||||
}
|
||||
|
||||
private static function abort(string $message, int $httpCode = 400): void
|
||||
{
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => $message,
|
||||
'data' => null,
|
||||
], $httpCode));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use app\model\SystemSetting;
|
||||
|
||||
class SettingsService
|
||||
{
|
||||
public static function get(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$row = SystemSetting::where('setting_key', $key)->find();
|
||||
if (!$row) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
$decoded = json_decode($row->setting_value, true);
|
||||
return json_last_error() === JSON_ERROR_NONE ? $decoded : $row->setting_value;
|
||||
}
|
||||
|
||||
public static function set(string $key, mixed $value): void
|
||||
{
|
||||
$stored = is_array($value) || is_object($value)
|
||||
? json_encode($value, JSON_UNESCAPED_UNICODE)
|
||||
: (string) $value;
|
||||
|
||||
$setting = SystemSetting::where('setting_key', $key)->find();
|
||||
if ($setting) {
|
||||
$setting->save(['setting_value' => $stored]);
|
||||
} else {
|
||||
SystemSetting::create([
|
||||
'setting_key' => $key,
|
||||
'setting_value' => $stored,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public static function getFeatures(): array
|
||||
{
|
||||
return self::get('features', [
|
||||
'markdown' => true,
|
||||
'image' => true,
|
||||
'video' => true,
|
||||
'voice' => true,
|
||||
'document' => true,
|
||||
'emoji' => true,
|
||||
'upload_image' => true,
|
||||
'upload_video' => true,
|
||||
'upload_file' => true,
|
||||
'paste_image' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
public static function isFeatureEnabled(string $feature): bool
|
||||
{
|
||||
$features = self::getFeatures();
|
||||
return !empty($features[$feature]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace app\service;
|
||||
|
||||
use app\model\Role;
|
||||
use app\model\User;
|
||||
use app\service\PermissionCatalog;
|
||||
|
||||
class UserContextService
|
||||
{
|
||||
public static function formatAuthUser(User $user): array
|
||||
{
|
||||
$user = User::with(['membership', 'roleModel', 'department'])->find($user->id);
|
||||
if (!$user) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$level = $user->membership;
|
||||
$role = $user->roleModel;
|
||||
$department = $user->department;
|
||||
|
||||
$permissions = PermissionCatalog::normalize($role?->permissions ?? []);
|
||||
|
||||
if (($user->role ?? '') === 'admin' && (!$role || ($role->slug ?? '') === 'super_admin')) {
|
||||
$permissions = PermissionCatalog::fullPermissions();
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $user->id,
|
||||
'username' => $user->username,
|
||||
'email' => $user->email,
|
||||
'nickname' => $user->nickname,
|
||||
'avatar' => $user->avatar,
|
||||
'is_guest' => str_starts_with($user->username, 'guest_'),
|
||||
'role' => $user->role,
|
||||
'role_id' => $user->role_id,
|
||||
'role_slug' => $role?->slug,
|
||||
'role_name' => $role?->name,
|
||||
'role_permissions' => $permissions,
|
||||
'department_id' => $user->department_id,
|
||||
'department_name' => $department?->name,
|
||||
'status' => $user->status,
|
||||
'membership_level_id' => $user->membership_level_id,
|
||||
'membership_name' => $level?->name,
|
||||
'membership_slug' => $level?->slug,
|
||||
'max_conversations' => $level?->max_conversations ?? 20,
|
||||
'max_messages_per_day' => $level?->max_messages_per_day ?? 50,
|
||||
'max_upload_size_mb' => $level?->max_upload_size_mb ?? 5,
|
||||
'membership_permissions' => $level?->permissions ?? [],
|
||||
];
|
||||
}
|
||||
|
||||
public static function formatPublicUser(int $userId): array
|
||||
{
|
||||
$user = User::with(['membership', 'roleModel', 'department'])->find($userId);
|
||||
if (!$user) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$data = self::formatAuthUser($user);
|
||||
unset($data['status']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user