From c4a59d68f87f737c5789e18ce96ebf3e75206cc9 Mon Sep 17 00:00:00 2001 From: ctexthuang Date: Thu, 31 Oct 2024 17:57:49 +0800 Subject: [PATCH] feat : oss callback --- app/Cache/Redis/Common/CommonRedisKey.php | 18 + app/Cache/Redis/RedisCache.php | 2 +- app/Controller/Admin/ConfigController.php | 3 +- app/Cron/Oss/OssDelByDisableTask.php | 23 ++ app/Cron/Oss/OssDelByOssIdTask.php | 23 ++ app/Cron/Oss/OssDelByUrlTask.php | 23 ++ app/Lib/Log.php | 14 + .../{ => Admin}/System/SystemService.php | 2 +- app/Service/Common/OssCallbackService.php | 311 ++++++++++++++++++ .../ServiceTrait/Common/AliStsTrait.php | 2 +- config/autoload/logger.php | 18 + sync/http/admin/address.http | 2 +- 12 files changed, 435 insertions(+), 6 deletions(-) create mode 100644 app/Cron/Oss/OssDelByDisableTask.php create mode 100644 app/Cron/Oss/OssDelByOssIdTask.php create mode 100644 app/Cron/Oss/OssDelByUrlTask.php rename app/Service/{ => Admin}/System/SystemService.php (97%) create mode 100644 app/Service/Common/OssCallbackService.php diff --git a/app/Cache/Redis/Common/CommonRedisKey.php b/app/Cache/Redis/Common/CommonRedisKey.php index 0f41907..4e64c48 100644 --- a/app/Cache/Redis/Common/CommonRedisKey.php +++ b/app/Cache/Redis/Common/CommonRedisKey.php @@ -12,4 +12,22 @@ class CommonRedisKey { return '__system:address:list:'.$type; } + + /** + * 待删除oss文件队列-根据url + * @return string + */ + public static function getDeleteOssImgListByUrl(): string + { + return '__system:deleteOssImgList:url'; + } + + /** + * 待删除oss文件队列-根据id + * @return string + */ + public static function getDeleteOssImgListByOssId(): string + { + return '__system:deleteOssImgList:oss_id'; + } } \ No newline at end of file diff --git a/app/Cache/Redis/RedisCache.php b/app/Cache/Redis/RedisCache.php index eb01c87..9784d94 100644 --- a/app/Cache/Redis/RedisCache.php +++ b/app/Cache/Redis/RedisCache.php @@ -421,7 +421,7 @@ class RedisCache * @throws NotFoundExceptionInterface * @throws RedisException */ - public function lPush(string $key, string $data, string $poolName = 'default') + public function lPush(string $key, string $data, string $poolName = 'default'): false|int|Redis { return $this->getRedis($poolName)->lPush($key, $data); } diff --git a/app/Controller/Admin/ConfigController.php b/app/Controller/Admin/ConfigController.php index e3cc0b3..f864b04 100644 --- a/app/Controller/Admin/ConfigController.php +++ b/app/Controller/Admin/ConfigController.php @@ -7,11 +7,10 @@ namespace App\Controller\Admin; use App\Controller\AbstractController; use App\Middleware\Admin\JwtAuthMiddleware; use App\Service\Admin\System\ConfigService; -use App\Service\System\SystemService; +use App\Service\Admin\System\SystemService; use Hyperf\HttpServer\Annotation\Controller; use Hyperf\HttpServer\Annotation\Middlewares; use Hyperf\HttpServer\Annotation\RequestMapping; -use Hyperf\Validation\Annotation\Scene; use Psr\Container\ContainerExceptionInterface; use Psr\Container\NotFoundExceptionInterface; use RedisException; diff --git a/app/Cron/Oss/OssDelByDisableTask.php b/app/Cron/Oss/OssDelByDisableTask.php new file mode 100644 index 0000000..bf15a2f --- /dev/null +++ b/app/Cron/Oss/OssDelByDisableTask.php @@ -0,0 +1,23 @@ +getLogger($name,$group)->error($msg,$content); } + /** + * callback 请求日志 + * @param $msg + * @param string $name + * @param string $group + * @return void + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + function callbackLog($msg, string $name = 'info', string $group = 'callback'): void + { + $this->getLogger($name,$group)->info($msg); + } + /** * admin 请求日志 * @param $msg diff --git a/app/Service/System/SystemService.php b/app/Service/Admin/System/SystemService.php similarity index 97% rename from app/Service/System/SystemService.php rename to app/Service/Admin/System/SystemService.php index 242fc5d..ed599f2 100644 --- a/app/Service/System/SystemService.php +++ b/app/Service/Admin/System/SystemService.php @@ -8,7 +8,7 @@ declare(strict_types=1); -namespace App\Service\System; +namespace App\Service\Admin\System; use App\Cache\Redis\Common\CityCache; use App\Constants\Common\CityCode; diff --git a/app/Service/Common/OssCallbackService.php b/app/Service/Common/OssCallbackService.php new file mode 100644 index 0000000..7bcb1c7 --- /dev/null +++ b/app/Service/Common/OssCallbackService.php @@ -0,0 +1,311 @@ +ossClient = new OssClient( + config('ali.access_key_id'), + config('ali.access_key_secret'), + config('oss.sts_endpoint') + ); + + $this->bucket = config('ali.bucket'); + } + + /** + * @return array + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws \RedisException + */ + public function process(): array + { + try { + //记录回调内容 + $this->filePutContents(); + + //检测直传type + $this->checkType(); + + //检测文件格式 + $this->checkMimeType(); + + //获取新文件名 + $this->getNewFileName(); + + //复制旧文件到指定文件夹 + try { + $this->ossClient->copyObject($this->bucket, urldecode($this->data['object']), $this->bucket, $this->newObjectPath); + } catch (OssException $e) { + throw new Exception($e->getMessage()); + } + + date_default_timezone_set('Asia/Shanghai'); + + //增加oss object数据 + $this->addOssObjectData(); + + //删除旧的文件 + $this->deleteOssObject(); + + }catch (Exception $exception){ + $this->deleteOssObject(); + throw new AdminException($exception->getMessage()); + } + + $this->log->callbackLog(__CLASS__.':oss回调完成'.json_encode($this->data),'oss'); + + return $this->adminReturn->success('上传成功',[ + 'id' => $this->newId, + 'url' => config('ali.oss_url') . $this->newObjectPath, 'old_file_name' => $this->fileName + ]); + } + + /** + * 记录回调内容 + * @return void + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + private function filePutContents(): void + { + + $this->data = $this->request->all(); + + $this->log->callbackLog(__CLASS__.':oss回调'.json_encode($this->data),'oss'); + } + + /** + * 检测直传type + * @return void + * @throws Exception + */ + private function checkType(): void + { + if (!in_array($this->data['type'], $this->allowType)) { + throw new Exception('上传类型错误'); + } + } + + + /** + * 检测文件格式 + * @return void + * @throws Exception + */ + private function checkMimeType(): void + { + $mimeType = explode('/', $this->data['mimeType']); + + switch ($this->data['mimeType']) { + case 'text/plain': + if ($mimeType[0] != 'text') { + throw new Exception("不允许此格式文件"); + } + $this->mimeType = 'txt'; + break; + default: + if (!in_array($mimeType[1], ['mp3', 'jpeg', 'jpg', 'png', 'gif', 'mp4', 'mpeg','aac', 'quicktime'])) { + throw new Exception("不允许此格式文件"); + } + $this->mimeType = $mimeType[1]; + } + } + + /** + * 获取新文件名 + * @return void + */ + private function getNewFileName(): void + { + + $this->fileName = explode('/', urldecode($this->data['object']))[1]; + + switch ($this->data['type']) + { + case 'video_main': + $newFileName = date('YmdHis').md5($this->data['type'].$this->fileName); + $this->newObjectPath = sprintf("upload/%s/%s/%s/%s.%s", 'admin', $this->data['type'], $this->data['library_dir'],$newFileName,$this->mimeType); + break; + case 'avatar': + $newFileName = date('YmdHis').md5($this->data['type'].$this->fileName); + $this->newObjectPath = sprintf("upload/%s/%s/%s/%s.%s", 'user', $this->data['user_id'], $this->data['type'],$newFileName,$this->mimeType); + break; + default: + $newFileName = md5(date('YmdHis').$this->data['type'].$this->fileName); + + $newMimeType = $this->mimeType; + if ($this->mimeType == 'quicktime') { + $newMimeType = 'mov'; + } + + $this->newObjectPath = sprintf("upload/%s/%s/%s.%s",'admin', $this->data['type'], $newFileName,$newMimeType); + break; + } + } + + /** + * 增加oss object数据 + * @return void + */ + private function addOssObjectData(): void + { + $type = 0; + switch ($this->mimeType) { + case 'jpg': + case 'jpeg': + case 'png': + case 'bmp': + $type = 1; + break; + case 'mp3': + $type = 2; + break; + case 'mp4': + case 'swf': + $type = 3; + break; + } + +// $ossObjectModel = new OssObject(); +// +// $ossObjectModel->url = $this->newObjectPath; +//// $ossObjectModel->url = urldecode($this->data['object']); +// $ossObjectModel->width = $this->data['imageInfo_width'] ?? 0; +// $ossObjectModel->height = $this->data['imageInfo_height'] ?? 0; +// $ossObjectModel->audio_second = $this->data['audio_second'] ?? 0; +// $ossObjectModel->video_duration = $this->data['video_duration'] ?? 0; +// $ossObjectModel->size = $this->data['size'] ?? 0; +// +// $ossObjectModel->type = $type; +// +// if (!$ossObjectModel->save()){ +// throw new AdminException('保存图片失败'); +// } + +// $this->newId = $ossObjectModel->id; + } + + /** + * @return void + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws \RedisException + */ + private function deleteOssObject(): void + { + //删除旧的文件 + $this->redisCache->lPush(CommonRedisKey::getDeleteOssImgListByUrl(), $this->data['object']); + } + +} \ No newline at end of file diff --git a/app/Service/ServiceTrait/Common/AliStsTrait.php b/app/Service/ServiceTrait/Common/AliStsTrait.php index 412ef62..4419c58 100644 --- a/app/Service/ServiceTrait/Common/AliStsTrait.php +++ b/app/Service/ServiceTrait/Common/AliStsTrait.php @@ -52,7 +52,7 @@ trait AliStsTrait * @throws NotFoundExceptionInterface */ public function getAliStsControls($payload){ - $client = self::createClient(); + $client = $this->createClient(); $assumeRoleRequest = new AssumeRoleRequest($payload); $runtime = new RuntimeOptions([]); try { diff --git a/config/autoload/logger.php b/config/autoload/logger.php index 76c8f9f..498befe 100644 --- a/config/autoload/logger.php +++ b/config/autoload/logger.php @@ -99,4 +99,22 @@ return [ ], ], ], + 'callback' => [ + 'handler' => [ + 'class' => Monolog\Handler\RotatingFileHandler::class, + 'constructor' => [ + 'filename' => BASE_PATH . '/runtime/logs/callback/hyperf.log', + 'level' => Monolog\Logger::DEBUG, + ], + ], + 'formatter' => [ + 'class' => Monolog\Formatter\LineFormatter::class, + 'constructor' => [ + 'format' => null, + 'dateFormat' => null, + 'allowInlineLineBreaks' => true, + 'ignoreEmptyContextAndExtra' => true, + ], + ], + ], ]; diff --git a/sync/http/admin/address.http b/sync/http/admin/address.http index 8546bd4..b12b1cd 100644 --- a/sync/http/admin/address.http +++ b/sync/http/admin/address.http @@ -37,7 +37,7 @@ Content-Type: application/json Authorization: Bearer {{admin_token}} ###城市列表 - 联表数据 -GET {{host}}/admin/config/system/address_list?deep=1&pid=82 +GET {{host}}/admin/config/system/address_list?deep=1&pid=14 Content-Type: application/json Authorization: Bearer {{admin_token}}