commit d40381cd01a60347c33ed84ddc60c3060d0a797f Author: personal82555 Date: Thu Oct 22 11:58:05 2026 +0800 feat: OCR图片搜索 + 图片编辑器 + Token管理 新增功能: - OCR图片内容搜索 (Tesseract + 中文支持) - 图片编辑器 (裁剪/旋转/亮度/对比度/饱和度/模糊) - 独立Token管理页面 Bug修复: - 修复图片显示和交互问题 - 修复相册计数不准确 - 修复搜索过滤逻辑 详细变更见 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4e067d2 --- /dev/null +++ b/CHANGELOG.md @@ -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` — 新增路由 diff --git a/app/Http/Controllers/User/AlbumController.php b/app/Http/Controllers/User/AlbumController.php new file mode 100644 index 0000000..35058fc --- /dev/null +++ b/app/Http/Controllers/User/AlbumController.php @@ -0,0 +1,70 @@ +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('删除成功'); + } +} diff --git a/app/Http/Controllers/User/ImageController.php b/app/Http/Controllers/User/ImageController.php new file mode 100644 index 0000000..558d5a4 --- /dev/null +++ b/app/Http/Controllers/User/ImageController.php @@ -0,0 +1,184 @@ +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('删除成功'); + } +} diff --git a/app/Http/Controllers/User/TokenController.php b/app/Http/Controllers/User/TokenController.php new file mode 100644 index 0000000..e72698a --- /dev/null +++ b/app/Http/Controllers/User/TokenController.php @@ -0,0 +1,52 @@ +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 不存在'); + } +} diff --git a/app/Models/Album.php b/app/Models/Album.php new file mode 100644 index 0000000..a5e881d --- /dev/null +++ b/app/Models/Album.php @@ -0,0 +1,75 @@ + '', + ]; + + 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'); + } +} diff --git a/app/Models/Image.php b/app/Models/Image.php new file mode 100644 index 0000000..405fc62 --- /dev/null +++ b/app/Models/Image.php @@ -0,0 +1,257 @@ + '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' => "![{$this->origin_name}]({$this->url})", + 'markdown_with_link' => "[![{$this->origin_name}]({$this->url})]({$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; + } +} diff --git a/app/Services/ImageService.php b/app/Services/ImageService.php new file mode 100644 index 0000000..16d3e21 --- /dev/null +++ b/app/Services/ImageService.php @@ -0,0 +1,661 @@ +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); + } +} diff --git a/app/Services/OcrService.php b/app/Services/OcrService.php new file mode 100644 index 0000000..2470a05 --- /dev/null +++ b/app/Services/OcrService.php @@ -0,0 +1,154 @@ + \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', + }; + } +} diff --git a/database/migrations/2026_07_01_191052_add_ocr_text_to_images_table.php b/database/migrations/2026_07_01_191052_add_ocr_text_to_images_table.php new file mode 100644 index 0000000..cf59077 --- /dev/null +++ b/database/migrations/2026_07_01_191052_add_ocr_text_to_images_table.php @@ -0,0 +1,22 @@ +text('ocr_text')->nullable()->after('origin_name'); + }); + } + + public function down() + { + Schema::table('images', function (Blueprint $table) { + $table->dropColumn('ocr_text'); + }); + } +}; diff --git a/public/js/cropper/cropper.min.css b/public/js/cropper/cropper.min.css new file mode 100644 index 0000000..049cab5 --- /dev/null +++ b/public/js/cropper/cropper.min.css @@ -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} \ No newline at end of file diff --git a/public/js/cropper/cropper.min.js b/public/js/cropper/cropper.min.js new file mode 100644 index 0000000..959d89f --- /dev/null +++ b/public/js/cropper/cropper.min.js @@ -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;tt.length)&&(e=t.length);for(var i=0,a=new Array(e);it.width?3===i?o=t.height*e:h=t.width/e:3===i?h=t.width/e:o=t.height*e,{aspectRatio:e,naturalWidth:n,naturalHeight:a,width:o,height:h});this.canvasData=e,this.limited=1===i||2===i,this.limitCanvas(!0,!0),e.width=Math.min(Math.max(e.width,e.minWidth),e.maxWidth),e.height=Math.min(Math.max(e.height,e.minHeight),e.maxHeight),e.left=(t.width-e.width)/2,e.top=(t.height-e.height)/2,e.oldLeft=e.left,e.oldTop=e.top,this.initialCanvasData=g({},e)},limitCanvas:function(t,e){var i=this.options,a=this.containerData,n=this.canvasData,o=this.cropBoxData,h=i.viewMode,r=n.aspectRatio,s=this.cropped&&o;t&&(t=Number(i.minCanvasWidth)||0,i=Number(i.minCanvasHeight)||0,1=a.width&&(n.minLeft=Math.min(0,r),n.maxLeft=Math.max(0,r)),n.height>=a.height)&&(n.minTop=Math.min(0,t),n.maxTop=Math.max(0,t))):(n.minLeft=-n.width,n.minTop=-n.height,n.maxLeft=a.width,n.maxTop=a.height))},renderCanvas:function(t,e){var i,a,n,o,h=this.canvasData,r=this.imageData;e&&(e={width:r.naturalWidth*Math.abs(r.scaleX||1),height:r.naturalHeight*Math.abs(r.scaleY||1),degree:r.rotate||0},r=e.width,o=e.height,e=e.degree,i=90==(e=Math.abs(e)%180)?{width:o,height:r}:(a=e%90*Math.PI/180,i=Math.sin(a),n=r*(a=Math.cos(a))+o*i,r=r*i+o*a,90h.maxWidth||h.widthh.maxHeight||h.heighte.width?a.height=a.width/i:a.width=a.height*i),this.cropBoxData=a,this.limitCropBox(!0,!0),a.width=Math.min(Math.max(a.width,a.minWidth),a.maxWidth),a.height=Math.min(Math.max(a.height,a.minHeight),a.maxHeight),a.width=Math.max(a.minWidth,a.width*t),a.height=Math.max(a.minHeight,a.height*t),a.left=e.left+(e.width-a.width)/2,a.top=e.top+(e.height-a.height)/2,a.oldLeft=a.left,a.oldTop=a.top,this.initialCropBoxData=g({},a)},limitCropBox:function(t,e){var i,a,n=this.options,o=this.containerData,h=this.canvasData,r=this.cropBoxData,s=this.limited,c=n.aspectRatio;t&&(t=Number(n.minCropBoxWidth)||0,n=Number(n.minCropBoxHeight)||0,i=s?Math.min(o.width,h.width,h.width+h.left,o.width-h.left):o.width,a=s?Math.min(o.height,h.height,h.height+h.top,o.height-h.top):o.height,t=Math.min(t,o.width),n=Math.min(n,o.height),c&&(t&&n?ti.maxWidth||i.widthi.maxHeight||i.height=e.width&&i.height>=e.height?q:I),f(this.cropBox,g({width:i.width,height:i.height},x({translateX:i.left,translateY:i.top}))),this.cropped&&this.limited&&this.limitCanvas(!0,!0),this.disabled||this.output()},output:function(){this.preview(),y(this.element,tt,this.getData())}},i={initPreview:function(){var t=this.element,i=this.crossOrigin,e=this.options.preview,a=i?this.crossOriginUrl:this.url,n=t.alt||"The image to preview",o=document.createElement("img");i&&(o.crossOrigin=i),o.src=a,o.alt=n,this.viewBox.appendChild(o),this.viewBoxImage=o,e&&("string"==typeof(o=e)?o=t.ownerDocument.querySelectorAll(e):e.querySelector&&(o=[e]),z(this.previews=o,function(t){var e=document.createElement("img");w(t,m,{width:t.offsetWidth,height:t.offsetHeight,html:t.innerHTML}),i&&(e.crossOrigin=i),e.src=a,e.alt=n,e.style.cssText='display:block;width:100%;height:auto;min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;image-orientation:0deg!important;"',t.innerHTML="",t.appendChild(e)}))},resetPreview:function(){z(this.previews,function(e){var i=Bt(e,m),i=(f(e,{width:i.width,height:i.height}),e.innerHTML=i.html,e),e=m;if(o(i[e]))try{delete i[e]}catch(t){i[e]=void 0}else if(i.dataset)try{delete i.dataset[e]}catch(t){i.dataset[e]=void 0}else i.removeAttribute("data-".concat(Dt(e)))})},preview:function(){var h=this.imageData,t=this.canvasData,e=this.cropBoxData,r=e.width,s=e.height,c=h.width,d=h.height,l=e.left-t.left-h.left,p=e.top-t.top-h.top;this.cropped&&!this.disabled&&(f(this.viewBoxImage,g({width:c,height:d},x(g({translateX:-l,translateY:-p},h)))),z(this.previews,function(t){var e=Bt(t,m),i=e.width,e=e.height,a=i,n=e,o=1;r&&(n=s*(o=i/r)),s&&eMath.abs(a-1)?i:a)&&(t.restore&&(o=this.getCanvasData(),h=this.getCropBoxData()),this.render(),t.restore)&&(this.setCanvasData(z(o,function(t,e){o[e]=t*n})),this.setCropBoxData(z(h,function(t,e){h[e]=t*n}))))},dblclick:function(){var t,e;this.disabled||this.options.dragMode===_||this.setDragMode((t=this.dragBox,e=Q,(t.classList?t.classList.contains(e):-1y&&(D.x=y-f);break;case k:p+D.xx&&(D.y=x-v)}}var i,a,o,n=this.options,h=this.canvasData,r=this.containerData,s=this.cropBoxData,c=this.pointers,d=this.action,l=n.aspectRatio,p=s.left,m=s.top,u=s.width,g=s.height,f=p+u,v=m+g,w=0,b=0,y=r.width,x=r.height,M=!0,C=(!l&&t.shiftKey&&(l=u&&g?u/g:1),this.limited&&(w=s.minLeft,b=s.minTop,y=w+Math.min(r.width,h.width,h.left+h.width),x=b+Math.min(r.height,h.height,h.top+h.height)),c[Object.keys(c)[0]]),D={x:C.endX-C.startX,y:C.endY-C.startY};switch(d){case I:p+=D.x,m+=D.y;break;case B:0<=D.x&&(y<=f||l&&(m<=b||x<=v))?M=!1:(e(B),(u+=D.x)<0&&(d=k,p-=u=-u),l&&(m+=(s.height-(g=u/l))/2));break;case T:D.y<=0&&(m<=b||l&&(p<=w||y<=f))?M=!1:(e(T),g-=D.y,m+=D.y,g<0&&(d=O,m-=g=-g),l&&(p+=(s.width-(u=g*l))/2));break;case k:D.x<=0&&(p<=w||l&&(m<=b||x<=v))?M=!1:(e(k),u-=D.x,p+=D.x,u<0&&(d=B,p-=u=-u),l&&(m+=(s.height-(g=u/l))/2));break;case O:0<=D.y&&(x<=v||l&&(p<=w||y<=f))?M=!1:(e(O),(g+=D.y)<0&&(d=T,m-=g=-g),l&&(p+=(s.width-(u=g*l))/2));break;case E:if(l){if(D.y<=0&&(m<=b||y<=f)){M=!1;break}e(T),g-=D.y,m+=D.y,u=g*l}else e(T),e(B),!(0<=D.x)||fMath.abs(o)&&(o=i)})}),o),t),M=!1;break;case U:D.x&&D.y?(i=Wt(this.cropper),p=C.startX-i.left,m=C.startY-i.top,u=s.minWidth,g=s.minHeight,0 or element.");this.element=t,this.options=g({},ut,u(e)&&e),this.cropped=!1,this.disabled=!1,this.pointers={},this.ready=!1,this.reloading=!1,this.replaced=!1,this.sized=!1,this.sizing=!1,this.init()}var t,e,i;return t=n,i=[{key:"noConflict",value:function(){return window.Cropper=Pt,n}},{key:"setDefaults",value:function(t){g(ut,u(t)&&t)}}],(e=[{key:"init",value:function(){var t,e=this.element,i=e.tagName.toLowerCase();if(!e[c]){if(e[c]=this,"img"===i){if(this.isImg=!0,t=e.getAttribute("src")||"",!(this.originalUrl=t))return;t=e.src}else"canvas"===i&&window.HTMLCanvasElement&&(t=e.toDataURL());this.load(t)}}},{key:"load",value:function(t){var e,i,a,n,o,h,r=this;t&&(this.url=t,this.imageData={},e=this.element,(i=this.options).rotatable||i.scalable||(i.checkOrientation=!1),i.checkOrientation&&window.ArrayBuffer?lt.test(t)?pt.test(t)?this.read((h=(h=t).replace(Xt,""),a=atob(h),h=new ArrayBuffer(a.length),z(n=new Uint8Array(h),function(t,e){n[e]=a.charCodeAt(e)}),h)):this.clone():(o=new XMLHttpRequest,h=this.clone.bind(this),this.reloading=!0,(this.xhr=o).onabort=h,o.onerror=h,o.ontimeout=h,o.onprogress=function(){o.getResponseHeader("content-type")!==ct&&o.abort()},o.onload=function(){r.read(o.response)},o.onloadend=function(){r.reloading=!1,r.xhr=null},i.checkCrossOrigin&&Lt(t)&&e.crossOrigin&&(t=zt(t)),o.open("GET",t,!0),o.responseType="arraybuffer",o.withCredentials="use-credentials"===e.crossOrigin,o.send()):this.clone())}},{key:"read",value:function(t){var e=this.options,i=this.imageData,a=Rt(t),n=0,o=1,h=1;1
',o=(n=n.querySelector(".".concat(c,"-container"))).querySelector(".".concat(c,"-canvas")),h=n.querySelector(".".concat(c,"-drag-box")),s=(r=n.querySelector(".".concat(c,"-crop-box"))).querySelector(".".concat(c,"-face")),this.container=a,this.cropper=n,this.canvas=o,this.dragBox=h,this.cropBox=r,this.viewBox=n.querySelector(".".concat(c,"-view-box")),this.face=s,o.appendChild(i),v(t,L),a.insertBefore(n,t.nextSibling),X(i,Z),this.initPreview(),this.bind(),e.initialAspectRatio=Math.max(0,e.initialAspectRatio)||NaN,e.aspectRatio=Math.max(0,e.aspectRatio)||NaN,e.viewMode=Math.max(0,Math.min(3,Math.round(e.viewMode)))||0,v(r,L),e.guides||v(r.getElementsByClassName("".concat(c,"-dashed")),L),e.center||v(r.getElementsByClassName("".concat(c,"-center")),L),e.background&&v(n,"".concat(c,"-bg")),e.highlight||v(s,G),e.cropBoxMovable&&(v(s,V),w(s,d,I)),e.cropBoxResizable||(v(r.getElementsByClassName("".concat(c,"-line")),L),v(r.getElementsByClassName("".concat(c,"-point")),L)),this.render(),this.ready=!0,this.setDragMode(e.dragMode),e.autoCrop&&this.crop(),this.setData(e.data),l(e.ready)&&b(t,"ready",e.ready,{once:!0}),y(t,"ready"))}},{key:"unbuild",value:function(){var t;this.ready&&(this.ready=!1,this.unbind(),this.resetPreview(),(t=this.cropper.parentNode)&&t.removeChild(this.cropper),X(this.element,L))}},{key:"uncreate",value:function(){this.ready?(this.unbuild(),this.ready=!1,this.cropped=!1):this.sizing?(this.sizingImage.onload=null,this.sizing=!1,this.sized=!1):this.reloading?(this.xhr.onabort=null,this.xhr.abort()):this.image&&this.stop()}}])&&j(t.prototype,e),i&&j(t,i),Object.defineProperty(t,"prototype",{writable:!1}),n}();return g(It.prototype,t,i,e,St,jt,At),It}); \ No newline at end of file diff --git a/resources/views/user/images.blade.php b/resources/views/user/images.blade.php new file mode 100644 index 0000000..285f8b4 --- /dev/null +++ b/resources/views/user/images.blade.php @@ -0,0 +1,985 @@ +@section('title', '我的图片') + +@push('styles') + + + + +@endpush + + +
+
+ +
+ + + + + + + 刷新 + + + + + + + + + + +
+
+
+ + + + + 最新 + + + + + + 最新 + + 最早 + + 最大 + + 最小 + + + + + + + 全部 + + + + + + 全部 + + 公开 + + 私有 + + + +
+
+
+ +
+
+ 相册 + + + +
+
+ +
加载中...
+
+
+ + +
+ +
+
+
+ + +
+
+ + +
+
+
+
+
+ + + + + + + + + + + + @push('scripts') + + + + + + + + + + + +
+
+
+

编辑图片

+ +
+
+
+ 编辑中 +
+
+
+ +
+ + + + +
+
+
+ +
+ + + + +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+
+ +
+
+ + @endpush +
diff --git a/resources/views/user/tokens.blade.php b/resources/views/user/tokens.blade.php new file mode 100644 index 0000000..89535a6 --- /dev/null +++ b/resources/views/user/tokens.blade.php @@ -0,0 +1,210 @@ +@section('title', '我的 Token') + + +
+
+
+

🔑 我的 Token

+ 共 {{ $totalTokens }} 个 +
+ + {{-- 新建 Token 表单 --}} +
+

快速创建 Token

+
+ @csrf + + +
+
+ + {{-- 新创建 Token 显示 --}} + + + {{-- Token 列表 --}} + @if($tokens->count() > 0) +
+ + + + + + + + + + + + + @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 + + + + + + + + + @endforeach + +
名称来源 IPToken创建时间最后使用操作
+ + {{ $name }} + + {{ $token->ip ?: '-' }} + @if($token->plain_token) + + {{ substr($token->plain_token, 0, 16) }}... + + @else + - + @endif + {{ $token->created_at->format('Y-m-d H:i') }}{{ $token->last_used_at ? $token->last_used_at->diffForHumans() : '从未使用' }} + +
+
+ + {{-- 分页 --}} + @if($tokens->hasPages()) +
+
+ 显示 {{ $tokens->firstItem() }}-{{ $tokens->lastItem() }},共 {{ $totalTokens }} 个 +
+
+ @if($tokens->onFirstPage()) + 上一页 + @else + 上一页 + @endif + + @foreach($tokens->getUrlRange(max(1, $tokens->currentPage() - 2), min($tokens->lastPage(), $tokens->currentPage() + 2)) as $page => $url) + {{ $page }} + @endforeach + + @if($tokens->hasMorePages()) + 下一页 + @else + 下一页 + @endif +
+
+ @endif + + @else +

暂无 Token,请通过上方表单创建

+ @endif + + {{-- 提示 --}} +
+

注意:Token 创建后仅在创建时显示明文,之后数据库中只保留哈希值。如需新 Token,请通过上方表单创建。

+
+
+
+ + @push('scripts') + + @endpush +
diff --git a/routes/web.php b/routes/web.php new file mode 100644 index 0000000..17757fc --- /dev/null +++ b/routes/web.php @@ -0,0 +1,162 @@ + 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, + ]); +});