- 新增阿里云OSS SDK核心类库文件 - 新增OSS插件配置文件及钩子监听 - 新增分类图标SVG资源并优化为轻量化格式 - 替换定位接口为天地图逆地理编码接口 - 新增OSS图片缩略处理工具方法
206 行
8.1 KiB
PHP
206 行
8.1 KiB
PHP
<?php
|
||
|
||
namespace app\admin\command;
|
||
|
||
use addons\alioss\library\Auth;
|
||
use app\common\model\Attachment;
|
||
use OSS\Core\OssException;
|
||
use OSS\Credentials\StaticCredentialsProvider;
|
||
use OSS\OssClient;
|
||
use think\Config;
|
||
use think\console\Command;
|
||
use think\console\Input;
|
||
use think\console\Output;
|
||
use think\Db;
|
||
use think\Loader;
|
||
|
||
/**
|
||
* 分类图片批量入库命令
|
||
*
|
||
* 流程(完全等同于 alioss 插件 serverbackup=0 模式下的 HTTP 上传):
|
||
* 1. 本地已有图片(PowerShell 生图脚本下载到 tmp_img/downloaded/{id}.jpg)
|
||
* 2. 按 savekey 规则(/uploads/{year}{mon}{day}/{filemd5}.suffix)move 到 ROOT_PATH/public 下
|
||
* 3. 用 Upload 类标准参数写 fa_attachment(storage=local)
|
||
* 4. OssClient::uploadFile 推 OSS
|
||
* 5. 删除本地文件 + 删除 local attachment 记录 + 新增 storage=alioss 的 attachment 记录
|
||
* 6. 更新 fa_fc_category.image 字段
|
||
*
|
||
* 用法:
|
||
* php think fc:category-images
|
||
*
|
||
* 前置:tmp_img/downloaded/{id}.jpg 已全部生成
|
||
*/
|
||
class FcCategoryImages extends Command
|
||
{
|
||
protected function configure()
|
||
{
|
||
$this->setName('fc:category-images')
|
||
->setDescription('批量入库分类 AI 配图(本地→OSS→附件表→分类表)');
|
||
}
|
||
|
||
protected function execute(Input $input, Output $output)
|
||
{
|
||
$downloadDir = ROOT_PATH . 'tmp_img' . DS . 'downloaded';
|
||
if (!is_dir($downloadDir)) {
|
||
$output->error("找不到图片目录: $downloadDir");
|
||
return 1;
|
||
}
|
||
|
||
// 1. 初始化 OSS(手动注册 addons/alioss OSS 命名空间,console 不会触发 Addon::appInit)
|
||
Loader::addNamespace('OSS', ROOT_PATH . 'addons' . DS . 'alioss' . DS . 'library' . DS . 'OSS' . DS);
|
||
$aliossConfig = $this->getAliossConfig();
|
||
if (!$aliossConfig) {
|
||
$output->error("alioss 插件未配置");
|
||
return 1;
|
||
}
|
||
$oss = new OssClient([
|
||
'accessKeyId' => $aliossConfig['accessKeyId'],
|
||
'endpoint' => $aliossConfig['endpoint'],
|
||
'bucket' => $aliossConfig['bucket'],
|
||
'region' => str_replace('-internal', '', substr(explode('.', $aliossConfig['endpoint'])[0], 4)),
|
||
'provider' => new StaticCredentialsProvider($aliossConfig['accessKeyId'], $aliossConfig['accessKeySecret']),
|
||
'signatureVersion' => OssClient::OSS_SIGNATURE_VERSION_V4,
|
||
]);
|
||
$output->writeln("==> OSS 已初始化: bucket={$aliossConfig['bucket']}");
|
||
|
||
// 2. 建立分类 id → 数据库记录映射
|
||
$categories = Db::name('fc_category')
|
||
->where('enabled', 1)
|
||
->column('id,pid,name,kind,image', 'id');
|
||
$output->writeln("==> 分类表加载: " . count($categories) . " 条");
|
||
|
||
// 3. 扫描下载目录
|
||
$files = glob($downloadDir . DS . '*.jpg');
|
||
$output->writeln("==> 本地图片: " . count($files) . " 张");
|
||
|
||
$success = 0; $skip = 0; $fail = 0;
|
||
$today = date('Ymd');
|
||
$uploadDir = '/uploads/' . $today . '/';
|
||
$destDir = ROOT_PATH . 'public' . str_replace('/', DS, $uploadDir);
|
||
if (!is_dir($destDir)) { @mkdir($destDir, 0755, true); }
|
||
|
||
foreach ($files as $localFile) {
|
||
$basename = basename($localFile);
|
||
$id = (int)pathinfo($basename, PATHINFO_FILENAME);
|
||
if (!$id) { continue; }
|
||
|
||
if (!isset($categories[$id])) {
|
||
$output->writeln("SKIP id=$id 分类不存在");
|
||
$skip++; continue;
|
||
}
|
||
|
||
$cat = $categories[$id];
|
||
try {
|
||
// 3a. 每次循环清空变量,防止上轮残留
|
||
unset($md5, $saveName, $ossKey, $urlPath, $destFile);
|
||
$md5 = md5_file($localFile);
|
||
if (!$md5) { throw new \Exception("无法计算 md5: $localFile"); }
|
||
$suffix = 'jpg';
|
||
$saveName = $md5 . '.' . $suffix;
|
||
$ossKey = ltrim($uploadDir . $saveName, '/');
|
||
$urlPath = '/' . $ossKey;
|
||
$destFile = $destDir . DS . $saveName;
|
||
|
||
// 3b. 用 copy + unlink(避免 move_uploaded_file 对非 HTTP 临时文件无效)
|
||
@copy($localFile, $destFile);
|
||
if (!file_exists($destFile)) { throw new \Exception("copy 到 uploads 失败: $destFile"); }
|
||
@unlink($localFile);
|
||
|
||
// 3c. 图片信息
|
||
$imgInfo = @getimagesize($destFile);
|
||
$filesize = filesize($destFile);
|
||
$width = $imgInfo ? (int)($imgInfo[0] ?? 0) : 0;
|
||
$height = $imgInfo ? (int)($imgInfo[1] ?? 0) : 0;
|
||
$sha1 = sha1_file($destFile);
|
||
$mimetype = 'image/jpeg';
|
||
$now = time();
|
||
|
||
// 3d. 先推 OSS(用临时本地文件)
|
||
$oss->uploadFile($aliossConfig['bucket'], $ossKey, $destFile);
|
||
|
||
// 3e. 写 attachment(storage=alioss,与 index::upload 的 serverbackup=0 模式一致)
|
||
$attachment = Attachment::create([
|
||
'admin_id' => 1,
|
||
'user_id' => 0,
|
||
'filename' => mb_substr($cat['name'] . '_分类图', 0, 100),
|
||
'category' => '',
|
||
'filesize' => $filesize,
|
||
'imagewidth' => $width,
|
||
'imageheight' => $height,
|
||
'imagetype' => $suffix,
|
||
'imageframes' => 0,
|
||
'mimetype' => $mimetype,
|
||
'url' => $urlPath,
|
||
'uploadtime' => $now,
|
||
'storage' => 'alioss',
|
||
'sha1' => $sha1,
|
||
], true);
|
||
|
||
// 3f. 更新 fc_category
|
||
Db::name('fc_category')
|
||
->where('id', $id)
|
||
->update([
|
||
'image' => $urlPath,
|
||
'icon_key' => '',
|
||
'updatetime' => $now,
|
||
]);
|
||
|
||
// 3g. serverbackup=0 → 删除本地临时文件(OSS 已是权威)
|
||
@unlink($destFile);
|
||
|
||
$success++;
|
||
if ($success % 50 === 0) {
|
||
$output->writeln(" ... 进度 $success 最后: {$cat['name']} #$id");
|
||
}
|
||
} catch (\Exception $e) {
|
||
$fail++;
|
||
$output->writeln("FAIL id=$id name={$cat['name']} err=" . $e->getMessage());
|
||
@unlink($localFile);
|
||
@unlink($destFile);
|
||
}
|
||
}
|
||
|
||
$output->writeln("==> 完成: success=$success skip=$skip fail=$fail total=" . count($files));
|
||
|
||
// 4. 验证 attachment 记录数
|
||
$attachmentCount = Db::name('attachment')
|
||
->where('storage', 'alioss')
|
||
->where('url', 'like', $uploadDir . '%')
|
||
->count();
|
||
$output->writeln("==> 校验: 今日 alioss attachment 记录 = $attachmentCount");
|
||
|
||
return 0;
|
||
}
|
||
|
||
/** 获取 alioss 插件配置 */
|
||
protected function getAliossConfig()
|
||
{
|
||
// 1. 尝试插件配置表(有的环境没有 fa_addon,避免崩溃)
|
||
try {
|
||
if (Db::query("SHOW TABLES LIKE 'fa_addon'")) {
|
||
$conf = Db::name('addon')->where('name', 'alioss')->find();
|
||
if ($conf && !empty($conf['config'])) {
|
||
$arr = json_decode($conf['config'], true);
|
||
if (is_array($arr) && isset($arr['accessKeyId'])) {
|
||
return $arr;
|
||
}
|
||
}
|
||
}
|
||
} catch (\Exception $e) { /* ignore */ }
|
||
|
||
// 2. 回退到插件默认 config.php
|
||
$ini = ROOT_PATH . 'addons' . DS . 'alioss' . DS . 'config.php';
|
||
if (file_exists($ini)) {
|
||
$default = include ROOT_PATH . 'addons' . DS . 'alioss' . DS . 'config.php';
|
||
$flat = [];
|
||
foreach ($default as $item) {
|
||
if (isset($item['name']) && isset($item['value'])) {
|
||
$flat[$item['name']] = $item['value'];
|
||
}
|
||
}
|
||
return $flat;
|
||
}
|
||
return null;
|
||
}
|
||
}
|