92 lines
2.5 KiB
PHP
92 lines
2.5 KiB
PHP
<?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));
|
|
}
|
|
}
|