更新
This commit is contained in:
@@ -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,148 @@
|
||||
<?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 streamChat(AiModel $model, array $messages, callable $onChunk): void
|
||||
{
|
||||
$url = rtrim($model->api_base_url, '/') . '/chat/completions';
|
||||
$payload = [
|
||||
'model' => $model->model_id,
|
||||
'messages' => $messages,
|
||||
'stream' => true,
|
||||
'max_tokens' => (int) $model->max_tokens,
|
||||
'temperature' => (float) $model->temperature,
|
||||
];
|
||||
|
||||
$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_WRITEFUNCTION => function ($ch, $data) use ($onChunk) {
|
||||
$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) {
|
||||
$onChunk($json);
|
||||
}
|
||||
}
|
||||
}
|
||||
return strlen($data);
|
||||
},
|
||||
CURLOPT_TIMEOUT => 120,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
$result = curl_exec($ch);
|
||||
if ($result === false) {
|
||||
$error = curl_error($ch);
|
||||
curl_close($ch);
|
||||
self::sseEvent('error', ['message' => 'AI 请求失败: ' . $error]);
|
||||
return;
|
||||
}
|
||||
curl_close($ch);
|
||||
}
|
||||
|
||||
public static function chat(AiModel $model, array $messages): array
|
||||
{
|
||||
$url = rtrim($model->api_base_url, '/') . '/chat/completions';
|
||||
$payload = [
|
||||
'model' => $model->model_id,
|
||||
'messages' => $messages,
|
||||
'stream' => false,
|
||||
'max_tokens' => (int) $model->max_tokens,
|
||||
'temperature' => (float) $model->temperature,
|
||||
];
|
||||
|
||||
$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_SSL_VERIFYPEER => false,
|
||||
]);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($httpCode !== 200) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => 'AI 请求失败: HTTP ' . $httpCode,
|
||||
'data' => null,
|
||||
], 502));
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
if (!$data) {
|
||||
throw new HttpResponseException(json([
|
||||
'code' => 1,
|
||||
'message' => 'AI 响应解析失败',
|
||||
'data' => null,
|
||||
], 502));
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public static function sseHeaders(): void
|
||||
{
|
||||
header('Content-Type: text/event-stream');
|
||||
header('Cache-Control: no-cache');
|
||||
header('Connection: keep-alive');
|
||||
header('X-Accel-Buffering: no');
|
||||
}
|
||||
|
||||
public static function sseEvent(string $event, mixed $data): void
|
||||
{
|
||||
echo "event: {$event}\n";
|
||||
echo 'data: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
|
||||
if (ob_get_level() > 0) {
|
||||
ob_flush();
|
||||
}
|
||||
flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?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
|
||||
{
|
||||
$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]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user