feat: OCR图片搜索 + 图片编辑器 + Token管理
新增功能: - OCR图片内容搜索 (Tesseract + 中文支持) - 图片编辑器 (裁剪/旋转/亮度/对比度/饱和度/模糊) - 独立Token管理页面 Bug修复: - 修复图片显示和交互问题 - 修复相册计数不准确 - 修复搜索过滤逻辑 详细变更见 CHANGELOG.md
This commit is contained in:
commit
d40381cd01
14 files changed
+2973
No files matched your search
+122
@@ -0,0 +1,122 @@
|
||||
# Lsky Pro 自定义版更新日志
|
||||
|
||||
## v1.0.0 (2026-10-22)
|
||||
|
||||
### ✨ 新功能
|
||||
|
||||
#### 1. OCR 图片内容搜索
|
||||
- 新增 `OcrService` 服务,集成 Tesseract OCR 引擎
|
||||
- 支持中文简体/繁体 + 英文识别
|
||||
- 上传图片时自动识别文字内容并存储到数据库
|
||||
- 搜索功能同时匹配文件名和图片内 OCR 文字
|
||||
- 新增数据库字段:`images.ocr_text`
|
||||
|
||||
#### 2. 图片编辑功能
|
||||
- 新增图片编辑器(Crop/旋转/调整)
|
||||
- 支持裁剪比例:1:1、4:3、16:9、自由
|
||||
- 支持旋转:左旋 90°、右旋 90°、水平翻转、垂直翻转
|
||||
- 支持调整:亮度、对比度、饱和度、模糊
|
||||
- 集成 Cropper.js 前端库
|
||||
- 编辑后自动保存并重新生成缩略图
|
||||
|
||||
#### 3. Token 管理页面
|
||||
- 新增独立的 Token 管理页面 `/tokens`
|
||||
- 支持创建、查看、删除 Token
|
||||
- 显示 Token 来源、IP、最后使用时间
|
||||
- 分页显示(每页 10 条)
|
||||
|
||||
### 🐛 Bug 修复
|
||||
|
||||
#### 1. 图片显示问题
|
||||
- 修复「我的图片」页面默认显示空的问题
|
||||
- 修复切换相册后图片不显示的问题
|
||||
- 修复图片无法点击、选择、查看的问题
|
||||
- 修复 DragSelect 和 Viewer.js 在动态加载后失效的问题
|
||||
|
||||
#### 2. 相册计数问题
|
||||
- 修复相册图片数量显示不准确的问题
|
||||
- 改用 `withCount('images')` 动态计数,替代过时的 `image_num` 字段
|
||||
|
||||
#### 3. API 搜索功能
|
||||
- 修复 `scopeFilter` 中 `album_id` 为空时的过滤逻辑
|
||||
- 现在未选择相册时显示所有图片
|
||||
|
||||
### 🔧 技术变更
|
||||
|
||||
#### 新增依赖
|
||||
- **Tesseract OCR** + 中文语言包(tesseract-ocr-chi-sim, tesseract-ocr-chi-tra)
|
||||
- **Cropper.js** v1.6.1(前端图片裁剪库)
|
||||
|
||||
#### 数据库变更
|
||||
- 新增迁移:`2026_07_01_191052_add_ocr_text_to_images_table`
|
||||
- `images` 表新增 `ocr_text` 字段(TEXT,可空)
|
||||
|
||||
#### 路由变更
|
||||
- 新增:`PUT /user/images/{id}/edit` — 图片编辑保存
|
||||
- 新增:`GET/POST /tokens` — Token 管理页面
|
||||
|
||||
#### 控制器变更
|
||||
- `User/ImageController` — 新增 `edit()` 方法
|
||||
- `User/AlbumController` — 改用 `withCount('images')` 动态计数
|
||||
- `User/TokenController` — 新增 Token 管理控制器
|
||||
- `Api/V1/AlbumController` — 改用 `withCount('images')` 动态计数
|
||||
|
||||
#### 模型变更
|
||||
- `Image` — `scopeFilter` 移除 `whereNull('album_id')` 默认过滤
|
||||
- `Image` — `fill` 数组新增 `ocr_text` 字段
|
||||
- `Album` — 移除静态 `image_num` 依赖,改用动态计数
|
||||
|
||||
#### 视图变更
|
||||
- `user/images.blade.php` — 新增图片编辑器、修复交互问题
|
||||
- `user/tokens.blade.php` — 新增 Token 管理页面
|
||||
|
||||
---
|
||||
|
||||
## 部署说明
|
||||
|
||||
### 1. 安装 Tesseract OCR
|
||||
```bash
|
||||
docker exec lsky-pro apt-get update
|
||||
docker exec lsky-pro apt-get install -y tesseract-ocr tesseract-ocr-chi-sim tesseract-ocr-chi-tra
|
||||
```
|
||||
|
||||
### 2. 迁移数据库
|
||||
```bash
|
||||
docker exec lsky-pro php artisan migrate
|
||||
```
|
||||
|
||||
### 3. 清除缓存
|
||||
```bash
|
||||
docker exec lsky-pro php artisan cache:clear
|
||||
docker exec lsky-pro php artisan view:clear
|
||||
docker exec lsky-pro php artisan route:clear
|
||||
```
|
||||
|
||||
### 4. 批量识别已有图片(可选)
|
||||
```bash
|
||||
docker exec lsky-pro php artisan tinker
|
||||
>>> $service = new App\Services\OcrService();
|
||||
>>> $images = App\Models\Image::whereNull('ocr_text')->get();
|
||||
>>> foreach ($images as $img) { $service->processImage($img); echo '.'; }
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 文件清单
|
||||
|
||||
### 新增文件
|
||||
- `app/Services/OcrService.php` — OCR 服务
|
||||
- `app/Http/Controllers/User/TokenController.php` — Token 控制器
|
||||
- `resources/views/user/tokens.blade.php` — Token 管理页面
|
||||
- `database/migrations/2026_07_01_191052_add_ocr_text_to_images_table.php` — 数据库迁移
|
||||
- `public/js/cropper/cropper.min.js` — Cropper.js 库
|
||||
- `public/js/cropper/cropper.min.css` — Cropper.js 样式
|
||||
|
||||
### 修改文件
|
||||
- `app/Models/Image.php` — OCR 搜索支持
|
||||
- `app/Http/Controllers/User/ImageController.php` — 图片编辑功能
|
||||
- `app/Http/Controllers/User/AlbumController.php` — 动态相册计数
|
||||
- `app/Http/Controllers/Api/V1/AlbumController.php` — 动态相册计数
|
||||
- `app/Services/ImageService.php` — OCR 集成
|
||||
- `resources/views/user/images.blade.php` — 编辑器 UI + 交互修复
|
||||
- `routes/web.php` — 新增路由
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\AlbumRequest;
|
||||
use App\Models\Album;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AlbumController extends Controller
|
||||
{
|
||||
public function albums(): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
$albums = $user->albums()->withCount('images')->latest()->paginate(40);
|
||||
$albums->getCollection()->each(function (Album $album) {
|
||||
$album->image_num = $album->images_count;
|
||||
$album->setVisible(['id', 'name', 'intro', 'image_num']);
|
||||
});
|
||||
return $this->success('success', compact('albums'));
|
||||
}
|
||||
|
||||
public function create(AlbumRequest $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
DB::transaction(function () use ($user, $request) {
|
||||
$user->albums()->create(array_filter($request->validated()));
|
||||
$user->album_num = $user->albums()->count();
|
||||
$user->save();
|
||||
});
|
||||
|
||||
return $this->success('创建成功');
|
||||
}
|
||||
|
||||
public function update(AlbumRequest $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
$album = $user->albums()->find($request->route('id'));
|
||||
if (is_null($album)) {
|
||||
return $this->fail('不存在的相册');
|
||||
}
|
||||
$album->update(array_filter($request->validated()));
|
||||
return $this->success('修改成功');
|
||||
}
|
||||
|
||||
public function delete(Request $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
/** @var Album|null $album */
|
||||
$album = $user->albums()->find($request->route('id'));
|
||||
if (is_null($album)) {
|
||||
return $this->fail('不存在的相册');
|
||||
}
|
||||
DB::transaction(function () use ($user, $album) {
|
||||
$album->images()->update(['album_id' => null]);
|
||||
$album->delete();
|
||||
$user->album_num = $user->albums()->count();
|
||||
$user->save();
|
||||
});
|
||||
return $this->success('删除成功');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Enums\ImagePermission;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\ImageRenameRequest;
|
||||
use App\Models\Album;
|
||||
use App\Models\Image;
|
||||
use App\Models\User;
|
||||
use App\Services\UserService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ImageController extends Controller
|
||||
{
|
||||
public function index(): View
|
||||
{
|
||||
return view('user.images');
|
||||
}
|
||||
|
||||
public function images(Request $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
|
||||
$images = $user->images()->filter($request)->with('group', 'strategy')->paginate(40);
|
||||
$images->getCollection()->each(function (Image $image) {
|
||||
// 图片宽高过小会导致前端排版异常
|
||||
$image->width = max($image->width, 200);
|
||||
$image->height = max($image->height, 200);
|
||||
|
||||
$image->human_date = $image->created_at->diffForHumans();
|
||||
$image->date = $image->created_at->format('Y-m-d H:i:s');
|
||||
$image->append(['url', 'thumb_url', 'filename', 'links'])->setVisible([
|
||||
'id', 'filename', 'url', 'thumb_url', 'human_date', 'date', 'size', 'width', 'height', 'links'
|
||||
]);
|
||||
});
|
||||
return $this->success('success', compact('images'));
|
||||
}
|
||||
|
||||
public function image(Request $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
/** @var Image $image */
|
||||
if (!$image = $user->images()->find($request->route('id'))) {
|
||||
return $this->fail('未找到该图片');
|
||||
}
|
||||
$image->strategy?->setVisible(['name']);
|
||||
$image->album?->setVisible(['name']);
|
||||
$image->append(['url', 'thumb_url', 'filename', 'links'])->setVisible([
|
||||
'id', 'filename', 'origin_name', 'url', 'thumb_url', 'width', 'height', 'size', 'mimetype', 'md5', 'sha1',
|
||||
'permission', 'strategy', 'album', 'uploaded_ip', 'links', 'created_at'
|
||||
]);
|
||||
return $this->success('success', compact('image'));
|
||||
}
|
||||
|
||||
public function permission(Request $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
$permission = $request->input('permission');
|
||||
$permissions = ['public' => ImagePermission::Public, 'private' => ImagePermission::Private];
|
||||
if (!in_array($permission, array_keys($permissions))) {
|
||||
return $this->fail('设置失败');
|
||||
}
|
||||
$user->images()->whereIn('id', (array) $request->input('ids'))->update([
|
||||
'permission' => $permissions[$permission],
|
||||
]);
|
||||
return $this->success('设置成功');
|
||||
}
|
||||
|
||||
public function rename(ImageRenameRequest $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
/** @var Image $image */
|
||||
if ($image = $user->images()->find($request->input('id'))) {
|
||||
$image->alias_name = $request->input('name');
|
||||
$image->save();
|
||||
}
|
||||
|
||||
return $this->success('重命名成功', $image->only('id', 'filename'));
|
||||
}
|
||||
|
||||
public function movement(Request $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
DB::transaction(function () use ($user, $request) {
|
||||
/** @var null|Album $album */
|
||||
$album = $user->albums()->find((int) $request->input('id'));
|
||||
$user->images()->whereIn('id', $request->input('selected'))->update([
|
||||
'album_id' => $album->id ?? null,
|
||||
]);
|
||||
if ($album) {
|
||||
$album->image_num = $album->images()->count();
|
||||
$album->save();
|
||||
}
|
||||
if ($albumId = (int) $request->input('album_id')) {
|
||||
/** @var Album $originAlbum */
|
||||
$originAlbum = $user->albums()->find($albumId);
|
||||
$originAlbum->image_num = $originAlbum->images()->count();
|
||||
$originAlbum->save();
|
||||
}
|
||||
});
|
||||
return $this->success('移动成功');
|
||||
}
|
||||
|
||||
public function edit(Request $request, string $id): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
/** @var Image|null $image */
|
||||
$image = $user->images()->find($id);
|
||||
if (is_null($image)) {
|
||||
return $this->fail('图片不存在');
|
||||
}
|
||||
if (!$request->hasFile('image')) {
|
||||
return $this->fail('请选择要上传的图片');
|
||||
}
|
||||
$file = $request->file('image');
|
||||
if (!$file->isValid()) {
|
||||
return $this->fail('图片上传失败');
|
||||
}
|
||||
try {
|
||||
// Read the uploaded image
|
||||
$resource = imagecreatefromstring(file_get_contents($file->getRealPath()));
|
||||
if (!$resource) {
|
||||
return $this->fail('无法读取图片');
|
||||
}
|
||||
// Get image dimensions
|
||||
$width = imagesx($resource);
|
||||
$height = imagesy($resource);
|
||||
// Build full path from strategy root + pathname
|
||||
$root = $image->strategy?->configs?->get('root', '');
|
||||
$fullPath = rtrim($root, '/') . '/' . ltrim($image->pathname, '/');
|
||||
$pathDir = dirname($fullPath);
|
||||
if (!is_dir($pathDir)) {
|
||||
mkdir($pathDir, 0755, true);
|
||||
}
|
||||
// Determine output format
|
||||
$extension = strtolower(pathinfo($fullPath, PATHINFO_EXTENSION));
|
||||
if (in_array($extension, ['jpg', 'jpeg'])) {
|
||||
imagejpeg($resource, $fullPath, 95);
|
||||
} elseif ($extension === 'png') {
|
||||
imagepng($resource, $fullPath);
|
||||
} else {
|
||||
// Default to JPEG
|
||||
imagejpeg($resource, $fullPath, 95);
|
||||
}
|
||||
imagedestroy($resource);
|
||||
// Update image dimensions in database
|
||||
$image->update([
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'size' => filesize($fullPath),
|
||||
]);
|
||||
// Regenerate thumbnail
|
||||
try {
|
||||
$imageService = new \App\Services\ImageService();
|
||||
$imageService->makeThumbnail($image, $fullPath, 400, true);
|
||||
} catch (\Exception $e) {
|
||||
// Thumbnail generation is not critical
|
||||
}
|
||||
return $this->success('编辑保存成功');
|
||||
} catch (\Exception $e) {
|
||||
return $this->fail('编辑失败: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function delete(Request $request): Response
|
||||
{
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
(new UserService())->deleteImages($request->all() ?: [], $user);
|
||||
return $this->success('删除成功');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class TokenController extends Controller
|
||||
{
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$user = Auth::user();
|
||||
$tokens = $user->tokens()
|
||||
->select('id', 'name', 'ip', 'plain_token', 'created_at', 'last_used_at')
|
||||
->orderByDesc('created_at')
|
||||
->paginate(10);
|
||||
$totalTokens = $user->tokens()->count();
|
||||
|
||||
return view('user.tokens', compact('tokens', 'totalTokens'));
|
||||
}
|
||||
|
||||
public function store(Request $request): Response
|
||||
{
|
||||
$request->validate([
|
||||
'name' => 'required|string|max:255',
|
||||
]);
|
||||
|
||||
$user = Auth::user();
|
||||
$tokenObj = $user->createToken($request->input('name'));
|
||||
$tokenObj->accessToken->ip = $request->ip();
|
||||
$tokenObj->accessToken->plain_token = $tokenObj->plainTextToken;
|
||||
$tokenObj->accessToken->save();
|
||||
|
||||
return $this->success('Token 创建成功', [
|
||||
'token' => $tokenObj->plainTextToken,
|
||||
'name' => $request->input('name'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request, string $id): Response
|
||||
{
|
||||
$user = Auth::user();
|
||||
if ($token = $user->tokens()->find($id)) {
|
||||
$token->delete();
|
||||
return $this->success('Token 已删除');
|
||||
}
|
||||
return $this->error('Token 不存在');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property int $user_id
|
||||
* @property string $name
|
||||
* @property string $intro
|
||||
* @property int $image_num
|
||||
* @property-read User $user
|
||||
* @property-read Collection $images
|
||||
*/
|
||||
class Album extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'intro',
|
||||
'image_num'
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'user_id',
|
||||
];
|
||||
|
||||
protected $attributes = [
|
||||
'intro' => '',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'image_num' => 'integer',
|
||||
];
|
||||
|
||||
public function scopeFilter(Builder $builder, Request $request)
|
||||
{
|
||||
return $builder->when($request->query('order') ?: 'newest', function (Builder $builder, $order) {
|
||||
switch ($order) {
|
||||
case 'earliest':
|
||||
$builder->orderBy('created_at');
|
||||
break;
|
||||
case 'most':
|
||||
$builder->orderByDesc('image_num');
|
||||
break;
|
||||
case 'least':
|
||||
$builder->orderBy('image_num');
|
||||
break;
|
||||
default:
|
||||
$builder->latest();
|
||||
}
|
||||
})->when($request->query('keyword'), function (Builder $builder, $keyword) {
|
||||
$builder->where('name', 'like', "%{$keyword}%")->orWhere('intro', 'like', "%{$keyword}%");
|
||||
});
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id', 'id');
|
||||
}
|
||||
|
||||
public function images(): HasMany
|
||||
{
|
||||
return $this->hasMany(Image::class, 'album_id', 'id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\GroupConfigKey;
|
||||
use App\Enums\ImagePermission;
|
||||
use App\Services\ImageService;
|
||||
use App\Utils;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
use League\Flysystem\Filesystem;
|
||||
|
||||
/**
|
||||
* @property int $id
|
||||
* @property int $user_id
|
||||
* @property int $album_id
|
||||
* @property int $group_id
|
||||
* @property int $strategy_id
|
||||
* @property string $key
|
||||
* @property string $path
|
||||
* @property string $name
|
||||
* @property string $pathname
|
||||
* @property string $origin_name
|
||||
* @property string $alias_name
|
||||
* @property string $filename
|
||||
* @property float $size
|
||||
* @property string $mimetype
|
||||
* @property string $extension
|
||||
* @property string $md5
|
||||
* @property string $sha1
|
||||
* @property integer $width
|
||||
* @property integer $height
|
||||
* @property string $url
|
||||
* @property string $thumb_url
|
||||
* @property Collection $links
|
||||
* @property int $permission
|
||||
* @property boolean $is_unhealthy
|
||||
* @property string $uploaded_ip
|
||||
* @property Carbon $updated_at
|
||||
* @property Carbon $created_at
|
||||
* @property-read User $user
|
||||
* @property-read Album $album
|
||||
* @property-read Group $group
|
||||
* @property-read Strategy $strategy
|
||||
*/
|
||||
class Image extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'key',
|
||||
'path',
|
||||
'name',
|
||||
'origin_name',
|
||||
'alias_name',
|
||||
'size',
|
||||
'mimetype',
|
||||
'extension',
|
||||
'md5',
|
||||
'sha1',
|
||||
'width',
|
||||
'height',
|
||||
'permission',
|
||||
'is_unhealthy',
|
||||
'uploaded_ip',
|
||||
'ocr_text',
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'user_id',
|
||||
'album_id',
|
||||
'group_id',
|
||||
'strategy_id',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'album_id' => 'integer',
|
||||
'group_id' => 'integer',
|
||||
'strategy_id' => 'integer',
|
||||
'width' => 'integer',
|
||||
'height' => 'integer',
|
||||
'size' => 'float',
|
||||
'is_unhealthy' => 'bool',
|
||||
'permission' => 'integer',
|
||||
];
|
||||
|
||||
protected ?Filesystem $filesystem = null;
|
||||
|
||||
protected static function booted()
|
||||
{
|
||||
static::creating(function (self $image) {
|
||||
$image->key = $image->generateKey();
|
||||
});
|
||||
|
||||
static::deleting(function (self $image) {
|
||||
// TODO 检测是否启用了队列,放置队列中异步删除
|
||||
// 在当前图片所属的策略中是否存在其他相同 md5 和 sha1 的记录,没有则可以删除物理文件
|
||||
if (!static::query()
|
||||
->where('strategy_id', $image->strategy_id)
|
||||
->where('id', '<>', $image->id)
|
||||
->where('md5', $image->md5)
|
||||
->where('sha1', $image->sha1)
|
||||
->exists()
|
||||
) {
|
||||
// 删除本地缓存文件
|
||||
try {
|
||||
// 删除物理文件
|
||||
$image->filesystem()->delete($image->pathname);
|
||||
@unlink(public_path($image->getThumbnailPathname()));
|
||||
// 删除缓存
|
||||
Cache::forget("image_{$image->key}");
|
||||
} catch (\Throwable $e) {
|
||||
Utils::e($e, '删除物理文件时发生异常');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function scopeFilter(Builder $builder, Request $request)
|
||||
{
|
||||
return $builder->when($request->query('order') ?: 'newest', function (Builder $builder, $order) {
|
||||
switch ($order) {
|
||||
case 'earliest':
|
||||
$builder->orderBy('created_at');
|
||||
break;
|
||||
case 'utmost':
|
||||
$builder->orderByDesc('size');
|
||||
break;
|
||||
case 'least':
|
||||
$builder->orderBy('size');
|
||||
break;
|
||||
default:
|
||||
$builder->latest();
|
||||
}
|
||||
})->when($request->query('permission') ?: 'all', function (Builder $builder, $permission) {
|
||||
switch ($permission) {
|
||||
case 'public':
|
||||
$builder->where('permission', ImagePermission::Public);
|
||||
break;
|
||||
case 'private':
|
||||
$builder->where('permission', ImagePermission::Private);
|
||||
break;
|
||||
}
|
||||
})->when($request->query('keyword'), function (Builder $builder, $keyword) {
|
||||
$builder->where(function ($q) use ($keyword) {
|
||||
$q->where('origin_name', 'like', "%{$keyword}%")
|
||||
->orWhere('alias_name', 'like', "%{$keyword}%")
|
||||
->orWhere('ocr_text', 'like', "%{$keyword}%");
|
||||
});
|
||||
})->when((int) $request->query('album_id'), function (Builder $builder, $albumId) {
|
||||
$builder->where('album_id', $albumId);
|
||||
});
|
||||
}
|
||||
|
||||
public function filename(): Attribute
|
||||
{
|
||||
return new Attribute(fn() => $this->alias_name ?: $this->origin_name);
|
||||
}
|
||||
|
||||
public function pathname(): Attribute
|
||||
{
|
||||
$path = $this->path ? "{$this->path}/" : '';
|
||||
return new Attribute(fn() => "{$path}{$this->name}");
|
||||
}
|
||||
|
||||
public function url(): Attribute
|
||||
{
|
||||
return new Attribute(function () {
|
||||
// 是否启用原图保护功能
|
||||
if ($this->group?->configs->get(GroupConfigKey::IsEnableOriginalProtection)) {
|
||||
$url = asset("{$this->key}.{$this->extension}");
|
||||
} else {
|
||||
$url = rtrim($this->strategy?->configs->get('url'), '/').'/'.ltrim($this->pathname, '/');
|
||||
}
|
||||
|
||||
// 拼接图片 url
|
||||
return $url.($this->strategy?->configs->get('queries') ?: '');
|
||||
});
|
||||
}
|
||||
|
||||
public function thumbUrl(): Attribute
|
||||
{
|
||||
return new Attribute(function () {
|
||||
$pathname = $this->getThumbnailPathname();
|
||||
|
||||
// 没有缩略图则返回原图
|
||||
if (! file_exists(public_path($pathname))) {
|
||||
return $this->url;
|
||||
}
|
||||
|
||||
return asset($pathname);
|
||||
});
|
||||
}
|
||||
|
||||
public function links(): Attribute
|
||||
{
|
||||
return new Attribute(fn() => collect([
|
||||
'url' => $this->url,
|
||||
'html' => "<img src=\"{$this->url}\" alt=\"{$this->origin_name}\" title=\"{$this->origin_name}\" />",
|
||||
'bbcode' => "[img]{$this->url}[/img]",
|
||||
'markdown' => "",
|
||||
'markdown_with_link' => "[]({$this->url})",
|
||||
'thumbnail_url' => $this->thumb_url,
|
||||
]));
|
||||
}
|
||||
|
||||
public function filesystem(): Filesystem
|
||||
{
|
||||
if (is_null($this->filesystem)) {
|
||||
$this->filesystem = new Filesystem((new ImageService())->getAdapter($this->strategy));
|
||||
}
|
||||
return $this->filesystem;
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id', 'id');
|
||||
}
|
||||
|
||||
public function album(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Album::class, 'album_id', 'id');
|
||||
}
|
||||
|
||||
public function group(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Group::class, 'group_id', 'id');
|
||||
}
|
||||
|
||||
public function strategy(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Strategy::class, 'strategy_id', 'id');
|
||||
}
|
||||
|
||||
public function getThumbnailPathname(): string
|
||||
{
|
||||
return trim(config('app.thumbnail_path'), '/')."/{$this->md5}.png";
|
||||
}
|
||||
|
||||
private function generateKey($length = 6): string
|
||||
{
|
||||
$key = Str::random($length);
|
||||
if (self::query()->where('key', $key)->exists()) {
|
||||
return $this->generateKey(++$length);
|
||||
}
|
||||
return $key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,661 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use AlibabaCloud\Client\AlibabaCloud;
|
||||
use AlibabaCloud\Green\Green;
|
||||
use App\Enums\ConfigKey;
|
||||
use App\Enums\GroupConfigKey;
|
||||
use App\Enums\ImagePermission;
|
||||
use App\Enums\Scan\AliyunOption;
|
||||
use App\Enums\Scan\NsfwJsOption;
|
||||
use App\Enums\Scan\TencentOption;
|
||||
use App\Enums\Strategy\CosOption;
|
||||
use App\Enums\Strategy\FtpOption;
|
||||
use App\Enums\Strategy\KodoOption;
|
||||
use App\Enums\Strategy\LocalOption;
|
||||
use App\Enums\Strategy\MinioOption;
|
||||
use App\Enums\Strategy\OssOption;
|
||||
use App\Enums\Strategy\S3Option;
|
||||
use App\Enums\Strategy\SftpOption;
|
||||
use App\Enums\Strategy\UssOption;
|
||||
use App\Enums\Strategy\WebDavOption;
|
||||
use App\Enums\StrategyKey;
|
||||
use App\Enums\UserConfigKey;
|
||||
use App\Enums\UserStatus;
|
||||
use App\Enums\Watermark\FontOption;
|
||||
use App\Enums\Watermark\ImageOption;
|
||||
use App\Enums\Watermark\Mode;
|
||||
use App\Exceptions\UploadException;
|
||||
use App\Models\Group;
|
||||
use App\Models\Image;
|
||||
use App\Models\Strategy;
|
||||
use App\Models\User;
|
||||
use App\Utils;
|
||||
use Aws\S3\S3Client;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use Intervention\Image\Facades\Image as InterventionImage;
|
||||
use Intervention\Image\Imagick\Font;
|
||||
use Intervention\Image\ImageManager;
|
||||
use League\Flysystem\AwsS3V3\AwsS3V3Adapter;
|
||||
use League\Flysystem\Filesystem;
|
||||
use League\Flysystem\FilesystemAdapter;
|
||||
use League\Flysystem\FilesystemException;
|
||||
use League\Flysystem\Ftp\FtpAdapter;
|
||||
use League\Flysystem\Ftp\FtpConnectionOptions;
|
||||
use League\Flysystem\Local\LocalFilesystemAdapter;
|
||||
use League\Flysystem\PhpseclibV2\SftpAdapter;
|
||||
use League\Flysystem\PhpseclibV2\SftpConnectionProvider;
|
||||
use League\Flysystem\WebDAV\WebDAVAdapter;
|
||||
use Overtrue\Flysystem\Cos\CosAdapter;
|
||||
use Overtrue\Flysystem\Qiniu\QiniuAdapter;
|
||||
use Sabre\DAV\Client;
|
||||
use TencentCloud\Common\Credential;
|
||||
use TencentCloud\Common\Profile\ClientProfile;
|
||||
use TencentCloud\Common\Profile\HttpProfile;
|
||||
use TencentCloud\Ims\V20201229\ImsClient;
|
||||
use TencentCloud\Ims\V20201229\Models\ImageModerationRequest;
|
||||
use WispX\Flysystem\Upyun\UpyunAdapter;
|
||||
use Zing\Flysystem\Oss\OssAdapter;
|
||||
use OSS\OssClient;
|
||||
|
||||
class ImageService
|
||||
{
|
||||
/**
|
||||
* @param Request $request
|
||||
* @return Image
|
||||
* @throws UploadException
|
||||
*/
|
||||
public function store(Request $request): Image
|
||||
{
|
||||
$file = $request->file('file');
|
||||
|
||||
if (Auth::guest() && !Utils::config(ConfigKey::IsAllowGuestUpload, true)) {
|
||||
throw new UploadException('管理员关闭了游客上传');
|
||||
}
|
||||
|
||||
$image = new Image();
|
||||
/** @var User|null $user */
|
||||
$user = $request->user();
|
||||
|
||||
/** @var Group $group */
|
||||
$group = ! is_null($user) ? $user->group : Group::query()->where('is_guest', true)->first();
|
||||
// 组配置
|
||||
$configs = $group->configs;
|
||||
// 储存策略
|
||||
$strategies = $group->strategies()->get();
|
||||
if ($strategies->isEmpty()) {
|
||||
throw new UploadException('没有可用的储存,请联系管理员。');
|
||||
}
|
||||
|
||||
$extension = strtolower($file->getClientOriginalExtension());
|
||||
|
||||
if (! in_array($extension, $configs->get(GroupConfigKey::AcceptedFileSuffixes))) {
|
||||
throw new UploadException('不支持的文件类型');
|
||||
}
|
||||
|
||||
if ($file->getSize() / 1024 > $configs->get(GroupConfigKey::MaximumFileSize)) {
|
||||
throw new UploadException("图片大小超出限制");
|
||||
}
|
||||
|
||||
// 图片所属组
|
||||
$image->group_id = $group->id;
|
||||
// 图片默认权限
|
||||
$image->permission = ImagePermission::Private;
|
||||
|
||||
if ($request->has('strategy_id')) {
|
||||
if (! $strategy = $strategies->find($request->input('strategy_id'))) {
|
||||
throw new UploadException('选定的策略不存在');
|
||||
}
|
||||
} else {
|
||||
// 没有指定则选择第一个策略
|
||||
$strategy = $strategies->first();
|
||||
}
|
||||
|
||||
$image->strategy_id = $strategy->id;
|
||||
|
||||
// 默认储存策略
|
||||
if (! is_null($user)) {
|
||||
if (Utils::config(ConfigKey::IsUserNeedVerify) && ! $user->email_verified_at) {
|
||||
throw new UploadException('账户未验证');
|
||||
}
|
||||
|
||||
if ($user->status !== UserStatus::Normal) {
|
||||
throw new UploadException('账号状态异常');
|
||||
}
|
||||
|
||||
if ($file->getSize() / 1024 + $user->images()->sum('size') > $user->capacity) {
|
||||
throw new UploadException('储存空间不足');
|
||||
}
|
||||
|
||||
// 图片保存至指定相册或默认相册
|
||||
if ($albumIdParam = $request->input('album_id')) {
|
||||
if ($user->albums()->where('id', $albumIdParam)->exists()) {
|
||||
$image->album_id = $albumIdParam;
|
||||
}
|
||||
} elseif ($albumId = $user->configs->get(UserConfigKey::DefaultAlbum)) {
|
||||
if ($user->albums()->where('id', $albumId)->exists()) {
|
||||
$image->album_id = $albumId;
|
||||
}
|
||||
}
|
||||
|
||||
$image->user_id = $user->id;
|
||||
// 用户设置的图片默认权限
|
||||
$image->permission = $user->configs->get(UserConfigKey::DefaultPermission, ImagePermission::Private);
|
||||
}
|
||||
|
||||
// 上传频率限制
|
||||
$this->rateLimiter($configs, $request);
|
||||
|
||||
// 图片处理,跳过 ico 于 gif
|
||||
if (! in_array($extension, ['ico', 'gif'])) {
|
||||
// 图片保存质量与格式,优先使用上传时指定的质量
|
||||
$quality = (int) $request->input('quality', $configs->get(GroupConfigKey::ImageSaveQuality, 100));
|
||||
$quality = max(1, min(100, $quality));
|
||||
$format = $configs->get(GroupConfigKey::ImageSaveFormat);
|
||||
if ($quality < 100 || $format) {
|
||||
// 获取拓展名,判断是否需要转换
|
||||
$format = $format ?: $extension;
|
||||
$filename = Str::replaceLast($extension, $format, $file->getClientOriginalName());
|
||||
$manager = new ImageManager(['driver' => 'imagick']);
|
||||
$handleImage = $manager->make($file)->save($format, $quality);
|
||||
$file = new UploadedFile($handleImage->basePath(), $filename, $handleImage->mime());
|
||||
// 重新设置拓展名
|
||||
$extension = $format;
|
||||
$handleImage->destroy();
|
||||
}
|
||||
|
||||
// 是否启用水印,覆盖原图片
|
||||
if (
|
||||
$configs->get(GroupConfigKey::IsEnableWatermark) &&
|
||||
collect($configs->get(GroupConfigKey::WatermarkConfigs))->get('mode', Mode::Overlay) == Mode::Overlay
|
||||
) {
|
||||
$watermarkImage = $this->stickWatermark($file, collect($configs->get(GroupConfigKey::WatermarkConfigs)));
|
||||
$watermarkImage->save();
|
||||
$file = new UploadedFile($watermarkImage->basePath(), $file->getClientOriginalName(), $file->getMimeType());
|
||||
$watermarkImage->destroy();
|
||||
}
|
||||
}
|
||||
|
||||
$filename = $this->replacePathname(
|
||||
$configs->get(GroupConfigKey::PathNamingRule).'/'.$configs->get(GroupConfigKey::FileNamingRule), $file,
|
||||
);
|
||||
$pathname = $filename.".{$extension}";
|
||||
|
||||
[$width, $height] = @getimagesize($file->getRealPath()) ?: [400, 400];
|
||||
|
||||
$image->fill([
|
||||
'md5' => md5_file($file->getRealPath()),
|
||||
'sha1' => sha1_file($file->getRealPath()),
|
||||
'path' => $configs->get(GroupConfigKey::PathNamingRule) ? dirname($pathname) : '',
|
||||
'name' => basename($pathname),
|
||||
'origin_name' => $file->getClientOriginalName(),
|
||||
'size' => $file->getSize() / 1024,
|
||||
'mimetype' => $file->getMimeType(),
|
||||
'extension' => strtolower($extension),
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'is_unhealthy' => false,
|
||||
'uploaded_ip' => $request->ip(),
|
||||
]);
|
||||
|
||||
$filesystem = new Filesystem($this->getAdapter($strategy));
|
||||
|
||||
// 检测该策略是否存在该图片,有则只创建记录不保存文件
|
||||
/** @var Image $existing */
|
||||
$existing = Image::query()->when($image->strategy_id, function (Builder $builder, $id) {
|
||||
$builder->where('strategy_id', $id);
|
||||
})->where('md5', $image->md5)->where('sha1', $image->sha1)->first();
|
||||
if (is_null($existing)) {
|
||||
$handle = fopen($file, 'r');
|
||||
try {
|
||||
$filesystem->writeStream($pathname, $handle);
|
||||
} catch (FilesystemException $e) {
|
||||
Utils::e($e, '保存图片时出现异常');
|
||||
throw new UploadException(config('app.debug', false) ? $e->getMessage() : '图片上传失败');
|
||||
}
|
||||
if (is_resource($handle)) @fclose($handle);
|
||||
} else {
|
||||
$image->fill($existing->only('path', 'name'));
|
||||
}
|
||||
|
||||
// 增加当前用户的图片数量和相册图片数量
|
||||
$updateNum = function ($method) use ($user, $image) {
|
||||
DB::transaction(function () use ($method, $user, $image) {
|
||||
if (! is_null($user)) {
|
||||
$user->{$method}('image_num');
|
||||
}
|
||||
if (! is_null($image->album)) {
|
||||
$image->album->{$method}('image_num');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
// 图片记录保存失败,删除物理文件
|
||||
if (! $image->save()) {
|
||||
if (is_null($existing)) $filesystem->delete($image->pathname);
|
||||
throw new \Exception('图片记录保存失败');
|
||||
}
|
||||
$updateNum('increment');
|
||||
} catch (\Throwable $e) {
|
||||
Utils::e($e, '保存图片记录时出现异常');
|
||||
throw new UploadException('图片记录保存失败');
|
||||
}
|
||||
|
||||
// 图片检测,跳过 tif、ico 以及 psd 格式
|
||||
if ($configs->get(GroupConfigKey::IsEnableScan) && ! in_array($extension, ['psd', 'ico', 'tif'])) {
|
||||
$scanConfigs = $configs->get(GroupConfigKey::ScanConfigs);
|
||||
if ($this->scan(
|
||||
driver: $scanConfigs['driver'],
|
||||
configs: collect($scanConfigs['drivers'][$scanConfigs['driver']]),
|
||||
image: $image,
|
||||
file: $file,
|
||||
)) {
|
||||
// 标记 or 删除
|
||||
if ($configs->get(GroupConfigKey::ScannedAction) === 'delete') {
|
||||
$image->delete();
|
||||
$updateNum('decrement');
|
||||
throw new UploadException('图片涉嫌违规,禁止上传。');
|
||||
} else {
|
||||
$image->is_unhealthy = true;
|
||||
$image->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 生成缩略图
|
||||
$this->makeThumbnail($image, $file);
|
||||
|
||||
// OCR: 识别图片文字(仅支持常见图片格式)
|
||||
if (in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp'])) {
|
||||
try {
|
||||
$ocrService = new OcrService();
|
||||
$ocrService->processImage($image);
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('OCR processing failed', ['image_id' => $image->id, 'error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
return $image;
|
||||
}
|
||||
|
||||
public function getAdapter(Strategy $strategy): FilesystemAdapter
|
||||
{
|
||||
$configs = $strategy->configs;
|
||||
return match ($strategy->key) {
|
||||
StrategyKey::Local => new LocalFilesystemAdapter(
|
||||
location: $configs->get(LocalOption::Root) ?: config('filesystems.disks.uploads.root')
|
||||
),
|
||||
StrategyKey::S3 => new AwsS3V3Adapter(
|
||||
client: new S3Client([
|
||||
'credentials' => [
|
||||
'key' => $configs->get(S3Option::AccessKeyId),
|
||||
'secret' => $configs->get(S3Option::SecretAccessKey)
|
||||
],
|
||||
'endpoint' => $configs->get(S3Option::Endpoint),
|
||||
'region' => $configs->get(S3Option::Region),
|
||||
'version' => '2006-03-01',
|
||||
]),
|
||||
bucket: $configs->get(S3Option::Bucket),
|
||||
),
|
||||
StrategyKey::Oss => new OssAdapter(
|
||||
client: new OssClient($configs->get(
|
||||
OssOption::AccessKeyId),
|
||||
$configs->get(OssOption::AccessKeySecret),
|
||||
$configs->get(OssOption::Endpoint),
|
||||
),
|
||||
bucket: $configs->get(OssOption::Bucket),
|
||||
),
|
||||
StrategyKey::Cos => new CosAdapter($configs->only([
|
||||
CosOption::AppId, CosOption::SecretId, CosOption::SecretKey, CosOption::Region, CosOption::Bucket,
|
||||
])->toArray()),
|
||||
StrategyKey::Kodo => new QiniuAdapter(
|
||||
accessKey: $configs->get(KodoOption::AccessKey),
|
||||
secretKey: $configs->get(KodoOption::SecretKey),
|
||||
bucket: $configs->get(KodoOption::Bucket),
|
||||
domain: $configs->get(KodoOption::Url),
|
||||
),
|
||||
StrategyKey::Uss => new UpyunAdapter(
|
||||
service: $configs->get(UssOption::Service),
|
||||
operator: $configs->get(UssOption::Operator),
|
||||
password: $configs->get(UssOption::Password),
|
||||
domain: $configs->get(UssOption::Url),
|
||||
),
|
||||
StrategyKey::Sftp => new SftpAdapter(
|
||||
connectionProvider: new SftpConnectionProvider(
|
||||
host: $configs->get(SftpOption::Host),
|
||||
username: $configs->get(SftpOption::Username),
|
||||
password: $configs->get(SftpOption::Password),
|
||||
privateKey: $configs->get(SftpOption::PrivateKey),
|
||||
passphrase: (string)$configs->get(SftpOption::Passphrase),
|
||||
port: (int)$configs->get(SftpOption::Port),
|
||||
useAgent: (bool)$configs->get(SftpOption::UseAgent)
|
||||
),
|
||||
root: $configs->get(SftpOption::Root),
|
||||
),
|
||||
StrategyKey::Ftp => new FtpAdapter(
|
||||
connectionOptions: FtpConnectionOptions::fromArray([
|
||||
'host' => $configs->get(FtpOption::Host),
|
||||
'root' => $configs->get(FtpOption::Root),
|
||||
'port' => (int)$configs->get(FtpOption::Port),
|
||||
'ssl' => (bool)$configs->get(FtpOption::Ssl),
|
||||
'username' => $configs->get(FtpOption::Username),
|
||||
'password' => $configs->get(FtpOption::Password),
|
||||
'passive' => (bool)$configs->get(FtpOption::Passive),
|
||||
'timeout' => 30,
|
||||
]),
|
||||
),
|
||||
StrategyKey::Webdav => new WebDAVAdapter(new Client([
|
||||
'baseUri' => $configs->get(WebDavOption::BaseUri),
|
||||
'userName' => $configs->get(WebDavOption::Username),
|
||||
'password' => $configs->get(WebDavOption::Password)
|
||||
])),
|
||||
StrategyKey::Minio => new AwsS3V3Adapter(
|
||||
client: new S3Client([
|
||||
'credentials' => [
|
||||
'key' => $configs->get(MinioOption::AccessKey),
|
||||
'secret' => $configs->get(MinioOption::SecretKey)
|
||||
],
|
||||
'endpoint' => $configs->get(MinioOption::Endpoint),
|
||||
'region' => $configs->get(MinioOption::Region),
|
||||
'version' => '2006-03-01',
|
||||
]),
|
||||
bucket: $configs->get(MinioOption::Bucket),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws UploadException
|
||||
*/
|
||||
protected function rateLimiter(Collection $configs, Request $request)
|
||||
{
|
||||
/** @var User|null $user */
|
||||
$user = $request->user();
|
||||
$carbon = Carbon::now();
|
||||
$array = [
|
||||
'minute' => ['key' => GroupConfigKey::LimitPerMinute, 'str' => '分钟'],
|
||||
'hours' => ['key' => GroupConfigKey::LimitPerHour, 'str' => '小时'],
|
||||
'days' => ['key' => GroupConfigKey::LimitPerDay, 'str' => '天'],
|
||||
'weeks' => ['key' => GroupConfigKey::LimitPerWeek, 'str' => '周'],
|
||||
'months' => ['key' => GroupConfigKey::LimitPerMonth, 'str' => '月'],
|
||||
];
|
||||
|
||||
foreach ($array as $key => $item) {
|
||||
$value = $configs->get($item['key'], 0);
|
||||
$count = Image::query()->whereBetween('created_at', [
|
||||
$carbon->parse("-1 {$key}"), $carbon,
|
||||
])->when(! is_null($user), function (Builder $builder) use ($user) {
|
||||
$builder->where('user_id', $user->id);
|
||||
}, function (Builder $builder) use ($request) {
|
||||
$builder->where('uploaded_ip', $request->ip())->whereNull('user_id');
|
||||
})->count();
|
||||
|
||||
if ($value && $count >= $value) {
|
||||
throw new UploadException("每{$item['str']}内你最多可以上传 {$value} 张图片");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测图片是否违规
|
||||
*
|
||||
* @param $driver
|
||||
* @param Collection $configs
|
||||
* @param Image $image
|
||||
* @param UploadedFile $file
|
||||
* @return bool true=违规
|
||||
* @throws UploadException
|
||||
*/
|
||||
public function scan($driver, Collection $configs, Image $image, UploadedFile $file): bool
|
||||
{
|
||||
$flag = false;
|
||||
try {
|
||||
if ($driver === 'tencent') {
|
||||
// 图片大小不得超过 5mb
|
||||
if ($file->getSize() >= 5242880) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cred = new Credential($configs->get(TencentOption::SecretId), $configs->get(TencentOption::SecretKey));
|
||||
$httpProfile = new HttpProfile();
|
||||
$httpProfile->setEndpoint($configs->get(TencentOption::Endpoint));
|
||||
$clientProfile = new ClientProfile();
|
||||
$clientProfile->setHttpProfile($httpProfile);
|
||||
$client = new ImsClient($cred, $configs->get(TencentOption::Region), $clientProfile);
|
||||
$req = new ImageModerationRequest();
|
||||
$params = [
|
||||
"FileContent" => base64_encode($file->getContent()),
|
||||
];
|
||||
if ($configs->get(TencentOption::BizType)) {
|
||||
$params['BizType'] = $configs->get(TencentOption::BizType);
|
||||
}
|
||||
$req->fromJsonString(json_encode($params));
|
||||
$resp = $client->ImageModeration($req);
|
||||
|
||||
if ($resp->getSuggestion() === 'Block') {
|
||||
$flag = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($driver === 'aliyun') {
|
||||
// 20 mb以内、宽高不超过 30000px
|
||||
if ($file->getSize() >= 20971520 || $image->width >= 30000 || $image->height >= 30000) {
|
||||
return false;
|
||||
}
|
||||
|
||||
AlibabaCloud::accessKeyClient(
|
||||
$configs->get(AliyunOption::AccessKeyId),
|
||||
$configs->get(AliyunOption::AccessKeySecret),
|
||||
)->regionId($configs->get(AliyunOption::RegionId))->asDefaultClient();
|
||||
$task = ['dataId' => $image->id, 'url' => $image->url];
|
||||
$response = Green::v20180509()->imageSyncScan()->body(json_encode([
|
||||
'tasks' => [$task],
|
||||
'scenes' => $configs->get(AliyunOption::Scenes),
|
||||
'bizType' => $configs->get(AliyunOption::BizType)
|
||||
]))->request();
|
||||
if (200 != $response->get('code')) {
|
||||
throw new \Exception("detect not success. code:" . $response->get('code'));
|
||||
}
|
||||
if ($result = $response->data[0] ?? null) {
|
||||
if (200 == $result->code) {
|
||||
foreach ($result->results as $item) {
|
||||
if ($item->suggestion === 'block') {
|
||||
$flag = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($driver === 'nsfwjs') {
|
||||
// 不支持 bmp 格式
|
||||
if ($image->extension === 'bmp') {
|
||||
return false;
|
||||
}
|
||||
$response = Http::timeout(180)->withOptions(['timeout' => 180])->attach(
|
||||
$configs->get(NsfwJsOption::AttrName, 'image'), $file->getContent(), $file->getClientOriginalName(),
|
||||
)->post($configs->get(NsfwJsOption::ApiUrl));
|
||||
$ratio = $configs->get(NsfwJsOption::Threshold, 60) / 100;
|
||||
|
||||
if ($response->json('hentai', 0.00) >= $ratio) {
|
||||
$flag = true;
|
||||
}
|
||||
|
||||
if ($response->json('porn', 0.00) >= $ratio) {
|
||||
$flag = true;
|
||||
}
|
||||
|
||||
if ($response->json('sexy', 0.00) >= $ratio) {
|
||||
$flag = true;
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
throw new UploadException('Scan: '.$e->getMessage());
|
||||
}
|
||||
|
||||
return $flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合成水印
|
||||
*
|
||||
* @param mixed $image
|
||||
* @param Collection $configs
|
||||
* @return \Intervention\Image\Image
|
||||
*/
|
||||
public function stickWatermark(mixed $image, Collection $configs): \Intervention\Image\Image
|
||||
{
|
||||
$driver = $configs->get('driver');
|
||||
$options = collect($configs->get("drivers")[$driver]);
|
||||
$manager = new ImageManager(['driver' => 'imagick']);
|
||||
$image = $manager->make($image);
|
||||
|
||||
$position = $options->get(FontOption::Position, 'bottom-right');
|
||||
$offsetX = (int) $options->get(FontOption::X, 10);
|
||||
$offsetY = (int) $options->get(FontOption::Y, 10);
|
||||
|
||||
$watermark = $this->getWatermark($driver, $options);
|
||||
|
||||
// 原图宽高
|
||||
$imageWidth = $image->width();
|
||||
$imageHeight = $image->height();
|
||||
|
||||
// 水印画布宽高
|
||||
$watermarkWidth = $watermark->width();
|
||||
$watermarkHeight = $watermark->height();
|
||||
|
||||
if ($position === 'tiled') {
|
||||
// 平铺水印
|
||||
for ($x = 0; $x < $imageWidth; $x++) {
|
||||
for ($y = 0; $y < $imageHeight; $y++) {
|
||||
$image->insert($watermark, '', $x, $y);
|
||||
$y += $watermarkHeight + $offsetY;
|
||||
}
|
||||
$x += $watermarkWidth + $offsetX;
|
||||
}
|
||||
} else {
|
||||
$image->insert($watermark, $position, $offsetX, $offsetY);
|
||||
}
|
||||
|
||||
return $image;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成缩略图,缩略图目录必须在 public 目录下,且该目录必须存在
|
||||
*
|
||||
* @param mixed $image 图片数据
|
||||
* @param mixed $data 物理图片数据
|
||||
* @param int $max 最大宽高
|
||||
* @param bool $force 是否强制覆盖
|
||||
* @return void
|
||||
*/
|
||||
public function makeThumbnail(Image $image, mixed $data, int $max = 400, bool $force = false): void
|
||||
{
|
||||
$pathname = public_path($image->getThumbnailPathname());
|
||||
|
||||
if (! file_exists($pathname) || $force) {
|
||||
try {
|
||||
// 创建文件夹
|
||||
if (! is_dir(dirname($pathname))) {
|
||||
@mkdir(dirname($pathname));
|
||||
}
|
||||
|
||||
@ini_set('memory_limit', '512M');
|
||||
|
||||
$manager = new ImageManager(['driver' => 'imagick']);
|
||||
$img = $manager->make($data);
|
||||
|
||||
$width = $w = $image->width;
|
||||
$height = $h = $image->height;
|
||||
|
||||
if ($w > $max && $h > $max) {
|
||||
$scale = min($max / $w, $max / $h);
|
||||
$width = (int)($w * $scale);
|
||||
$height = (int)($h * $scale);
|
||||
}
|
||||
|
||||
$img->fit($width, $height, fn($constraint) => $constraint->upsize())->encode('png')->save($pathname);
|
||||
$img->destroy();
|
||||
} catch (\Throwable $e) {
|
||||
Utils::e($e, '生成缩略图时出现异常');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取水印画布
|
||||
*
|
||||
* @param string $driver
|
||||
* @param Collection $options
|
||||
* @return \Intervention\Image\Image
|
||||
*/
|
||||
private function getWatermark(string $driver, Collection $options): \Intervention\Image\Image
|
||||
{
|
||||
$manager = new ImageManager(config('image'));
|
||||
|
||||
if ($driver === 'image') {
|
||||
$watermark = $manager->make(storage_path('app/public/'.trim($options->get(ImageOption::Image), '/')));
|
||||
$opacity = (int) $options->get(ImageOption::Opacity, 0);
|
||||
$rotate = (int) $options->get(ImageOption::Rotate, 0);
|
||||
$width = $options->get(ImageOption::Width, 0);
|
||||
$height = $options->get(ImageOption::Height, 0);
|
||||
|
||||
if ($opacity && $opacity != 100) {
|
||||
$watermark->opacity((int) min($opacity, 100));
|
||||
}
|
||||
|
||||
if ($rotate) {
|
||||
$watermark->rotate($rotate);
|
||||
}
|
||||
|
||||
if ($width + $height > 0) {
|
||||
$watermark->resize($width ?: null, $height ?: null, function ($constraint) {
|
||||
$constraint->aspectRatio();
|
||||
$constraint->upsize();
|
||||
});
|
||||
}
|
||||
return $watermark;
|
||||
} else {
|
||||
$text = $options->get(FontOption::Text, Utils::config(ConfigKey::AppName));
|
||||
$font = new Font(urldecode($text));
|
||||
$font->valign('top')
|
||||
->file(storage_path('app/public/'.trim($options->get(FontOption::Font), '/')))
|
||||
->size((int) $options->get(FontOption::Size, 50))
|
||||
->angle((int) $options->get(FontOption::Angle, 0))
|
||||
->color($options->get(FontOption::Color, '000000')); // 十六进制 or rgba
|
||||
$box = $font->getBoxSize();
|
||||
$canvas = $manager->canvas($box['width'], $box['height']);
|
||||
$font->applyToImage($canvas);
|
||||
return $manager->make($canvas);
|
||||
}
|
||||
}
|
||||
|
||||
protected function replacePathname(string $pathname, UploadedFile $file): string
|
||||
{
|
||||
$array = [
|
||||
'{Y}' => date('Y'),
|
||||
'{y}' => date('y'),
|
||||
'{m}' => date('m'),
|
||||
'{d}' => date('d'),
|
||||
'{timestamp}' => time(),
|
||||
'{uniqid}' => uniqid(),
|
||||
'{md5}' => md5(microtime().Str::random()),
|
||||
'{md5-16}' => substr(md5(microtime().Str::random()), 0, 16),
|
||||
'{str-random-16}' => Str::random(),
|
||||
'{str-random-10}' => Str::random(10),
|
||||
'{filename}' => Str::replaceLast('.'.$file->getClientOriginalExtension(), '', $file->getClientOriginalName()),
|
||||
'{uid}' => Auth::check() ? Auth::id() : 0,
|
||||
];
|
||||
return str_replace(array_keys($array), array_values($array), $pathname);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class OcrService
|
||||
{
|
||||
/**
|
||||
* Get AI config from database (cached).
|
||||
*/
|
||||
private function getConfig(): array
|
||||
{
|
||||
$provider = Cache::rememberForever('configs', fn() => \App\Utils::config()->toArray());
|
||||
return [
|
||||
'enabled' => $provider['ai_ocr_enabled'] ?? true,
|
||||
'provider' => $provider['ai_provider'] ?? 'tesseract',
|
||||
'api_url' => $provider['ai_api_url'] ?? '',
|
||||
'api_key' => $provider['ai_api_key'] ?? '',
|
||||
'model' => $provider['ai_model'] ?? '',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Process an image — extract text via configured provider.
|
||||
*/
|
||||
public function processImage($image): string
|
||||
{
|
||||
$config = $this->getConfig();
|
||||
|
||||
if (!$config['enabled'] || $config['provider'] === 'none') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$fullPath = $this->getFullPath($image);
|
||||
if (!$fullPath || !file_exists($fullPath)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$text = match ($config['provider']) {
|
||||
'openai' => $this->ocrViaOpenAI($fullPath, $config),
|
||||
default => $this->ocrViaTesseract($fullPath),
|
||||
};
|
||||
|
||||
$text = trim($text);
|
||||
if ($text !== '') {
|
||||
$image->update(['ocr_text' => $text]);
|
||||
Log::info("OCR done for image {$image->id}: " . mb_substr($text, 0, 100));
|
||||
}
|
||||
|
||||
return $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build full disk path from image record.
|
||||
*/
|
||||
private function getFullPath($image): ?string
|
||||
{
|
||||
$filesystem = $image->strategy->filesystem ?? null;
|
||||
$strategyConfig = $image->strategy->configs ?? null;
|
||||
if (!$filesystem || !$strategyConfig) return null;
|
||||
|
||||
$root = $strategyConfig->get('root');
|
||||
if (!$root) return null;
|
||||
|
||||
return rtrim($root, '/') . '/' . ltrim($image->pathname, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Local Tesseract OCR.
|
||||
*/
|
||||
private function ocrViaTesseract(string $filePath): string
|
||||
{
|
||||
$process = new \Symfony\Component\Process\Process([
|
||||
'tesseract', $filePath, 'stdout',
|
||||
'-l', 'chi_sim+eng',
|
||||
'--psm', '3',
|
||||
]);
|
||||
$process->setTimeout(30);
|
||||
$process->run();
|
||||
|
||||
return $process->isSuccessful() ? $process->getOutput() : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenAI-compatible Vision API.
|
||||
*/
|
||||
private function ocrViaOpenAI(string $filePath, array $config): string
|
||||
{
|
||||
$apiKey = $config['api_key'];
|
||||
$apiUrl = $config['api_url'] ?: 'https://api.openai.com/v1/chat/completions';
|
||||
$model = $config['model'] ?: 'gpt-4o-mini';
|
||||
|
||||
if (empty($apiKey)) {
|
||||
Log::warning('OCR: OpenAI API key not configured');
|
||||
return '';
|
||||
}
|
||||
|
||||
$imageData = base64_encode(file_get_contents($filePath));
|
||||
$mimeType = $this->getMimeType($filePath);
|
||||
$dataUrl = "data:{$mimeType};base64,{$imageData}";
|
||||
|
||||
try {
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer {$apiKey}",
|
||||
'Content-Type' => 'application/json',
|
||||
])->timeout(60)->post($apiUrl, [
|
||||
'model' => $model,
|
||||
'messages' => [
|
||||
[
|
||||
'role' => 'user',
|
||||
'content' => [
|
||||
[
|
||||
'type' => 'text',
|
||||
'text' => '请识别这张图片中的所有文字内容,直接输出文字,不要添加任何说明。',
|
||||
],
|
||||
[
|
||||
'type' => 'image_url',
|
||||
'image_url' => ['url' => $dataUrl],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
'max_tokens' => 4096,
|
||||
]);
|
||||
|
||||
if ($response->successful()) {
|
||||
$body = $response->json();
|
||||
return $body['choices'][0]['message']['content'] ?? '';
|
||||
}
|
||||
|
||||
Log::error('OCR API error: ' . $response->body());
|
||||
return '';
|
||||
} catch (\Exception $e) {
|
||||
Log::error('OCR API exception: ' . $e->getMessage());
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
private function getMimeType(string $filePath): string
|
||||
{
|
||||
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
|
||||
return match ($ext) {
|
||||
'jpg', 'jpeg' => 'image/jpeg',
|
||||
'png' => 'image/png',
|
||||
'gif' => 'image/gif',
|
||||
'webp' => 'image/webp',
|
||||
'bmp' => 'image/bmp',
|
||||
default => 'image/png',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up()
|
||||
{
|
||||
Schema::table('images', function (Blueprint $table) {
|
||||
$table->text('ocr_text')->nullable()->after('origin_name');
|
||||
});
|
||||
}
|
||||
|
||||
public function down()
|
||||
{
|
||||
Schema::table('images', function (Blueprint $table) {
|
||||
$table->dropColumn('ocr_text');
|
||||
});
|
||||
}
|
||||
};
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
/*!
|
||||
* Cropper.js v1.6.1
|
||||
* https://fengyuanchen.github.io/cropperjs
|
||||
*
|
||||
* Copyright 2015-present Chen Fengyuan
|
||||
* Released under the MIT license
|
||||
*
|
||||
* Date: 2023-09-17T03:44:17.565Z
|
||||
*/.cropper-container{direction:ltr;font-size:0;line-height:0;position:relative;-ms-touch-action:none;touch-action:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.cropper-container img{backface-visibility:hidden;display:block;height:100%;image-orientation:0deg;max-height:none!important;max-width:none!important;min-height:0!important;min-width:0!important;width:100%}.cropper-canvas,.cropper-crop-box,.cropper-drag-box,.cropper-modal,.cropper-wrap-box{bottom:0;left:0;position:absolute;right:0;top:0}.cropper-canvas,.cropper-wrap-box{overflow:hidden}.cropper-drag-box{background-color:#fff;opacity:0}.cropper-modal{background-color:#000;opacity:.5}.cropper-view-box{display:block;height:100%;outline:1px solid #39f;outline-color:rgba(51,153,255,.75);overflow:hidden;width:100%}.cropper-dashed{border:0 dashed #eee;display:block;opacity:.5;position:absolute}.cropper-dashed.dashed-h{border-bottom-width:1px;border-top-width:1px;height:33.33333%;left:0;top:33.33333%;width:100%}.cropper-dashed.dashed-v{border-left-width:1px;border-right-width:1px;height:100%;left:33.33333%;top:0;width:33.33333%}.cropper-center{display:block;height:0;left:50%;opacity:.75;position:absolute;top:50%;width:0}.cropper-center:after,.cropper-center:before{background-color:#eee;content:" ";display:block;position:absolute}.cropper-center:before{height:1px;left:-3px;top:0;width:7px}.cropper-center:after{height:7px;left:0;top:-3px;width:1px}.cropper-face,.cropper-line,.cropper-point{display:block;height:100%;opacity:.1;position:absolute;width:100%}.cropper-face{background-color:#fff;left:0;top:0}.cropper-line{background-color:#39f}.cropper-line.line-e{cursor:ew-resize;right:-3px;top:0;width:5px}.cropper-line.line-n{cursor:ns-resize;height:5px;left:0;top:-3px}.cropper-line.line-w{cursor:ew-resize;left:-3px;top:0;width:5px}.cropper-line.line-s{bottom:-3px;cursor:ns-resize;height:5px;left:0}.cropper-point{background-color:#39f;height:5px;opacity:.75;width:5px}.cropper-point.point-e{cursor:ew-resize;margin-top:-3px;right:-3px;top:50%}.cropper-point.point-n{cursor:ns-resize;left:50%;margin-left:-3px;top:-3px}.cropper-point.point-w{cursor:ew-resize;left:-3px;margin-top:-3px;top:50%}.cropper-point.point-s{bottom:-3px;cursor:s-resize;left:50%;margin-left:-3px}.cropper-point.point-ne{cursor:nesw-resize;right:-3px;top:-3px}.cropper-point.point-nw{cursor:nwse-resize;left:-3px;top:-3px}.cropper-point.point-sw{bottom:-3px;cursor:nesw-resize;left:-3px}.cropper-point.point-se{bottom:-3px;cursor:nwse-resize;height:20px;opacity:1;right:-3px;width:20px}@media (min-width:768px){.cropper-point.point-se{height:15px;width:15px}}@media (min-width:992px){.cropper-point.point-se{height:10px;width:10px}}@media (min-width:1200px){.cropper-point.point-se{height:5px;opacity:.75;width:5px}}.cropper-point.point-se:before{background-color:#39f;bottom:-50%;content:" ";display:block;height:200%;opacity:0;position:absolute;right:-50%;width:200%}.cropper-invisible{opacity:0}.cropper-bg{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC")}.cropper-hide{display:block;height:0;position:absolute;width:0}.cropper-hidden{display:none!important}.cropper-move{cursor:move}.cropper-crop{cursor:crosshair}.cropper-disabled .cropper-drag-box,.cropper-disabled .cropper-face,.cropper-disabled .cropper-line,.cropper-disabled .cropper-point{cursor:not-allowed}
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
/*!
|
||||
* Cropper.js v1.6.1
|
||||
* https://fengyuanchen.github.io/cropperjs
|
||||
*
|
||||
* Copyright 2015-present Chen Fengyuan
|
||||
* Released under the MIT license
|
||||
*
|
||||
* Date: 2023-09-17T03:44:19.860Z
|
||||
*/
|
||||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Cropper=e()}(this,function(){"use strict";function C(e,t){var i,a=Object.keys(e);return Object.getOwnPropertySymbols&&(i=Object.getOwnPropertySymbols(e),t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),a.push.apply(a,i)),a}function S(a){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?C(Object(n),!0).forEach(function(t){var e,i;e=a,i=n[t=t],(t=P(t))in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(n)):C(Object(n)).forEach(function(t){Object.defineProperty(a,t,Object.getOwnPropertyDescriptor(n,t))})}return a}function D(t){return(D="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function j(t,e){for(var i=0;i<e.length;i++){var a=e[i];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(t,P(a.key),a)}}function A(t){return function(t){if(Array.isArray(t))return a(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,e){var i;if(t)return"string"==typeof t?a(t,e):"Map"===(i="Object"===(i=Object.prototype.toString.call(t).slice(8,-1))&&t.constructor?t.constructor.name:i)||"Set"===i?Array.from(t):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?a(t,e):void 0}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var i=0,a=new Array(e);i<e;i++)a[i]=t[i];return a}function P(t){t=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0===i)return("string"===e?String:Number)(t);if("object"!=typeof(i=i.call(t,e||"default")))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}(t,"string");return"symbol"==typeof t?t:String(t)}var t="undefined"!=typeof window&&void 0!==window.document,h=t?window:{},e=!(!t||!h.document.documentElement)&&"ontouchstart"in h.document.documentElement,i=t&&"PointerEvent"in h,c="cropper",I="all",U="crop",q="move",$="zoom",B="e",k="w",O="s",T="n",E="ne",W="nw",H="se",N="sw",Q="".concat(c,"-crop"),K="".concat(c,"-disabled"),L="".concat(c,"-hidden"),Z="".concat(c,"-hide"),G="".concat(c,"-invisible"),n="".concat(c,"-modal"),V="".concat(c,"-move"),d="".concat(c,"Action"),m="".concat(c,"Preview"),F="crop",J="move",_="none",tt="crop",et="cropend",it="cropmove",at="cropstart",nt="dblclick",ot=i?"pointerdown":e?"touchstart":"mousedown",ht=i?"pointermove":e?"touchmove":"mousemove",rt=i?"pointerup pointercancel":e?"touchend touchcancel":"mouseup",st="zoom",ct="image/jpeg",dt=/^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/,lt=/^data:/,pt=/^data:image\/jpeg;base64,/,mt=/^img|canvas$/i,ut={viewMode:0,dragMode:F,initialAspectRatio:NaN,aspectRatio:NaN,data:null,preview:"",responsive:!0,restore:!0,checkCrossOrigin:!0,checkOrientation:!0,modal:!0,guides:!0,center:!0,highlight:!0,background:!0,autoCrop:!0,autoCropArea:.8,movable:!0,rotatable:!0,scalable:!0,zoomable:!0,zoomOnTouch:!0,zoomOnWheel:!0,wheelZoomRatio:.1,cropBoxMovable:!0,cropBoxResizable:!0,toggleDragModeOnDblclick:!0,minCanvasWidth:0,minCanvasHeight:0,minCropBoxWidth:0,minCropBoxHeight:0,minContainerWidth:200,minContainerHeight:100,ready:null,cropstart:null,cropmove:null,cropend:null,crop:null,zoom:null},gt=Number.isNaN||h.isNaN;function p(t){return"number"==typeof t&&!gt(t)}function ft(t){return 0<t&&t<1/0}function vt(t){return void 0===t}function o(t){return"object"===D(t)&&null!==t}var wt=Object.prototype.hasOwnProperty;function u(t){if(!o(t))return!1;try{var e=t.constructor,i=e.prototype;return e&&i&&wt.call(i,"isPrototypeOf")}catch(t){return!1}}function l(t){return"function"==typeof t}var bt=Array.prototype.slice;function yt(t){return Array.from?Array.from(t):bt.call(t)}function z(i,a){return i&&l(a)&&(Array.isArray(i)||p(i.length)?yt(i).forEach(function(t,e){a.call(i,t,e,i)}):o(i)&&Object.keys(i).forEach(function(t){a.call(i,i[t],t,i)})),i}var g=Object.assign||function(i){for(var t=arguments.length,e=new Array(1<t?t-1:0),a=1;a<t;a++)e[a-1]=arguments[a];return o(i)&&0<e.length&&e.forEach(function(e){o(e)&&Object.keys(e).forEach(function(t){i[t]=e[t]})}),i},xt=/\.\d*(?:0|9){12}\d*$/;function Y(t,e){e=1<arguments.length&&void 0!==e?e:1e11;return xt.test(t)?Math.round(t*e)/e:t}var Mt=/^width|height|left|top|marginLeft|marginTop$/;function f(t,e){var i=t.style;z(e,function(t,e){Mt.test(e)&&p(t)&&(t="".concat(t,"px")),i[e]=t})}function v(t,eLine truncated
|
||||
@@ -0,0 +1,985 @@
|
||||
@section('title', '我的图片')
|
||||
|
||||
@push('styles')
|
||||
<link rel="stylesheet" href="{{ asset('css/justified-gallery/justifiedGallery.min.css') }}">
|
||||
<link rel="stylesheet" href="{{ asset('css/viewer-js/viewer.min.css') }}">
|
||||
<link rel="stylesheet" href="{{ asset('css/context-js/context-js.css') }}">
|
||||
<style>
|
||||
/* Make image selector always visible for easier selection */
|
||||
#images-grid .images-item .image-selector { display: block !important; }
|
||||
#images-grid .images-item:hover { outline-color: #3b82f6; }
|
||||
#images-grid .images-item.ds-selected { outline-color: #3b82f6; }
|
||||
#images-grid .images-item .image-selector i { transition: all 0.15s; }
|
||||
#images-grid .images-item:hover .image-selector i,
|
||||
#images-grid .images-item.ds-selected .image-selector i { border-color: #fff; color: #0061ff; }
|
||||
/* Image Editor Modal */
|
||||
#editor-modal { display: none; position: fixed; inset: 0; z-index: 9999; background: rgba(0,0,0,0.8); overflow: auto; }
|
||||
#editor-modal.active { display: flex; align-items: center; justify-content: center; }
|
||||
.editor-container { background: #fff; border-radius: 8px; width: 90vw; max-width: 1000px; max-height: 90vh; display: flex; flex-direction: column; overflow: hidden; }
|
||||
.editor-header { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; border-bottom: 1px solid #e5e7eb; }
|
||||
.editor-header h3 { font-size: 16px; font-weight: 600; color: #374151; }
|
||||
.editor-body { display: flex; flex: 1; overflow: hidden; }
|
||||
.editor-preview { flex: 1; display: flex; align-items: center; justify-content: center; background: #f3f4f6; min-height: 400px; position: relative; }
|
||||
.editor-preview img { max-width: 100%; max-height: 60vh; }
|
||||
.editor-sidebar { width: 240px; padding: 16px; border-left: 1px solid #e5e7eb; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; }
|
||||
.editor-group { display: flex; flex-direction: column; gap: 8px; }
|
||||
.editor-group label { font-size: 13px; font-weight: 500; color: #6b7280; }
|
||||
.editor-group input[type="range"] { width: 100%; }
|
||||
.editor-toolbar { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.editor-toolbar button { padding: 6px 12px; border: 1px solid #d1d5db; border-radius: 6px; background: #fff; cursor: pointer; font-size: 13px; color: #374151; transition: all 0.15s; }
|
||||
.editor-toolbar button:hover { background: #f3f4f6; border-color: #9ca3af; }
|
||||
.editor-toolbar button.active { background: #3b82f6; color: #fff; border-color: #3b82f6; }
|
||||
.editor-footer { display: flex; justify-content: flex-end; gap: 8px; padding: 12px 16px; border-top: 1px solid #e5e7eb; }
|
||||
.editor-footer button { padding: 8px 20px; border-radius: 6px; font-size: 14px; font-weight: 500; cursor: pointer; transition: all 0.15s; }
|
||||
.btn-cancel { background: #fff; border: 1px solid #d1d5db; color: #374151; }
|
||||
.btn-cancel:hover { background: #f9fafb; }
|
||||
.btn-save { background: #3b82f6; border: 1px solid #3b82f6; color: #fff; }
|
||||
.btn-save:hover { background: #2563eb; }
|
||||
.btn-save:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.ratio-btns { display: flex; gap: 6px; flex-wrap: wrap; }
|
||||
.ratio-btns button { padding: 4px 10px; font-size: 12px; }
|
||||
</style>
|
||||
@endpush
|
||||
|
||||
<x-app-layout>
|
||||
<div class="relative flex justify-between items-center px-2 py-2 z-[3] top-0 left-0 right-0 bg-white border-solid border-b">
|
||||
<div class="space-x-2 flex justify-between items-center">
|
||||
<div class="flex-row hidden lg:flex">
|
||||
<a data-operate="movements" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">移动到相册</a>
|
||||
<a data-operate="remove" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">移出当前相册</a>
|
||||
<a data-operate="permission" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">设置权限</a>
|
||||
<a data-operate="detail" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">详细信息</a>
|
||||
<a data-operate="rename" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">重命名</a>
|
||||
<a data-operate="edit" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)"><i class="fas fa-crop-alt text-green-500 mr-1"></i> 编辑</a>
|
||||
<a data-operate="ai" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)"><i class="fas fa-magic text-indigo-500 mr-1"></i> AI 处理</a>
|
||||
<a data-operate="delete" class="hidden text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">删除</a>
|
||||
</div>
|
||||
<div class="block lg:hidden">
|
||||
<x-dropdown direction="right">
|
||||
<x-slot name="trigger">
|
||||
<a class="text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)"><i class="fas fa-ellipsis-h text-blue-500"></i></a>
|
||||
</x-slot>
|
||||
|
||||
<x-slot name="content">
|
||||
<x-dropdown-link data-operate="refresh" href="javascript:void(0)" @click="open = false">刷新</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="movements" class="hidden" href="javascript:void(0)" @click="open = false">移动到相册</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="remove" class="hidden" href="javascript:void(0)" @click="open = false">移出当前相册</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="permission" class="hidden" href="javascript:void(0)" @click="open = false">设置权限</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="detail" class="hidden" href="javascript:void(0)" @click="open = false">详细信息</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="rename" class="hidden" href="javascript:void(0)" @click="open = false">重命名</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="edit" class="hidden" href="javascript:void(0)" @click="open = false"><i class="fas fa-crop-alt text-green-500 mr-1"></i> 编辑</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="ai" class="hidden" href="javascript:void(0)" @click="open = false"><i class="fas fa-magic text-indigo-500 mr-1"></i> AI 处理</x-dropdown-link>
|
||||
<x-dropdown-link data-operate="delete" class="hidden" href="javascript:void(0)" @click="open = false">删除</x-dropdown-link>
|
||||
</x-slot>
|
||||
</x-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex space-x-2 items-center">
|
||||
<input type="text" id="search" class="px-3 py-2 border border-gray-300 outline-none rounded-lg bg-white text-sm transition-all duration-300 w-64 focus:w-80 focus:border-blue-400 focus:shadow-sm placeholder:text-gray-400" placeholder="🔍 搜索文件名 / 图片OCR识别文字...">
|
||||
<x-dropdown direction="left">
|
||||
<x-slot name="trigger">
|
||||
<a id="order" class="text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">
|
||||
<span>最新</span>
|
||||
<i class="fas fa-sort-alpha-up text-blue-500"></i>
|
||||
</a>
|
||||
</x-slot>
|
||||
|
||||
<x-slot name="content">
|
||||
<x-dropdown-link href="javascript:void(0)" @click="setOrderBy('newest'); open = false">最新
|
||||
</x-dropdown-link>
|
||||
<x-dropdown-link href="javascript:void(0)" @click="setOrderBy('earliest'); open = false">最早
|
||||
</x-dropdown-link>
|
||||
<x-dropdown-link href="javascript:void(0)" @click="setOrderBy('utmost'); open = false">最大
|
||||
</x-dropdown-link>
|
||||
<x-dropdown-link href="javascript:void(0)" @click="setOrderBy('least'); open = false">最小
|
||||
</x-dropdown-link>
|
||||
</x-slot>
|
||||
</x-dropdown>
|
||||
<x-dropdown direction="left">
|
||||
<x-slot name="trigger">
|
||||
<a id="permission" class="text-sm py-2 px-3 hover:bg-gray-100 rounded text-gray-800" href="javascript:void(0)">
|
||||
<span>全部</span>
|
||||
<i class="fas fa-eye text-blue-500"></i>
|
||||
</a>
|
||||
</x-slot>
|
||||
|
||||
<x-slot name="content">
|
||||
<x-dropdown-link href="javascript:void(0)" @click="open = false; setPermission('all')">全部
|
||||
</x-dropdown-link>
|
||||
<x-dropdown-link href="javascript:void(0)" @click="open = false; setPermission('public')">公开
|
||||
</x-dropdown-link>
|
||||
<x-dropdown-link href="javascript:void(0)" @click="open = false; setPermission('private')">私有
|
||||
</x-dropdown-link>
|
||||
</x-slot>
|
||||
</x-dropdown>
|
||||
</div>
|
||||
</div>
|
||||
<div class="relative inset-0 h-full overflow-hidden flex">
|
||||
<!-- 左侧相册列表 -->
|
||||
<div id="albums-sidebar" class="w-48 md:w-56 bg-gray-50 border-r border-gray-200 flex-shrink-0 flex flex-col h-full overflow-hidden">
|
||||
<div class="px-3 py-2 border-b border-gray-200 bg-white flex items-center justify-between">
|
||||
<span class="text-sm font-medium text-gray-700">相册</span>
|
||||
<a href="javascript:void(0)" onclick="$('#album-add').toggleClass('hidden')" class="text-blue-500 hover:text-blue-600">
|
||||
<i class="fas fa-plus text-sm"></i>
|
||||
</a>
|
||||
</div>
|
||||
<div id="albums-list" class="flex-1 overflow-y-auto p-2 space-y-1">
|
||||
<!-- 相册列表将通过JS动态加载 -->
|
||||
<div class="text-center text-gray-400 py-4 text-sm">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右侧图片区域 -->
|
||||
<div class="flex-1 relative">
|
||||
<!-- content -->
|
||||
<div id="images-scroll" class="absolute inset-0 overflow-y-scroll dragselect select-none">
|
||||
<div id="images-grid" class="dragselect"></div>
|
||||
</div>
|
||||
<!-- right drawer -->
|
||||
<div id="drawer-mask" class="absolute hidden inset-0 bg-gray-500 bg-opacity-50 z-[2]" onclick="drawer.close()"></div>
|
||||
<div id="drawer" class="absolute bg-white w-64 md:w-72 top-0 -right-[1000px] bottom-0 z-[2] flex flex-col transition-all duration-300">
|
||||
<div class="flex justify-between items-center text-md px-3 py-1 border-b">
|
||||
<span class="text-gray-600 truncate" id="drawer-title"></span>
|
||||
<a href="javascript:drawer.close()" class="p-2"><i class="fas fa-times text-blue-500"></i></a>
|
||||
</div>
|
||||
<div id="drawer-content" class="overflow-y-auto"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/html" id="images-item-tpl">
|
||||
<a href="javascript:void(0)" data-id="__id__" data-json='__json__' class="images-item relative cursor-default rounded outline outline-2 outline-offset-2 outline-transparent">
|
||||
<div class="image-selector absolute z-[2] top-0 right-0 overflow-hidden cursor-pointer sm:hidden group-hover:block">
|
||||
<div class="p-1 text-xl sm:text-2xl">
|
||||
<i class="fas fa-check-circle block rounded-full bg-white text-white border border-gray-500"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="image-mask absolute left-0 right-0 bottom-0 h-20 z-[1] bg-gradient-to-t from-black" onclick="$(this).siblings('img').trigger('click')">
|
||||
<div class="absolute left-2 bottom-2 text-white z-[2] w-[90%]">
|
||||
<p class="text-sm truncate filename" title="__name__">__name__</p>
|
||||
<p class="text-xs date" title="__human_date__">__date__</p>
|
||||
</div>
|
||||
</div>
|
||||
<img alt="__name__" data-original="__url__" src="__thumb_url__" width="__width__" height="__height__">
|
||||
</a>
|
||||
</script>
|
||||
|
||||
<script type="text/html" id="album-add-tpl">
|
||||
<div id="album-add" class="flex flex-col w-full hidden border rounded p-2 bg-white mb-2">
|
||||
<p class="error-message text-white p-2 mb-2 text-sm bg-red-500 rounded hidden"></p>
|
||||
<form class="w-full space-y-2" action="/user/albums">
|
||||
<input type="text" class="w-full rounded px-2.5 py-1.5 text-sm border-0 bg-gray-200" name="name" placeholder="请输入名称">
|
||||
<textarea class="w-full resize-y rounded-md text-sm border-0 bg-gray-200" name="intro" placeholder="请输入简介"></textarea>
|
||||
<div class="flex space-x-2">
|
||||
<button type="submit" class="flex-1 py-1 px-2 bg-indigo-500 text-white text-sm text-center tracking-wider font-semibold rounded-md">创建</button>
|
||||
<button type="button" onclick="$('#album-add').addClass('hidden')" class="py-1 px-2 bg-gray-300 text-gray-700 text-sm rounded-md">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</script>
|
||||
|
||||
<script type="text/html" id="albums-item-tpl">
|
||||
<a href="javascript:void(0)" data-id="__id__" data-json='__json__' title="__intro__" class="albums-item flex justify-between items-center group px-2 h-8 rounded w-full text-gray-700 hover:bg-blue-100 cursor-pointer">
|
||||
<span class="text-sm truncate w-[70%] name">__name__</span>
|
||||
<div class="flex items-center justify-center space-x-1 hidden group-hover:block">
|
||||
<span class="update text-gray-500 hover:text-blue-500"><i class="fas fa-edit text-xs"></i></span>
|
||||
<span class="delete text-gray-500 hover:text-red-500"><i class="fas fa-trash-alt text-xs"></i></span>
|
||||
</div>
|
||||
<span class="group-hover:hidden text-xs text-gray-400">__image_num__</span>
|
||||
</a>
|
||||
</script>
|
||||
|
||||
<script type="text/html" id="album-update-tpl">
|
||||
<div id="album-edit" data-id="__id__" class="flex flex-col w-full border rounded p-2 bg-white mb-2">
|
||||
<p class="error-message text-white p-2 mb-2 text-sm bg-red-500 rounded hidden"></p>
|
||||
<form class="w-full space-y-2" action="/user/albums/__id__">
|
||||
<input type="text" class="w-full rounded px-2.5 py-1.5 text-sm border-0 bg-gray-200" placeholder="请输入名称" name="name" value="__name__">
|
||||
<textarea class="w-full resize-y rounded-md text-sm border-0 bg-gray-200" name="intro" placeholder="请输入简介">__intro__</textarea>
|
||||
<div class="flex space-x-2">
|
||||
<button type="submit" class="flex-1 py-1 px-2 bg-indigo-500 text-white text-sm text-center tracking-wider font-semibold rounded-md">确认</button>
|
||||
<button type="button" onclick="$(this).closest('#album-edit').remove()" class="py-1 px-2 bg-gray-300 text-gray-700 text-sm rounded-md">取消</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</script>
|
||||
|
||||
<script type="text/html" id="image-detail-tpl">
|
||||
<div class="my-4 px-4 space-y-3">
|
||||
<div>
|
||||
<span class="text-sm font-semibold">相册名称</span>
|
||||
<p class="my-2 break-words text-gray-700">__album_name__</p>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-sm font-semibold">使用策略</div>
|
||||
<p class="my-2 break-words text-gray-600">__strategy_name__</p>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-sm font-semibold">图片名称</div>
|
||||
<p class="my-2 break-words text-gray-600">__filename__</p>
|
||||
</div>
|
||||
<div>
|
||||
<div class="text-sm font-semibold">链接</div>
|
||||
<div class="my-2 p-2 bg-gray-100 rounded">
|
||||
<div class="space-y-1">
|
||||
<div>
|
||||
<span class="text-xs text-gray-500">直链</span>
|
||||
<p class="text-xs text-blue-500 truncate">__url__</p>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-500">Markdown</span>
|
||||
<p class="text-xs text-gray-600 break-all">__markdown__</p>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-500">HTML</span>
|
||||
<p class="text-xs text-gray-600 break-all">__html__</p>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-500">BBCode</span>
|
||||
<p class="text-xs text-gray-600 break-all">__bbcode__</p>
|
||||
</div>
|
||||
<div>
|
||||
<span class="text-xs text-gray-500">缩略图</span>
|
||||
<p class="text-xs text-blue-500 truncate">__thumb_url__</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between text-sm text-gray-500">
|
||||
<span>尺寸:__width__ x __height__</span>
|
||||
<span>大小:__size__</span>
|
||||
</div>
|
||||
<div class="text-sm text-gray-500">上传时间:__date__</div>
|
||||
</div>
|
||||
</script>
|
||||
|
||||
@push('scripts')
|
||||
<script src="{{ asset('js/justified-gallery/jquery.justifiedGallery.min.js') }}"></script>
|
||||
<script src="{{ asset('js/dragselect/ds.min.js') }}"></script>
|
||||
<script src="{{ asset('js/viewer-js/viewer.min.js') }}"></script>
|
||||
<script src="{{ asset('js/context-js/context-js.js') }}"></script>
|
||||
<link rel="stylesheet" href="{{ asset('js/cropper/cropper.min.css') }}">
|
||||
<script src="{{ asset('js/cropper/cropper.min.js') }}"></script>
|
||||
<script>
|
||||
const IMAGES_SCROLL = '#images-scroll';
|
||||
const IMAGES_GRID = '#images-grid';
|
||||
const IMAGES_ITEM = '.images-item';
|
||||
const ALBUM_ITEM = '.albums-item';
|
||||
const HEADER_TITLE = '#header-title';
|
||||
|
||||
const gridConfigs = {
|
||||
rowHeight: 180,
|
||||
maxRowHeight: 360,
|
||||
margins: 8,
|
||||
lastRow: 'nojustify',
|
||||
justifyThreshold: 0.9,
|
||||
cssAnimation: true
|
||||
};
|
||||
|
||||
const $headerTitle = $(HEADER_TITLE);
|
||||
const $photos = $(IMAGES_GRID);
|
||||
const $drawer = $("#drawer");
|
||||
const $drawerMask = $('#drawer-mask');
|
||||
let viewer = new Viewer(document.getElementById('images-grid'), {url: 'data-original'});
|
||||
const drawer = {
|
||||
open(title, content, callback) {
|
||||
$drawerMask.fadeIn();
|
||||
$drawer.css('right', 0);
|
||||
$drawer.find('#drawer-title').html(title);
|
||||
$drawer.find('#drawer-content').html(content);
|
||||
callback && callback();
|
||||
},
|
||||
close(callback) {
|
||||
$drawerMask.fadeOut();
|
||||
$drawer.css('right', '-1000px');
|
||||
callback && callback();
|
||||
},
|
||||
toggle(title, content, callback) {
|
||||
if ($drawerMask.is(':hidden')) {
|
||||
this.open(title, content, callback);
|
||||
} else {
|
||||
this.close(callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Gallery will be initialized on first image load via galleryNeedsInit
|
||||
|
||||
let albumsInfinite = null;
|
||||
const imagesInfinite = utils.infiniteScroll(IMAGES_SCROLL, {
|
||||
url: '{{ route('user.images') }}',
|
||||
classes: ['dragselect'],
|
||||
success: function (response) {
|
||||
if (!response.status) {
|
||||
return toastr.error(response.message);
|
||||
}
|
||||
|
||||
let images = response.data.images.data;
|
||||
if (images.length <= 0 || response.data.images.current_page === response.data.images.last_page) {
|
||||
this.finished = true;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
for (const i in images) {
|
||||
let item = $('#images-item-tpl').html()
|
||||
.replace(/__id__/g, images[i].id)
|
||||
.replace(/__url__/g, images[i].url)
|
||||
.replace(/__thumb_url__/g, images[i].thumb_url)
|
||||
.replace(/__width__/g, images[i].width)
|
||||
.replace(/__height__/g, images[i].height)
|
||||
.replace(/__name__/g, images[i].filename)
|
||||
.replace(/__human_date__/g, images[i].human_date)
|
||||
.replace(/__date__/g, images[i].date)
|
||||
.replace(/__json__/g, JSON.stringify(images[i]))
|
||||
html += item;
|
||||
}
|
||||
|
||||
$photos.append(html);
|
||||
// Manually register new images with DragSelect
|
||||
try {
|
||||
ds.addSelectables($photos.find('.images-item').toArray());
|
||||
} catch(e) {}
|
||||
if (galleryNeedsInit) {
|
||||
$photos.justifiedGallery(gridConfigs);
|
||||
galleryNeedsInit = false;
|
||||
// Reinitialize Viewer for new images
|
||||
if (viewer) viewer.destroy();
|
||||
viewer = new Viewer(document.getElementById('images-grid'), {url: 'data-original'});
|
||||
// DragSelect auto-detects new elements via event delegation
|
||||
} else {
|
||||
$photos.justifiedGallery('norewind');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let galleryNeedsInit = true;
|
||||
const resetImages = (params) => {
|
||||
try { $photos.justifiedGallery('destroy'); } catch(e) {}
|
||||
$photos.html('');
|
||||
galleryNeedsInit = true;
|
||||
ds.clearSelection();
|
||||
params = $.extend({page: 1}, params)
|
||||
imagesInfinite.refresh(params);
|
||||
}
|
||||
|
||||
// 初始化相册列表
|
||||
const initAlbums = () => {
|
||||
const $albumsList = $('#albums-list');
|
||||
const CREATE_ID = '#album-add';
|
||||
|
||||
// 加载相册
|
||||
$.ajax({
|
||||
url: '{{ route('user.albums') }}',
|
||||
success: function(response) {
|
||||
if (!response.status) {
|
||||
return toastr.error(response.message);
|
||||
}
|
||||
|
||||
let albums = response.data.albums.data;
|
||||
let html = $('#album-add-tpl').html();
|
||||
for (const i in albums) {
|
||||
let item = $('#albums-item-tpl').html()
|
||||
.replace(/__id__/g, albums[i].id)
|
||||
.replace(/__name__/g, albums[i].name)
|
||||
.replace(/__intro__/g, albums[i].intro)
|
||||
.replace(/__image_num__/g, albums[i].image_num)
|
||||
.replace(/__json__/g, JSON.stringify(albums[i]))
|
||||
if (albums[i].id === selectedAlbum.id) {
|
||||
item = item
|
||||
.replace(/bg-gray-100/g, 'bg-blue-400')
|
||||
.replace(/text-gray-800/g, 'text-white')
|
||||
}
|
||||
html += item;
|
||||
}
|
||||
$albumsList.html(html);
|
||||
|
||||
// 绑定点击事件
|
||||
bindAlbumEvents();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 绑定相册事件
|
||||
const bindAlbumEvents = () => {
|
||||
const $albumsList = $('#albums-list');
|
||||
const CREATE_ID = '#album-add';
|
||||
const UPDATE_ID = '#album-edit';
|
||||
|
||||
// 点击相册
|
||||
$albumsList.off('click', '>a.albums-item').on('click', '>a.albums-item', function() {
|
||||
if (selectedAlbum.id === $(this).data('id')) {
|
||||
selectedAlbum = {};
|
||||
} else {
|
||||
selectedAlbum = $(this).data('json');
|
||||
}
|
||||
resetImages({page: 1, album_id: selectedAlbum.id || null});
|
||||
ds.clearSelection();
|
||||
// 更新高亮
|
||||
$albumsList.find('a.albums-item').removeClass('bg-blue-400 text-white').addClass('bg-transparent text-gray-700');
|
||||
if (selectedAlbum.id) {
|
||||
$(this).removeClass('bg-transparent text-gray-700').addClass('bg-blue-400 text-white');
|
||||
}
|
||||
});
|
||||
|
||||
// 编辑相册
|
||||
$albumsList.off('click', '.update').on('click', '.update', function(e) {
|
||||
e.stopPropagation();
|
||||
let $item = $(this).closest('a.albums-item');
|
||||
$albumsList.find(UPDATE_ID).remove();
|
||||
$item.after($('#album-update-tpl').html()
|
||||
.replace(/__id__/g, $item.data('id'))
|
||||
.replace(/__name__/g, $item.find('>span.name').html())
|
||||
.replace(/__intro__/g, $item.attr('title'))
|
||||
);
|
||||
});
|
||||
|
||||
// 删除相册
|
||||
$albumsList.off('click', '.delete').on('click', '.delete', function(e) {
|
||||
e.stopPropagation();
|
||||
Swal.fire({
|
||||
title: '确认删除该相册?',
|
||||
text: "删除后相册中的图片将会被移出。",
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: '确认',
|
||||
}).then((result) => {
|
||||
if (result.isConfirmed) {
|
||||
let id = $(this).closest(ALBUM_ITEM).data('id');
|
||||
axios.delete(`/user/albums/${id}`).then(response => {
|
||||
if (response.data.status) {
|
||||
selectedAlbum = {};
|
||||
initAlbums();
|
||||
resetImages();
|
||||
} else {
|
||||
toastr.error(response.data.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 创建相册
|
||||
$albumsList.off('submit', CREATE_ID + ' form').on('submit', CREATE_ID + ' form', function(e) {
|
||||
e.preventDefault();
|
||||
let $form = $(this);
|
||||
axios.post($form.attr('action'), $form.serialize()).then(response => {
|
||||
let $errorMessage = $albumsList.find(CREATE_ID + ' .error-message').html('').hide();
|
||||
if (response.data.status) {
|
||||
$form.get(0).reset();
|
||||
initAlbums();
|
||||
} else {
|
||||
$errorMessage.html('<i class="fas fa-exclamation-circle"></i> ' + response.data.message).show();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 更新相册
|
||||
$albumsList.off('submit', UPDATE_ID + ' form').on('submit', UPDATE_ID + ' form', function(e) {
|
||||
e.preventDefault();
|
||||
let $form = $(this);
|
||||
let $editContainer = $(this).closest(UPDATE_ID);
|
||||
axios.put($form.attr('action'), $form.serialize()).then(response => {
|
||||
let $errorMessage = $albumsList.find(UPDATE_ID + ' .error-message').html('').hide();
|
||||
if (response.data.status) {
|
||||
$albumsList.find(`>a[data-id=${$editContainer.data('id')}]`)
|
||||
.attr('title', $form.find('textarea').val())
|
||||
.find('.name').text($form.find('input').val());
|
||||
$editContainer.remove();
|
||||
} else {
|
||||
$errorMessage.html('<i class="fas fa-exclamation-circle"></i> ' + response.data.message).show();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 页面加载时初始化相册
|
||||
initAlbums();
|
||||
|
||||
const setOrderBy = function (sort) {
|
||||
resetImages({page: 1, order: sort})
|
||||
$('#order span').text({newest: '最新', earliest: '最早', utmost: '最大', least: '最小'}[sort]);
|
||||
};
|
||||
|
||||
const setPermission = function (permission) {
|
||||
resetImages({page: 1, permission: permission})
|
||||
$('#permission span').text({public: '公开', private: '私有', all: '全部'}[permission]);
|
||||
};
|
||||
|
||||
$('#search').keydown(function (e) {
|
||||
if (e.keyCode === 13) {
|
||||
resetImages({page: 1, keyword: $(this).val()});
|
||||
}
|
||||
});
|
||||
|
||||
$(document).keydown(e => {
|
||||
if (e.keyCode === 65 && (e.altKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
ds.setSelection($(IMAGES_ITEM));
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<script>
|
||||
const ds = new DragSelect({
|
||||
area: $(IMAGES_SCROLL).get(0),
|
||||
keyboardDrag: false,
|
||||
});
|
||||
// Click on empty area clears selection
|
||||
ds.subscribe("elementselect", () => { let items = ds.getSelection();
|
||||
if (!items.length) {
|
||||
$headerTitle.text('我的图片');
|
||||
$('[data-operate]').hide();
|
||||
$('[data-operate="refresh"]').show();
|
||||
}
|
||||
});
|
||||
// Double-click image → show in Viewer
|
||||
$(IMAGES_SCROLL).on('dblclick', '.images-item', function(e) {
|
||||
e.preventDefault();
|
||||
let $items = $('#images-grid .images-item');
|
||||
let idx = $items.index($(this));
|
||||
if (viewer) {
|
||||
try { viewer.view(idx); } catch(err) {}
|
||||
viewer.show();
|
||||
}
|
||||
});
|
||||
// Capture-phase handler: intercept clicks on .image-selector BEFORE DragSelect sees them
|
||||
document.addEventListener('mousedown', function(e) {
|
||||
var sel = e.target.closest('.image-selector');
|
||||
if (!sel) return;
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
var item = sel.closest('.images-item');
|
||||
if (!item) return;
|
||||
// Directly toggle DragSelect's internal state
|
||||
if (ds.SelectedSet.has(item)) {
|
||||
ds.SelectedSet.remove(item);
|
||||
item.classList.remove('ds-selected');
|
||||
} else {
|
||||
ds.SelectedSet.add(item);
|
||||
item.classList.add('ds-selected');
|
||||
}
|
||||
bindOperates();
|
||||
}, true);
|
||||
|
||||
const bindOperates = () => {
|
||||
let selected = ds.getSelection();
|
||||
if (selected.length) {
|
||||
$headerTitle.text(`已选择 ${selected.length} 张图片`);
|
||||
} else {
|
||||
$headerTitle.text('我的图片');
|
||||
}
|
||||
$('[data-operate]').hide();
|
||||
let operates = [];
|
||||
if (selected.length === 0) {
|
||||
operates = ['refresh'];
|
||||
}
|
||||
if (selected.length === 1) {
|
||||
operates = ['refresh', 'movements', 'permission', 'detail', 'rename', 'edit', 'ai', 'delete'];
|
||||
}
|
||||
if (selected.length > 1) {
|
||||
operates = ['refresh', 'movements', 'permission', 'delete'];
|
||||
}
|
||||
if (selected.length && selectedAlbum.id !== undefined) {
|
||||
operates.push('remove');
|
||||
}
|
||||
$(operates.map(item => `[data-operate=${item}]`).toString()).css('display', 'block');
|
||||
};
|
||||
|
||||
ds.subscribe("elementselect", () => bindOperates()); ds.subscribe("elementunselect", () => bindOperates());
|
||||
|
||||
|
||||
// === Image Editor ===
|
||||
let editorCropper = null;
|
||||
let editorImageId = null;
|
||||
let editorOriginalSrc = null;
|
||||
const editor = {
|
||||
open(imageId, src) {
|
||||
editorImageId = imageId;
|
||||
editorOriginalSrc = src;
|
||||
const img = document.getElementById('editor-image');
|
||||
img.src = src;
|
||||
img.style.filter = '';
|
||||
$('#editor-modal').addClass('active');
|
||||
// Reset sliders
|
||||
$('#brightness, #contrast, #saturate').val(0).trigger('input');
|
||||
$('#blur').val(0).trigger('input');
|
||||
// Init Cropper after image loads
|
||||
img.onload = function() {
|
||||
if (editorCropper) editorCropper.destroy();
|
||||
editorCropper = new Cropper(img, {
|
||||
viewMode: 1,
|
||||
autoCropArea: 0.8,
|
||||
responsive: true,
|
||||
background: false,
|
||||
});
|
||||
};
|
||||
if (img.complete) img.onload();
|
||||
},
|
||||
close() {
|
||||
if (editorCropper) { editorCropper.destroy(); editorCropper = null; }
|
||||
$('#editor-modal').removeClass('active');
|
||||
editorImageId = null;
|
||||
},
|
||||
rotate(deg) {
|
||||
if (editorCropper) editorCropper.rotate(deg);
|
||||
},
|
||||
flipH() {
|
||||
if (editorCropper) editorCropper.scaleX(editorCropper.getData().scaleX === -1 ? 1 : -1);
|
||||
},
|
||||
flipV() {
|
||||
if (editorCropper) editorCropper.scaleY(editorCropper.getData().scaleY === -1 ? 1 : -1);
|
||||
},
|
||||
setAspectRatio(ratio) {
|
||||
if (editorCropper) editorCropper.setAspectRatio(ratio);
|
||||
$('.ratio-btns button').removeClass('active');
|
||||
event.target.classList.add('active');
|
||||
},
|
||||
updateFilter() {
|
||||
const b = parseInt($('#brightness').val());
|
||||
const c = parseInt($('#contrast').val());
|
||||
const s = parseInt($('#saturate').val());
|
||||
const bl = parseInt($('#blur').val());
|
||||
$('#brightness-val').text(b);
|
||||
$('#contrast-val').text(c);
|
||||
$('#saturate-val').text(s);
|
||||
$('#blur-val').text(bl);
|
||||
const filter = `brightness(${1 + b/100}) contrast(${1 + c/100}) saturate(${1 + s/100}) blur(${bl}px)`;
|
||||
$('#editor-image').css('filter', filter);
|
||||
},
|
||||
resetFilters() {
|
||||
$('#brightness, #contrast, #saturate').val(0).trigger('input');
|
||||
$('#blur').val(0).trigger('input');
|
||||
},
|
||||
async save() {
|
||||
if (!editorCropper) return;
|
||||
const btn = $('#editor-save');
|
||||
btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>处理中...');
|
||||
try {
|
||||
// Get cropped canvas
|
||||
const canvas = editorCropper.getCroppedCanvas({ maxWidth: 4096, maxHeight: 4096 });
|
||||
// Apply CSS filters to a new canvas
|
||||
const b = parseInt($('#brightness').val());
|
||||
const c = parseInt($('#contrast').val());
|
||||
const s = parseInt($('#saturate').val());
|
||||
const bl = parseInt($('#blur').val());
|
||||
const hasFilter = b !== 0 || c !== 0 || s !== 0 || bl > 0;
|
||||
let finalCanvas = canvas;
|
||||
if (hasFilter) {
|
||||
const tmpCanvas = document.createElement('canvas');
|
||||
tmpCanvas.width = canvas.width;
|
||||
tmpCanvas.height = canvas.height;
|
||||
const ctx = tmpCanvas.getContext('2d');
|
||||
ctx.filter = `brightness(${1+b/100}) contrast(${1+c/100}) saturate(${1+s/100}) blur(${bl}px)`;
|
||||
ctx.drawImage(canvas, 0, 0);
|
||||
finalCanvas = tmpCanvas;
|
||||
}
|
||||
// Convert to blob and upload
|
||||
finalCanvas.toBlob(async function(blob) {
|
||||
const formData = new FormData();
|
||||
formData.append('image', blob, 'edited.jpg');
|
||||
formData.append('id', editorImageId);
|
||||
try {
|
||||
const response = await axios.put('/user/images/' + editorImageId + '/edit', formData, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' }
|
||||
});
|
||||
if (response.data.status) {
|
||||
toastr.success('编辑保存成功');
|
||||
editor.close();
|
||||
resetImages();
|
||||
} else {
|
||||
toastr.error(response.data.message || '保存失败');
|
||||
}
|
||||
} catch(err) {
|
||||
toastr.error('上传失败: ' + (err.response?.data?.message || err.message));
|
||||
}
|
||||
btn.prop('disabled', false).html('<i class="fas fa-save mr-1"></i>保存');
|
||||
}, 'image/jpeg', 0.95);
|
||||
} catch(err) {
|
||||
toastr.error('处理失败: ' + err.message);
|
||||
btn.prop('disabled', false).html('<i class="fas fa-save mr-1"></i>保存');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
$('[data-operate]').on('click', function () {
|
||||
let operate = $(this).data('operate');
|
||||
let selected = ds.getSelection();
|
||||
if (operate === 'refresh') {
|
||||
resetImages();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!selected.length && operate !== 'refresh') {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (operate) {
|
||||
case 'movements': // 移动到相册
|
||||
methods.movements();
|
||||
break;
|
||||
case 'remove': // 移出当前相册
|
||||
methods.remove();
|
||||
break;
|
||||
case 'rename': // 重命名
|
||||
methods.rename(selected[0]);
|
||||
break;
|
||||
case 'permission':
|
||||
methods.permission();
|
||||
break;
|
||||
case 'detail':
|
||||
methods.detail(selected[0]);
|
||||
break;
|
||||
case 'edit': // 编辑
|
||||
if (selected.length === 1) {
|
||||
var jsonData = $(selected[0]).data('json');
|
||||
var imgUrl = jsonData.url || jsonData.thumb_url;
|
||||
var imgId = jsonData.id || $(selected[0]).data('id');
|
||||
editor.open(imgId, imgUrl);
|
||||
}
|
||||
break;
|
||||
case 'ai': // AI 处理
|
||||
if (selected.length) {
|
||||
var json = $(selected[0]).data('json');
|
||||
if (json && json.thumb_url) {
|
||||
window.location.href = '/ai?image_url=' + encodeURIComponent(json.thumb_url) + '&image_id=' + encodeURIComponent(json.id || $(selected[0]).data('id'));
|
||||
} else if (json && json.url) {
|
||||
window.location.href = '/ai?image_url=' + encodeURIComponent(json.url) + '&image_id=' + encodeURIComponent(json.id || $(selected[0]).data('id'));
|
||||
} else {
|
||||
toastr.error('无法获取图片信息');
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'delete': // 删除
|
||||
methods.delete();
|
||||
break;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
<script>
|
||||
let selectedAlbum = {};
|
||||
const methods = {
|
||||
movements() {
|
||||
let selected = ds.getSelection();
|
||||
const content = $('#albums-container-tpl').html();
|
||||
drawer.toggle('移动到相册', content, function () {
|
||||
let $albums = $('#albums-container');
|
||||
const CREATE_ID = '#album-add';
|
||||
albumsInfinite = utils.infiniteScroll('#drawer-content', {
|
||||
url: '{{ route('user.albums') }}',
|
||||
success: function (response) {
|
||||
if (!response.status) {
|
||||
return toastr.error(response.message);
|
||||
}
|
||||
|
||||
let albums = response.data.albums.data;
|
||||
if (albums.length <= 0 || response.data.albums.current_page === response.data.albums.last_page) {
|
||||
this.finished = true;
|
||||
}
|
||||
|
||||
let html = '';
|
||||
for (const i in albums) {
|
||||
let item = $('#albums-item-tpl').html()
|
||||
.replace(/__id__/g, albums[i].id)
|
||||
.replace(/__name__/g, albums[i].name)
|
||||
.replace(/__intro__/g, albums[i].intro)
|
||||
.replace(/__image_num__/g, albums[i].image_num)
|
||||
.replace(/__json__/g, JSON.stringify(albums[i]))
|
||||
html += item;
|
||||
}
|
||||
|
||||
$albums.append(html);
|
||||
|
||||
callback && callback.call(this, $albums.get(0));
|
||||
}
|
||||
});
|
||||
|
||||
$albums.off('click', '>a').on('click', '>a', function () {
|
||||
let id = $(this).data('id');
|
||||
let ids = [];
|
||||
selected.forEach(item => ids.push($(item).data('id')));
|
||||
axios.put('{{ route('user.images.movement') }}', {
|
||||
selected: ids,
|
||||
id: id
|
||||
}).then(response => {
|
||||
if (response.data.status) {
|
||||
toastr.success('移动成功');
|
||||
resetImages();
|
||||
setTimeout(_ => drawer.close(), 300)
|
||||
} else {
|
||||
toastr.error(response.data.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
remove() {
|
||||
let selected = ds.getSelection();
|
||||
let ids = [];
|
||||
selected.forEach(item => ids.push($(item).data('id')));
|
||||
axios.put('{{ route('user.images.movement') }}', {
|
||||
selected: ids,
|
||||
id: 0
|
||||
}).then(response => {
|
||||
if (response.data.status) {
|
||||
toastr.success('移出成功');
|
||||
resetImages();
|
||||
} else {
|
||||
toastr.error(response.data.message);
|
||||
}
|
||||
});
|
||||
},
|
||||
rename(image) {
|
||||
let $image = $(image);
|
||||
Swal.fire({
|
||||
title: '请输入新的名称',
|
||||
input: 'text',
|
||||
inputValue: $image.find('.filename').text(),
|
||||
showCancelButton: true,
|
||||
confirmButtonText: '确认',
|
||||
cancelButtonText: '取消',
|
||||
}).then((result) => {
|
||||
if (result.isConfirmed) {
|
||||
axios.put('{{ route('user.images.rename') }}', {
|
||||
id: $image.data('id'),
|
||||
name: result.value
|
||||
}).then(response => {
|
||||
if (response.data.status) {
|
||||
toastr.success('修改成功');
|
||||
$image.find('.filename').text(result.value);
|
||||
let json = $image.data('json');
|
||||
json.filename = result.value;
|
||||
$image.data('json', json);
|
||||
} else {
|
||||
toastr.error(response.data.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
permission() {
|
||||
let selected = ds.getSelection();
|
||||
let ids = [];
|
||||
selected.forEach(item => ids.push($(item).data('id')));
|
||||
let permission = 1;
|
||||
var jsonData = $(selected[0]).data('json');
|
||||
if (jsonData && jsonData.permission !== undefined) {
|
||||
permission = jsonData.permission === 0 ? 1 : 0;
|
||||
}
|
||||
axios.put('{{ route('user.images.permission') }}', {
|
||||
selected: ids,
|
||||
id: permission
|
||||
}).then(response => {
|
||||
if (response.data.status) {
|
||||
toastr.success('修改成功');
|
||||
resetImages();
|
||||
} else {
|
||||
toastr.error(response.data.message);
|
||||
}
|
||||
});
|
||||
},
|
||||
detail(image) {
|
||||
let data = $(image).data('json');
|
||||
let content = $('#image-detail-tpl').html()
|
||||
.replace(/__album_name__/g, data.album_name || '未分组')
|
||||
.replace(/__strategy_name__/g, data.strategy_name)
|
||||
.replace(/__filename__/g, data.filename)
|
||||
.replace(/__url__/g, data.url)
|
||||
.replace(/__thumb_url__/g, data.thumb_url)
|
||||
.replace(/__markdown__/g, ``)
|
||||
.replace(/__html__/g, `<img src="${data.url}" alt="${data.filename}">`)
|
||||
.replace(/__bbcode__/g, `[img]${data.url}[/img]`)
|
||||
.replace(/__width__/g, data.width)
|
||||
.replace(/__height__/g, data.height)
|
||||
.replace(/__size__/g, (data.size / 1024).toFixed(2) + ' KB')
|
||||
.replace(/__date__/g, data.date);
|
||||
drawer.toggle('图片详情', content);
|
||||
},
|
||||
delete() {
|
||||
let selected = ds.getSelection();
|
||||
let ids = [];
|
||||
selected.forEach(item => ids.push($(item).data('id')));
|
||||
Swal.fire({
|
||||
title: '确认删除选中的图片?',
|
||||
text: "删除后将无法恢复!",
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: '确认',
|
||||
cancelButtonText: '取消',
|
||||
}).then((result) => {
|
||||
if (result.isConfirmed) {
|
||||
axios.delete('{{ route('user.images.delete') }}', {
|
||||
data: {selected: ids}
|
||||
}).then(response => {
|
||||
if (response.data.status) {
|
||||
toastr.success('删除成功');
|
||||
resetImages();
|
||||
} else {
|
||||
toastr.error(response.data.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Image Editor Modal -->
|
||||
<div id="editor-modal">
|
||||
<div class="editor-container">
|
||||
<div class="editor-header">
|
||||
<h3><i class="fas fa-crop-alt text-green-500 mr-2"></i>编辑图片</h3>
|
||||
<button onclick="editor.close()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times text-xl"></i></button>
|
||||
</div>
|
||||
<div class="editor-body">
|
||||
<div class="editor-preview">
|
||||
<img id="editor-image" src="" alt="编辑中">
|
||||
</div>
|
||||
<div class="editor-sidebar">
|
||||
<div class="editor-group">
|
||||
<label><i class="fas fa-crop-alt mr-1"></i>裁剪比例</label>
|
||||
<div class="ratio-btns">
|
||||
<button onclick="editor.setAspectRatio(1/1)" class="active" data-ratio="1/1">1:1</button>
|
||||
<button onclick="editor.setAspectRatio(4/3)" data-ratio="4/3">4:3</button>
|
||||
<button onclick="editor.setAspectRatio(16/9)" data-ratio="16/9">16:9</button>
|
||||
<button onclick="editor.setAspectRatio(NaN)" data-ratio="free">自由</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-group">
|
||||
<label><i class="fas fa-redo mr-1"></i>旋转</label>
|
||||
<div class="editor-toolbar">
|
||||
<button onclick="editor.rotate(-90)"><i class="fas fa-undo"></i> -90°</button>
|
||||
<button onclick="editor.rotate(90)"><i class="fas fa-redo"></i> +90°</button>
|
||||
<button onclick="editor.flipH()"><i class="fas fa-arrows-alt-h"></i></button>
|
||||
<button onclick="editor.flipV()"><i class="fas fa-arrows-alt-v"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-group">
|
||||
<label>亮度 <span id="brightness-val">0</span></label>
|
||||
<input type="range" id="brightness" min="-100" max="100" value="0" oninput="editor.updateFilter()">
|
||||
</div>
|
||||
<div class="editor-group">
|
||||
<label>对比度 <span id="contrast-val">0</span></label>
|
||||
<input type="range" id="contrast" min="-100" max="100" value="0" oninput="editor.updateFilter()">
|
||||
</div>
|
||||
<div class="editor-group">
|
||||
<label>饱和度 <span id="saturate-val">0</span></label>
|
||||
<input type="range" id="saturate" min="-100" max="100" value="0" oninput="editor.updateFilter()">
|
||||
</div>
|
||||
<div class="editor-group">
|
||||
<label>模糊 <span id="blur-val">0</span>px</label>
|
||||
<input type="range" id="blur" min="0" max="20" value="0" oninput="editor.updateFilter()">
|
||||
</div>
|
||||
<button onclick="editor.resetFilters()" class="text-sm text-blue-500 hover:text-blue-600">重置所有调整</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-footer">
|
||||
<button class="btn-cancel" onclick="editor.close()">取消</button>
|
||||
<button class="btn-save" id="editor-save" onclick="editor.save()"><i class="fas fa-save mr-1"></i>保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@endpush
|
||||
</x-app-layout>
|
||||
@@ -0,0 +1,210 @@
|
||||
@section('title', '我的 Token')
|
||||
|
||||
<x-app-layout>
|
||||
<div class="my-6 md:my-9">
|
||||
<div class="bg-white rounded-lg shadow-sm p-6 mb-6">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-lg font-semibold text-gray-800">🔑 我的 Token</h2>
|
||||
<span class="text-sm text-gray-500">共 {{ $totalTokens }} 个</span>
|
||||
</div>
|
||||
|
||||
{{-- 新建 Token 表单 --}}
|
||||
<div class="bg-gray-50 rounded-lg p-4 mb-6">
|
||||
<p class="text-sm font-medium text-gray-700 mb-3">快速创建 Token</p>
|
||||
<form id="create-token-form" class="flex items-center gap-2">
|
||||
@csrf
|
||||
<input type="text" name="name" placeholder="Token 名称(如 my-app)"
|
||||
class="flex-1 px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"
|
||||
required>
|
||||
<button type="submit" class="px-4 py-2 bg-green-500 text-white text-sm rounded-lg hover:bg-green-600">
|
||||
<i class="fas fa-plus mr-1"></i>创建
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{{-- 新创建 Token 显示 --}}
|
||||
<div id="new-token-box" class="hidden my-4 p-4 bg-green-50 border border-green-300 rounded-lg">
|
||||
<p class="text-sm font-semibold text-green-700 mb-2">
|
||||
<i class="fas fa-check-circle mr-1"></i>Token 创建成功!请立即复制保存,刷新页面后将无法再次查看:
|
||||
</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<code id="new-token-value" class="flex-1 p-3 bg-white border rounded text-sm text-gray-800 break-all font-mono"></code>
|
||||
<button onclick="copyToken()" class="px-4 py-2 bg-blue-500 text-white text-sm rounded-lg hover:bg-blue-600 whitespace-nowrap">
|
||||
<i class="fas fa-copy mr-1"></i>复制
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{{-- Token 列表 --}}
|
||||
@if($tokens->count() > 0)
|
||||
<div class="overflow-x-auto">
|
||||
<table class="min-w-full divide-y divide-gray-200">
|
||||
<thead class="bg-gray-50">
|
||||
<tr>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">名称</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">来源 IP</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Token</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">创建时间</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">最后使用</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="bg-white divide-y divide-gray-200">
|
||||
@foreach($tokens as $token)
|
||||
@php
|
||||
$name = $token->name;
|
||||
if (str_starts_with($name, 'hermes')) $source = 'Hermes Agent';
|
||||
elseif (str_starts_with($name, 'py-') || str_starts_with($name, 'script')) $source = 'Python/脚本';
|
||||
elseif (str_contains($name, 'smzdm')) $source = '值得买发布';
|
||||
elseif (str_contains($name, 'pub-')) $source = '自动发布脚本';
|
||||
elseif (filter_var($name, FILTER_VALIDATE_EMAIL)) $source = 'API接口(邮箱登录)';
|
||||
else $source = $name;
|
||||
@endphp
|
||||
<tr class="hover:bg-gray-50">
|
||||
<td class="px-4 py-3 whitespace-nowrap">
|
||||
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
|
||||
{{ str_starts_with($name, 'hermes') ? 'bg-purple-100 text-purple-700' :
|
||||
(filter_var($name, FILTER_VALIDATE_EMAIL) ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-700') }}">
|
||||
{{ $name }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500 font-mono">{{ $token->ip ?: '-' }}</td>
|
||||
<td class="px-4 py-3 text-sm text-gray-500 font-mono max-w-[200px]" title="{{ $token->plain_token ?: '旧Token无明文' }}">
|
||||
@if($token->plain_token)
|
||||
<span class="cursor-pointer hover:text-blue-500" onclick="copyPlainText('{{ $token->plain_token }}', this)">
|
||||
{{ substr($token->plain_token, 0, 16) }}...
|
||||
</span>
|
||||
@else
|
||||
<span class="text-gray-300">-</span>
|
||||
@endif
|
||||
</td>
|
||||
<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{{ $token->created_at->format('Y-m-d H:i') }}</td>
|
||||
<td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{{ $token->last_used_at ? $token->last_used_at->diffForHumans() : '从未使用' }}</td>
|
||||
<td class="px-4 py-3 whitespace-nowrap text-sm">
|
||||
<button onclick="deleteToken({{ $token->id }}, '{{ $name }}')" class="text-red-500 hover:text-red-700">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{{-- 分页 --}}
|
||||
@if($tokens->hasPages())
|
||||
<div class="mt-4 flex items-center justify-between">
|
||||
<div class="text-sm text-gray-500">
|
||||
显示 {{ $tokens->firstItem() }}-{{ $tokens->lastItem() }},共 {{ $totalTokens }} 个
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
@if($tokens->onFirstPage())
|
||||
<span class="px-3 py-1 text-sm text-gray-400 bg-gray-100 rounded cursor-not-allowed">上一页</span>
|
||||
@else
|
||||
<a href="{{ $tokens->previousPageUrl() }}" class="px-3 py-1 text-sm text-gray-600 bg-white border rounded hover:bg-gray-50">上一页</a>
|
||||
@endif
|
||||
|
||||
@foreach($tokens->getUrlRange(max(1, $tokens->currentPage() - 2), min($tokens->lastPage(), $tokens->currentPage() + 2)) as $page => $url)
|
||||
<a href="{{ $url }}" class="px-3 py-1 text-sm {{ $page == $tokens->currentPage() ? 'bg-blue-500 text-white' : 'text-gray-600 bg-white border hover:bg-gray-50' }} rounded">{{ $page }}</a>
|
||||
@endforeach
|
||||
|
||||
@if($tokens->hasMorePages())
|
||||
<a href="{{ $tokens->nextPageUrl() }}" class="px-3 py-1 text-sm text-gray-600 bg-white border rounded hover:bg-gray-50">下一页</a>
|
||||
@else
|
||||
<span class="px-3 py-1 text-sm text-gray-400 bg-gray-100 rounded cursor-not-allowed">下一页</span>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@else
|
||||
<p class="text-center text-gray-400 py-8">暂无 Token,请通过上方表单创建</p>
|
||||
@endif
|
||||
|
||||
{{-- 提示 --}}
|
||||
<div class="mt-6 p-3 bg-yellow-50 border-l-4 border-yellow-400 rounded text-sm text-gray-600">
|
||||
<p><i class="fas fa-info-circle mr-1"></i><b>注意</b>:Token 创建后仅在创建时显示明文,之后数据库中只保留哈希值。如需新 Token,请通过上方表单创建。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@push('scripts')
|
||||
<script>
|
||||
// 创建 Token
|
||||
document.getElementById('create-token-form').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
const form = this;
|
||||
const name = form.querySelector('[name="name"]').value;
|
||||
const csrf = form.querySelector('[name="_token"]').value;
|
||||
|
||||
fetch('{{ route("user.tokens.store") }}', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-CSRF-TOKEN': csrf,
|
||||
'Accept': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ name: name })
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.status) {
|
||||
document.getElementById('new-token-box').classList.remove('hidden');
|
||||
document.getElementById('new-token-value').textContent = data.data.token;
|
||||
form.querySelector('[name="name"]').value = '';
|
||||
// 刷新页面以更新列表
|
||||
setTimeout(() => location.reload(), 3000);
|
||||
} else {
|
||||
alert('创建失败: ' + (data.message || '未知错误'));
|
||||
}
|
||||
})
|
||||
.catch(err => alert('请求失败: ' + err));
|
||||
});
|
||||
|
||||
// 复制新 Token
|
||||
function copyToken() {
|
||||
const token = document.getElementById('new-token-value').textContent;
|
||||
navigator.clipboard.writeText(token).then(() => {
|
||||
const btn = event.target.closest('button');
|
||||
btn.innerHTML = '<i class="fas fa-check mr-1"></i>已复制';
|
||||
setTimeout(() => btn.innerHTML = '<i class="fas fa-copy mr-1"></i>复制', 1500);
|
||||
});
|
||||
}
|
||||
|
||||
// 复制明文 Token
|
||||
function copyPlainText(token, el) {
|
||||
navigator.clipboard.writeText(token).then(() => {
|
||||
const orig = el.textContent;
|
||||
el.textContent = '已复制!';
|
||||
el.classList.add('text-green-500');
|
||||
setTimeout(() => {
|
||||
el.textContent = orig;
|
||||
el.classList.remove('text-green-500');
|
||||
}, 1500);
|
||||
});
|
||||
}
|
||||
|
||||
// 删除 Token
|
||||
function deleteToken(id, name) {
|
||||
if (!confirm('确定要删除 Token "' + name + '" 吗?')) return;
|
||||
const csrf = '{{ csrf_token() }}';
|
||||
fetch('{{ route("user.tokens.destroy", "TOKEN_ID") }}'.replace('TOKEN_ID', id), {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'X-CSRF-TOKEN': csrf,
|
||||
'Accept': 'application/json',
|
||||
}
|
||||
})
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.status) {
|
||||
location.reload();
|
||||
} else {
|
||||
alert('删除失败: ' + (data.message || '未知错误'));
|
||||
}
|
||||
})
|
||||
.catch(err => alert('请求失败: ' + err));
|
||||
}
|
||||
</script>
|
||||
@endpush
|
||||
</x-app-layout>
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Web Routes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here is where you can register web routes for your application. These
|
||||
| routes are loaded by the RouteServiceProvider within a group which
|
||||
| contains the "web" middleware group. Now create something great!
|
||||
|
|
||||
*/
|
||||
|
||||
use App\Http\Middleware\CheckIsEnableApi;
|
||||
use App\Http\Middleware\CheckIsEnableGallery;
|
||||
use App\Http\Middleware\CheckIsEnableGuestUpload;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use App\Http\Middleware\CheckIsInstalled;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Controllers\User\UserController;
|
||||
use App\Http\Controllers\User\ImageController;
|
||||
use App\Http\Controllers\User\AlbumController;
|
||||
use App\Http\Controllers\User\TokenController;
|
||||
use App\Http\Controllers\User\AiController;
|
||||
use App\Http\Controllers\Common\GalleryController;
|
||||
use App\Http\Controllers\Common\ApiController;
|
||||
|
||||
use App\Http\Controllers\Admin\ConsoleController as AdminConsoleController;
|
||||
use App\Http\Controllers\Admin\GroupController as AdminGroupController;
|
||||
use App\Http\Controllers\Admin\StrategyController as AdminStrategyController;
|
||||
use App\Http\Controllers\Admin\UserController as AdminUserController;
|
||||
use App\Http\Controllers\Admin\SettingController as AdminSettingController;
|
||||
use App\Http\Controllers\Admin\ImageController as AdminImageController;
|
||||
|
||||
Route::get('/', fn () => view('welcome'))
|
||||
->name('/')
|
||||
->middleware(CheckIsInstalled::class)
|
||||
->middleware(CheckIsEnableGuestUpload::class);
|
||||
|
||||
Route::any('install', [Controller::class, 'install'])->name('install');
|
||||
Route::post('upload', [Controller::class, 'upload']);
|
||||
Route::group(['middleware' => ['auth']], function () {
|
||||
Route::get('dashboard', [UserController::class, 'dashboard'])->name('dashboard');
|
||||
Route::get('gallery', [GalleryController::class, 'index'])->middleware(CheckIsEnableGallery::class)->name('gallery');
|
||||
|
||||
Route::prefix('settings')->group(function () {
|
||||
Route::get('', [UserController::class, 'settings'])->name('settings');
|
||||
Route::put('', [UserController::class, 'update'])->name('settings.update');
|
||||
Route::put('set-strategy', [UserController::class, 'setStrategy'])->name('settings.strategy.set');
|
||||
});
|
||||
|
||||
Route::prefix('tokens')->group(function () {
|
||||
Route::get('', [TokenController::class, 'index'])->name('user.tokens');
|
||||
Route::post('', [TokenController::class, 'store'])->name('user.tokens.store');
|
||||
Route::delete('{id}', [TokenController::class, 'destroy'])->name('user.tokens.destroy');
|
||||
});
|
||||
|
||||
Route::prefix('ai')->group(function () {
|
||||
Route::get('', [AiController::class, 'index'])->name('ai');
|
||||
Route::post('process', [AiController::class, 'process'])->name('ai.process');
|
||||
Route::post('process-download', [AiController::class, 'processAndDownload'])->name('ai.process.download');
|
||||
Route::get('config', [AiController::class, 'config'])->name('ai.config');
|
||||
Route::post('config', [AiController::class, 'saveConfig'])->name('ai.config.save');
|
||||
Route::get('health', [AiController::class, 'health'])->name('ai.health');
|
||||
});
|
||||
Route::group([
|
||||
'prefix' => 'api',
|
||||
'middleware' => CheckIsEnableApi::class
|
||||
], function () {
|
||||
Route::match(['get', 'post'], '', [ApiController::class, 'index'])->name('api');
|
||||
});
|
||||
|
||||
Route::get('upload', fn () => view('user.upload'))->name('upload');
|
||||
Route::get('images', [ImageController::class, 'index'])->name('images');
|
||||
Route::group(['prefix' => 'user'], function () {
|
||||
Route::get('images', [ImageController::class, 'images'])->name('user.images');
|
||||
Route::get('images/{id}', [ImageController::class, 'image'])->name('user.image');
|
||||
Route::delete('images', [ImageController::class, 'delete'])->name('user.images.delete');
|
||||
Route::put('images/permission', [ImageController::class, 'permission'])->name('user.images.permission');
|
||||
Route::put('images/rename', [ImageController::class, 'rename'])->name('user.images.rename');
|
||||
Route::put('images/movement', [ImageController::class, 'movement'])->name('user.images.movement');
|
||||
Route::put('images/{id}/edit', [ImageController::class, 'edit'])->name('user.images.edit');
|
||||
Route::get('albums', [AlbumController::class, 'albums'])->name('user.albums');
|
||||
Route::post('albums', [AlbumController::class, 'create'])->name('user.album.create');
|
||||
Route::put('albums/{id}', [AlbumController::class, 'update'])->name('user.album.update');
|
||||
Route::delete('albums/{id}', [AlbumController::class, 'delete'])->name('user.album.delete');
|
||||
});
|
||||
});
|
||||
|
||||
Route::group(['prefix' => 'admin', 'middleware' => ['auth.admin']], function () {
|
||||
Route::get('console', [AdminConsoleController::class, 'index'])->name('admin.console');
|
||||
|
||||
Route::group(['prefix' => 'users'], function () {
|
||||
Route::get('', [AdminUserController::class, 'index'])->name('admin.users');
|
||||
Route::get('{id}', [AdminUserController::class, 'edit'])->name('admin.user.edit');
|
||||
Route::put('{id}', [AdminUserController::class, 'update'])->name('admin.user.update');
|
||||
Route::delete('{id}', [AdminUserController::class, 'delete'])->name('admin.user.delete');
|
||||
});
|
||||
|
||||
Route::group(['prefix' => 'images'], function () {
|
||||
Route::get('', [AdminImageController::class, 'index'])->name('admin.images');
|
||||
Route::put('{id}', [AdminImageController::class, 'update'])->name('admin.image.update');
|
||||
Route::delete('{id}', [AdminImageController::class, 'delete'])->name('admin.image.delete');
|
||||
});
|
||||
|
||||
Route::group(['prefix' => 'groups'], function () {
|
||||
Route::get('', [AdminGroupController::class, 'index'])->name('admin.groups');
|
||||
Route::get('create', [AdminGroupController::class, 'add'])->name('admin.group.add');
|
||||
Route::post('create', [AdminGroupController::class, 'create'])->name('admin.group.create');
|
||||
Route::get('{id}', [AdminGroupController::class, 'edit'])->name('admin.group.edit');
|
||||
Route::put('{id}', [AdminGroupController::class, 'update'])->name('admin.group.update');
|
||||
Route::delete('{id}', [AdminGroupController::class, 'delete'])->name('admin.group.delete');
|
||||
Route::delete('{id}/clear-cache', [AdminGroupController::class, 'clearCache'])->name('admin.group.cache.clear');
|
||||
});
|
||||
|
||||
Route::group(['prefix' => 'strategies'], function () {
|
||||
Route::get('', [AdminStrategyController::class, 'index'])->name('admin.strategies');
|
||||
Route::get('create', [AdminStrategyController::class, 'add'])->name('admin.strategy.add');
|
||||
Route::post('create', [AdminStrategyController::class, 'create'])->name('admin.strategy.create');
|
||||
Route::get('{id}', [AdminStrategyController::class, 'edit'])->name('admin.strategy.edit');
|
||||
Route::put('{id}', [AdminStrategyController::class, 'update'])->name('admin.strategy.update');
|
||||
Route::delete('{id}', [AdminStrategyController::class, 'delete'])->name('admin.strategy.delete');
|
||||
});
|
||||
|
||||
Route::group(['prefix' => 'settings'], function () {
|
||||
Route::get('', [AdminSettingController::class, 'index'])->name('admin.settings');
|
||||
Route::put('save', [AdminSettingController::class, 'save'])->name('admin.settings.save');
|
||||
Route::post('mail-test', [AdminSettingController::class, 'mailTest'])->name('admin.settings.mail.test');
|
||||
Route::get('check-update', [AdminSettingController::class, 'checkUpdate'])->name('admin.settings.check.update');
|
||||
Route::post('upgrade', [AdminSettingController::class, 'upgrade'])->name('admin.settings.upgrade');
|
||||
Route::get('upgrade/progress', [AdminSettingController::class, 'upgradeProgress'])->name('admin.settings.upgrade.progress');
|
||||
});
|
||||
|
||||
Route::group(['prefix' => 'directory-import'], function () {
|
||||
Route::get('', [\App\Http\Controllers\Admin\DirectoryImportController::class, 'index'])->name('admin.directory-import');
|
||||
Route::post('scan', [\App\Http\Controllers\Admin\DirectoryImportController::class, 'scan'])->name('admin.directory-import.scan');
|
||||
Route::post('import', [\App\Http\Controllers\Admin\DirectoryImportController::class, 'import'])->name('admin.directory-import.import');
|
||||
});
|
||||
});
|
||||
|
||||
require __DIR__.'/image.php';
|
||||
require __DIR__.'/auth.php';
|
||||
|
||||
Route::get('/health', function () {
|
||||
$storage = 0;
|
||||
try {
|
||||
$path = storage_path('app/uploads');
|
||||
$io = popen('/usr/bin/du -sb ' . escapeshellarg($path), 'r');
|
||||
if ($io) {
|
||||
$storage = (int)fgets($io);
|
||||
pclose($io);
|
||||
}
|
||||
} catch (\Exception $e) {}
|
||||
|
||||
return response()->json([
|
||||
'status' => 'ok',
|
||||
'time' => now()->toIso8601String(),
|
||||
'php_version' => PHP_VERSION,
|
||||
'laravel_version' => app()->version(),
|
||||
'storage_bytes' => $storage,
|
||||
]);
|
||||
});
|
||||
Reference in new issue
Block a user