diff --git a/app/Http/Controllers/Api/FileController.php b/app/Http/Controllers/Api/FileController.php index c058f4900..d04444912 100755 --- a/app/Http/Controllers/Api/FileController.php +++ b/app/Http/Controllers/Api/FileController.php @@ -257,6 +257,7 @@ class FileController extends AbstractController 'userid' => $userid, 'created_id' => $user->userid, ]); + $file->checkName(); $file->saveBeforePids(); // $data = File::find($file->id); @@ -307,6 +308,7 @@ class FileController extends AbstractController 'userid' => $userid, 'created_id' => $user->userid, ]); + $file->checkName(); $data = AbstractModel::transaction(function() use ($file) { $content = FileContent::select(['content', 'text', 'size'])->whereFid($file->cid)->orderByDesc('id')->first(); $file->size = $content?->size ?: 0; @@ -383,6 +385,7 @@ class FileController extends AbstractController } // $file->pid = $pid; + $file->checkName(); $file->saveBeforePids(); $files[] = $file; } @@ -692,6 +695,7 @@ class FileController extends AbstractController 'userid' => $userid, 'created_id' => $user->userid, ]); + $dirRow->checkName(); if ($dirRow->saveBeforePids()) { $addItem[] = File::find($dirRow->id); } @@ -758,6 +762,7 @@ class FileController extends AbstractController 'userid' => $userid, 'created_id' => $user->userid, ]); + $file->checkName(); // 开始创建 return AbstractModel::transaction(function () use ($addItem, $webkitRelativePath, $type, $user, $data, $file) { $file->size = $data['size'] * 1024; diff --git a/app/Models/File.php b/app/Models/File.php index 006e37c5f..5f5f567b6 100644 --- a/app/Models/File.php +++ b/app/Models/File.php @@ -197,6 +197,35 @@ class File extends AbstractModel return true; } + /** + * 检查文件名 + * @param boolean $rename 重复是否自动重命名 + * @return bool + */ + public function checkName($rename = true) + { + $exist = self::wherePid($this->pid)->whereUserid($this->userid)->whereName($this->name)->exists(); + if (!$exist) { + return true; // 未重名 + } + if (!$rename) { + return false; // 重名不需要自动重命名 + } + // 自动重命名 + $nextNum = 2; + if (preg_match("/(.*?)(\s+\(\d+\))*$/", $this->name)) { + $preName = preg_replace("/(.*?)(\s+\(\d+\))*$/", "$1", $this->name); + $nextNum = self::wherePid($this->pid)->whereUserid($this->userid)->where("name", "LIKE", "{$preName}%")->count() + 1; + } + $newName = "{$this->name} ({$nextNum})"; + if (self::wherePid($this->pid)->whereUserid($this->userid)->whereName($newName)->exists()) { + $nextNum = rand(100, 9999); + $newName = "{$this->name} ({$nextNum})"; + } + $this->name = $newName; + return true; + } + /** * 保存前更新pids * @return bool @@ -475,6 +504,7 @@ class File extends AbstractModel 'userid' => $newUserid, 'created_id' => 0, ]); + $file->checkName(); $file->saveBeforePids(); // 移交文件