| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use app\job\ImageJob;
- use app\service\ImageService;
- use think\App;
- use think\Db;
- use think\Exception;
- use think\Log;
- use think\Queue;
- use think\queue\job\Redis;
- class WorkOrder extends Api
- {
- protected $noNeedLogin = ['*'];
- protected $noNeedRight = ['*'];
- /**
- * 出图接口
- * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
- */
- public function imageToText()
- {
- $params = $this->request->param();
- $service = new ImageService();
- $service->handleImage($params);
- $this->success('任务成功提交至队列');
- }
- public function textToImage()
- {
- $outputDirRaw = 'uploads/operate/ai/Preview/undefined_BRdP4/3';
- $img_name = '42131321';
- $rootPath = str_replace('\\', '/', ROOT_PATH);
- $outputDir = rtrim($rootPath . 'public/' . $outputDirRaw, '/') . '/';
- $dateDir = date('Y-m-d') . '/';
- $fullBaseDir = $outputDir . $dateDir;
- // 确保目录存在
- if (!is_dir($fullBaseDir . '2048x2048/')) {
- mkdir($fullBaseDir . '2048x2048/', 0755, true);
- }
- // // API配置
- // $config = [
- // 'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
- // 'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
- // 'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
- // 'default_prompt' => '恐怖的树状怪物,拥有尖牙利爪和血红眼睛,在蓝色背景下显得阴森可怕,风格为黑暗奇幻。'
- // ];
- //
- // // 1. 准备请求数据
- // $prompt = $config['default_prompt'];
- // $postData = [
- // 'botType' => 'MID_JOURNEY',
- // 'prompt' => $prompt,
- // 'base64Array' => [],
- // 'accountFilter' => [
- // 'channelId' => "",
- // 'instanceId' => "",
- // 'modes' => [],
- // 'remark' => "",
- // 'remix' => true,
- // 'remixAutoConsidered' => true
- // ],
- // 'notifyHook' => "",
- // 'state' => ""
- // ];
- // // 2. 提交生成请求
- // $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
- // echo "<pre>";
- // print_r($generateResponse);
- // echo "<pre>";
- // $generateData = json_decode($generateResponse, true);
- // echo "<pre>";
- // print_r($generateData);
- // echo "<pre>";
- // if (empty($generateData['result'])) {
- // throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
- // }
- //
- // die;
- // $taskId = "1755229064353588";
- $taskId = "1755234114253556";
- // $taskId = "1755224966357751";
- // 3. 等待图片生成完成
- sleep(3);
- $imageUrl = $this->getImageSeed($taskId);
- echo "<pre>";
- print_r($imageUrl);
- echo "<pre>";die;
- $img_name = mb_substr(preg_replace('/[^\x{4e00}-\x{9fa5}A-Za-z0-9_\- ]/u', '', $img_name), 0, 30);
- $filename = $img_name . '.png';
- $path512 = $fullBaseDir . '2048x2048/' . $filename;
- // 下载并保存图片
- // file_get_contents($imageUrl['data']['imageUrl']);
- // 下载并保存图片到本地文件夹中
- $imageData = file_get_contents($imageUrl['data']['imageUrl']);
- $result = file_put_contents($path512, $imageData);
- if ($result === false) {
- die('保存图片失败,请检查目录权限');
- }
- // 数据库更新
- Db::name('text_to_image')->where('id', '10694')->update([
- 'new_image_url' => str_replace($rootPath . 'public/', '', $path512),
- 'img_name' => $img_name,
- 'model' => 'MID_JOURNEY',
- 'status' => trim($img_name) === '' ? 0 : 1,
- 'status_name' => "文生图",
- 'size' => "2048",
- 'quality' => 'standard',
- 'style' => 'vivid',
- 'error_msg' => '',
- 'update_time' => date('Y-m-d H:i:s')
- ]);
- return "成功";
- }
- public function getImageSeed($taskId)
- {
- // 配置参数
- $apiUrl = 'https://chatapi.onechats.ai/mj/task/' . $taskId . '/fetch';
- $apiKey = 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK';
- try {
- // 初始化cURL
- $ch = curl_init();
- // 设置cURL选项
- curl_setopt_array($ch, [
- CURLOPT_URL => $apiUrl,
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_CUSTOMREQUEST => 'GET', // 明确指定GET方法
- CURLOPT_HTTPHEADER => [
- 'Authorization: Bearer ' . $apiKey,
- 'Accept: application/json',
- 'Content-Type: application/json'
- ],
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_TIMEOUT => 60,
- CURLOPT_FAILONERROR => true // 添加失败时返回错误
- ]);
- // 执行请求
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // 错误处理
- if (curl_errno($ch)) {
- throw new Exception('cURL请求失败: ' . curl_error($ch));
- }
- // 关闭连接
- curl_close($ch);
- // 验证HTTP状态码
- if ($httpCode < 200 || $httpCode >= 300) {
- throw new Exception('API返回错误状态码: ' . $httpCode);
- }
- // 解析JSON响应
- $responseData = json_decode($response, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- throw new Exception('JSON解析失败: ' . json_last_error_msg());
- }
- // 返回结构化数据
- return [
- 'success' => true,
- 'http_code' => $httpCode,
- 'data' => $responseData
- ];
- } catch (Exception $e) {
- // 确保关闭cURL连接
- if (isset($ch) && is_resource($ch)) {
- curl_close($ch);
- }
- return [
- 'success' => false,
- 'error' => $e->getMessage(),
- 'http_code' => $httpCode ?? 0
- ];
- }
- }
- private function sendPostRequest($url, $data, $apiKey)
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey,
- 'Accept: application/json',
- 'Content-Type: application/json'
- ]);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- curl_close($ch);
- return [
- 'response' => $response,
- 'http_code' => $httpCode,
- 'error' => $error
- ];
- }
- /**
- * 文本生成图片并保存第一张结果
- * @param array $params 请求参数
- * @return array 返回结果
- */
- public function txttowimg()
- {
- // API配置
- $config = [
- 'api_url' => 'https://chatapi.onechats.ai/mj/submit/imagine',
- 'fetch_url' => 'https://chatapi.onechats.ai/mj/task/',
- 'api_key' => 'sk-iURfrAgzAjhZ4PpPLwzmWIAhM7zKfrkwDvyxk4RVBQ4ouJNK',
- 'default_prompt' => '一个猫',
- 'wait_time' => 3 // 等待生成完成的秒数
- ];
- try {
- // 1. 准备请求数据
- $prompt = $config['default_prompt'];
- $postData = [
- 'botType' => 'MID_JOURNEY',
- 'prompt' => $prompt,
- 'base64Array' => [],
- 'accountFilter' => [
- 'channelId' => "",
- 'instanceId' => "",
- 'modes' => [],
- 'remark' => "",
- 'remix' => true,
- 'remixAutoConsidered' => true
- ],
- 'notifyHook' => "",
- 'state' => ""
- ];
- // 2. 提交生成请求
- $generateResponse = $this->sendApiRequest($config['api_url'], $postData, $config['api_key']);
- $generateData = json_decode($generateResponse, true);
- if (empty($generateData['result'])) {
- throw new Exception('生成失败: '.($generateData['message'] ?? '未知错误'));
- }
- $taskId = $generateData['result'];
- // 3. 等待图片生成完成
- sleep($config['wait_time']);
- // 4. 获取生成结果
- $fetchUrl = $config['fetch_url'].$taskId.'/fetch';
- $fetchResponse = $this->sendApiRequest($fetchUrl, [], $config['api_key'], 'GET');
- $fetchData = json_decode($fetchResponse, true);
- if (empty($fetchData['imageUrl'])) {
- throw new Exception('获取图片失败: '.($fetchData['message'] ?? '未知错误'));
- }
- // 5. 处理返回的图片数组(取第一张)
- $imageUrls = is_array($fetchData['imageUrl']) ? $fetchData['imageUrl'] : [$fetchData['imageUrl']];
- $firstImageUrl = $imageUrls[0];
- // 6. 保存图片到本地
- $savePath = $this->saveImage($firstImageUrl);
- // 7. 返回结果
- return [
- 'code' => 200,
- 'msg' => '图片生成并保存成功',
- 'data' => [
- 'local_path' => $savePath,
- 'web_url' => request()->domain().$savePath,
- 'task_id' => $taskId
- ]
- ];
- } catch (Exception $e) {
- // 错误处理
- return [
- 'code' => 500,
- 'msg' => '处理失败: '.$e->getMessage(),
- 'data' => null
- ];
- }
- }
- /**
- * 发送API请求
- * @param string $url 请求地址
- * @param array $data 请求数据
- * @param string $apiKey API密钥
- * @param string $method 请求方法
- * @return string 响应内容
- * @throws Exception
- */
- private function sendApiRequest($url, $data, $apiKey, $method = 'POST')
- {
- $ch = curl_init();
- curl_setopt_array($ch, [
- CURLOPT_URL => $url,
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_CUSTOMREQUEST => $method,
- CURLOPT_HTTPHEADER => [
- 'Authorization: Bearer '.$apiKey,
- 'Accept: application/json',
- 'Content-Type: application/json'
- ],
- CURLOPT_POSTFIELDS => $method === 'POST' ? json_encode($data) : null,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_SSL_VERIFYHOST => false,
- CURLOPT_TIMEOUT => 60,
- CURLOPT_FAILONERROR => true
- ]);
- $response = curl_exec($ch);
- $error = curl_error($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- if ($error) {
- throw new Exception('API请求失败: '.$error);
- }
- if ($httpCode < 200 || $httpCode >= 300) {
- throw new Exception('API返回错误状态码: '.$httpCode);
- }
- return $response;
- }
- /**
- * 保存图片到本地
- * @param string $imageUrl 图片URL
- * @return string 本地保存路径
- * @throws Exception
- */
- private function saveImage($imageUrl)
- {
- // 1. 创建存储目录
- $saveDir = ROOT_PATH.'public'.DS.'uploads'.DS.'midjourney'.DS.date('Ymd');
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 2. 生成唯一文件名
- $filename = uniqid().'.png';
- $localPath = DS.'uploads'.DS.'midjourney'.DS.date('Ymd').DS.$filename;
- $fullPath = $saveDir.DS.$filename;
- // 3. 下载图片
- $ch = curl_init($imageUrl);
- curl_setopt_array($ch, [
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_SSL_VERIFYPEER => false,
- CURLOPT_CONNECTTIMEOUT => 15
- ]);
- $imageData = curl_exec($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if (!$imageData) {
- throw new Exception('图片下载失败: '.$error);
- }
- // 4. 验证图片类型
- $imageInfo = getimagesizefromstring($imageData);
- if (!in_array($imageInfo['mime'] ?? '', ['image/png', 'image/jpeg'])) {
- throw new Exception('下载内容不是有效图片');
- }
- // 5. 保存文件
- if (!file_put_contents($fullPath, $imageData)) {
- throw new Exception('图片保存失败');
- }
- return $localPath;
- }
- /**
- * 图生图本地测试
- */
- public function imgtowimg()
- {
- $prompt = $this->request->param('prompt', '');
- $imgRelPath = 'uploads/operate/ai/Preview/arr/两只手碰拳的黑白线条插画下有Daddy Me字样风格简约质.png';
- $imgPath = ROOT_PATH . 'public/' . $imgRelPath;
- if (!file_exists($imgPath)) {
- return json(['code' => 1, 'msg' => '原图不存在:' . $imgRelPath]);
- }
- $imgData = file_get_contents($imgPath);
- $base64Img = 'data:image/png;base64,' . base64_encode($imgData);
- $params = [
- 'prompt' => $prompt,
- 'negative_prompt' => '(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy',
- 'steps' => 20,
- 'sampler_name' => 'DPM++ 2M SDE',
- 'cfg_scale' => 7,
- 'seed' => -1,
- 'width' => 1024,
- 'height' => 1303,
- 'override_settings' => [
- 'sd_model_checkpoint' => 'realisticVisionV51_v51VAE-inpainting',
- 'sd_vae' => 'vae-ft-mse-840000-ema-pruned',
- 'CLIP_stop_at_last_layers' => 2
- ],
- 'clip_skip' => 2,
- 'alwayson_scripts' => [
- 'controlnet' => [
- 'args' => [[
- 'enabled' => true,
- 'input_image' => $base64Img,
- 'module' => 'inpaint_only+lama',
- 'model' => 'control_v11p_sd15_inpaint_fp16 [be8bc0ed]',
- 'weight' => 1,
- 'resize_mode' => 'Resize and Fill',
- 'pixel_perfect' => false,
- 'control_mode' => 'ControlNet is more important',
- 'starting_control_step' => 0,
- 'ending_control_step' => 1
- ]]
- ]
- ]
- ];
- $apiUrl = "http://20.0.17.188:45001/sdapi/v1/txt2img";
- $headers = ['Content-Type: application/json'];
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $apiUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params, JSON_UNESCAPED_UNICODE));
- curl_setopt($ch, CURLOPT_TIMEOUT, 180);
- $response = curl_exec($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error) {
- return json(['code' => 1, 'msg' => '请求失败:' . $error]);
- }
- $data = json_decode($response, true);
- if (!isset($data['images'][0])) {
- return json(['code' => 1, 'msg' => '接口未返回图像数据']);
- }
- $resultImg = base64_decode($data['images'][0]);
- $saveDir = ROOT_PATH . 'public/uploads/img2img/';
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- $originalBaseName = pathinfo($imgRelPath, PATHINFO_FILENAME);
- $fileName = $originalBaseName . '-' . time() . '-1024x1248.png';
- $savePath = $saveDir . $fileName;
- file_put_contents($savePath, $resultImg);
- return json([
- 'code' => 0,
- 'msg' => '图像生成成功',
- 'data' => [
- 'origin_url' => '/uploads/img2img/' . $fileName
- ]
- ]);
- }
- /**
- * 后期图像处理-单张图片高清放大处理
- */
- public function extra_image()
- {
- // 配置参数
- $config = [
- 'input_dir' => 'uploads/operate/ai/Preview/arr/',
- 'output_dir' => 'uploads/extra_image/',
- 'api_url' => 'http://20.0.17.188:45001/sdapi/v1/extra-single-image',
- 'timeout' => 120, // 增加超时时间,高清处理可能耗时较长
- 'upscale_params' => [
- 'resize_mode' => 0,
- 'show_extras_results' => true,
- 'gfpgan_visibility' => 0, // 人脸修复关闭
- 'codeformer_visibility' => 0, // 人脸修复关闭
- 'codeformer_weight' => 0,
- 'upscaling_resize' => 2.45, // 放大倍数
- 'upscaling_crop' => true,
- 'upscaler_1' => 'R-ESRGAN 4x+ Anime6B', // 主放大模型
- 'upscaler_2' => 'None', // 不使用第二放大器
- 'extras_upscaler_2_visibility' => 0,
- 'upscale_first' => false,
- ]
- ];
- // 输入文件处理
- $imgRelPath = '图案的整体色调是柔和的蓝色和灰色形成温馨而宁静的视觉效果花卉.png';
- $imgPath = ROOT_PATH . 'public/' . $config['input_dir'] . $imgRelPath;
- if (!file_exists($imgPath)) {
- return json(['code' => 1, 'msg' => '原图不存在:' . $imgRelPath]);
- }
- // 读取并编码图片
- try {
- $imgData = file_get_contents($imgPath);
- if ($imgData === false) {
- throw new Exception('无法读取图片文件');
- }
- $base64Img = base64_encode($imgData);
- } catch (Exception $e) {
- return json(['code' => 1, 'msg' => '图片处理失败:' . $e->getMessage()]);
- }
- // 准备API请求数据
- $postData = array_merge($config['upscale_params'], ['image' => $base64Img]);
- $jsonData = json_encode($postData);
- if ($jsonData === false) {
- return json(['code' => 1, 'msg' => 'JSON编码失败']);
- }
- // 调用API进行高清放大
- $ch = curl_init();
- curl_setopt_array($ch, [
- CURLOPT_URL => $config['api_url'],
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_POST => true,
- CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
- CURLOPT_POSTFIELDS => $jsonData,
- CURLOPT_TIMEOUT => $config['timeout'],
- CURLOPT_CONNECTTIMEOUT => 30,
- ]);
- $response = curl_exec($ch);
- $error = curl_error($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- if ($error) {
- return json(['code' => 1, 'msg' => 'API请求失败:' . $error]);
- }
- if ($httpCode !== 200) {
- return json(['code' => 1, 'msg' => 'API返回错误状态码:' . $httpCode]);
- }
- $data = json_decode($response, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- return json(['code' => 1, 'msg' => 'API返回数据解析失败']);
- }
- if (!isset($data['image']) || empty($data['image'])) {
- return json(['code' => 1, 'msg' => '接口未返回有效的图像数据']);
- }
- // 保存处理后的图片
- try {
- $resultImg = base64_decode($data['image']);
- if ($resultImg === false) {
- throw new Exception('Base64解码失败');
- }
- $saveDir = ROOT_PATH . 'public/' . $config['output_dir'];
- if (!is_dir($saveDir) && !mkdir($saveDir, 0755, true)) {
- throw new Exception('无法创建输出目录');
- }
- $originalBaseName = pathinfo($imgRelPath, PATHINFO_FILENAME);
- $fileName = $originalBaseName . '-hd.png'; // 使用-hd后缀更明确
- $savePath = $saveDir . $fileName;
- if (file_put_contents($savePath, $resultImg) === false) {
- throw new Exception('无法保存处理后的图片');
- }
- // 返回成功响应
- return json([
- 'code' => 0,
- 'msg' => '图像高清放大处理成功',
- 'data' => [
- 'url' => '/' . $config['output_dir'] . $fileName,
- 'original_size' => filesize($imgPath),
- 'processed_size' => filesize($savePath),
- 'resolution' => getimagesize($savePath), // 返回新图片的分辨率
- ]
- ]);
- } catch (Exception $e) {
- return json(['code' => 1, 'msg' => '保存结果失败:' . $e->getMessage()]);
- }
- }
- /**
- * 获取 SD 模型列表
- * 接口地址: /sdapi/v1/sd-models
- */
- public function sd_models() {
- // $url = "http://20.0.17.188:45001/sdapi/v1/sd-models";
- // // 初始化 cURL
- // $ch = curl_init();
- // // 设置请求参数
- // curl_setopt($ch, CURLOPT_URL, $url);
- // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // curl_setopt($ch, CURLOPT_TIMEOUT, 10);
- // curl_setopt($ch, CURLOPT_HTTPHEADER, [
- // 'Content-Type: application/json',
- // 'Accept: application/json',
- // ]);
- // // 发送请求
- // $response = curl_exec($ch);
- // // 错误处理
- // if (curl_errno($ch)) {
- // curl_close($ch);
- // return json([
- // 'code' => 1,
- // 'msg' => '请求失败: ' . curl_error($ch),
- // 'data' => [],
- // 'count' => 0
- // ]);
- // }
- // curl_close($ch);
- // // 解析 JSON 响应
- // $result = json_decode($response, true);
- // // 判断返回数据是否有效
- // if (!is_array($result)) {
- // return json([
- // 'code' => 1,
- // 'msg' => '数据解析失败',
- // 'data' => [],
- // 'count' => 0
- // ]);
- // }
- // 正常返回
- return json([
- 'code' => 0,
- 'msg' => '查询成功',
- 'data' => '',
- 'count' => 2,
- ]);
- }
- /**
- * 查询队列列表
- * 统计文件对应的队列情况
- */
- public function get_queue_logs()
- {
- $params = $this->request->param('old_image_file', '');
- $queue_logs = Db::name('queue_logs')
- ->where('old_image_file', $params)
- ->order('id desc')
- ->select();
- $result = []; //初始化变量,避免未定义错误
- foreach ($queue_logs as &$log) {
- $taskId = $log['id'];
- $statusCount = Db::name('image_task_log')
- ->field('status, COUNT(*) as count')
- ->where('task_id', $taskId)
- ->where('mod_rq', null)
- ->group('status')
- ->select();
- $log['已完成数量'] = 0;
- $log['处理中数量'] = 0;
- $log['排队中的数量'] = 0;
- $log['失败数量'] = 0;
- foreach ($statusCount as $item) {
- switch ($item['status']) {
- case 0:
- $log['排队中的数量'] = $item['count'];
- break;
- case 1:
- $log['处理中数量'] = $item['count'];
- break;
- case 2:
- $log['已完成数量'] = $item['count'];
- break;
- case -1:
- $log['失败数量'] = $item['count'];
- break;
- }
- }
- // if ($log['排队中的数量'] >$log['已完成数量']) {
- // $result[] = $log;
- // }
- if ($log['排队中的数量']) {
- $result[] = $log;
- }
- // if ($log['处理中数量'] >= 0) {
- // $result[] = $log;
- // }
- }
- return json([
- 'code' => 0,
- 'msg' => '查询成功',
- 'data' => $result,
- 'count' => count($result)
- ]);
- }
- /**
- * 查询总队列状态(统计当前处理的数据量)
- */
- public function queueStats()
- {
- $statusList = Db::name('image_task_log')
- ->field('status, COUNT(*) as total')
- ->where('mod_rq', null)
- ->where('create_time', '>=', date('Y-m-d 00:00:00'))
- ->group('status')
- ->select();
- $statusCount = [];
- foreach ($statusList as $item) {
- $statusCount[$item['status']] = $item['total'];
- }
- // 总数为所有状态和
- $total = array_sum($statusCount);
- //获取队列当前状态
- $statusText = Db::name('queue_logs')->order('id desc')->value('status');
- return json([
- 'code' => 0,
- 'msg' => '获取成功',
- 'data' => [
- '总任务数' => $total,
- '待处理' => $statusCount[0] ?? 0,
- '处理中' => $statusCount[1] ?? 0,
- '成功' => $statusCount[2] ?? 0,
- '失败' => $statusCount[-1] ?? 0,
- '当前状态' => $statusText
- ]
- ]);
- }
- /**
- * 显示当前运行中的队列监听进程
- */
- public function viewQueueStatus()
- {
- $redis = new \Redis();
- $redis->connect('127.0.0.1', 6379);
- $redis->auth('123456');
- $redis->select(15);
- $key = 'queues:imgtotxt';
- // 判断 key 是否存在,避免报错
- if (!$redis->exists($key)) {
- return json([
- 'code' => 0,
- 'msg' => '查询成功,队列为空',
- 'count' => 0,
- 'tasks_preview' => []
- ]);
- }
- $count = $redis->lLen($key);
- $list = $redis->lRange($key, 0, 9);
- // 解码 JSON 内容,确保每一项都有效
- $parsed = array_filter(array_map(function ($item) {
- return json_decode($item, true);
- }, $list), function ($item) {
- return !is_null($item);
- });
- return json([
- 'code' => 0,
- 'msg' => '查询成功',
- 'count' => $count,
- 'tasks_preview' => $parsed
- ]);
- }
- /**
- * 清空队列并删除队列日志记录
- */
- public function stopQueueProcesses()
- {
- Db::name('image_task_log')
- ->where('log', '队列中')
- ->whereOr('status', 1)
- ->where('create_time', '>=', date('Y-m-d 00:00:00'))
- ->update([
- 'status' => "-1",
- 'log' => '清空取消队列',
- 'mod_rq' => date('Y-m-d H:i:s')
- ]);
- Db::name('image_task_log')
- ->whereLike('log', '%处理中%')
- ->where('create_time', '>=', date('Y-m-d 00:00:00'))
- ->update([
- 'status' => "-1",
- 'log' => '清空取消队列',
- 'mod_rq' => date('Y-m-d H:i:s')
- ]);
- $redis = new \Redis();
- $redis->connect('127.0.0.1', 6379);
- $redis->auth('123456');
- $redis->select(15);
- $key_txttoimg = 'queues:txttoimg:reserved';
- $key_txttotxt = 'queues:txttotxt:reserved';
- $key_imgtotxt = 'queues:imgtotxt:reserved';
- $key_imgtoimg = 'queues:imgtoimg:reserved';
- // 清空 Redis 队列
- $redis->del($key_txttoimg);
- $redis->del($key_txttotxt);
- $redis->del($key_imgtotxt);
- $redis->del($key_imgtoimg);
- $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);
- // if ($count === 0) {
- // return json([
- // 'code' => 1,
- // 'msg' => '暂无队列需要停止'
- // ]);
- // }
- return json([
- 'code' => 0,
- 'msg' => '成功停止队列任务'
- ]);
- }
- /**
- * 开启队列任务
- * 暂时用不到、服务器已开启自动开启队列模式
- */
- // public function kaiStats()
- // {
- // // 判断是否已有监听进程在运行
- // $check = shell_exec("ps aux | grep 'queue:listen' | grep -v grep");
- // if ($check) {
- // return json([
- // 'code' => 1,
- // 'msg' => '监听进程已存在,请勿重复启动'
- // ]);
- // }
- // // 启动监听
- // $command = 'nohup php think queue:listen --queue --timeout=300 --sleep=3 --memory=256 > /var/log/job_queue.log 2>&1 &';
- // exec($command, $output, $status);
- // if ($status === 0) {
- // return json([
- // 'code' => 0,
- // 'msg' => '队列监听已启动'
- // ]);
- // } else {
- // return json([
- // 'code' => 1,
- // 'msg' => '队列启动失败',
- // 'output' => $output
- // ]);
- // }
- // }
- /**
- * 通过店铺ID-查询对应店铺表数据
- *
- */
- public function PatternApi()
- {
- $params = $this->request->param('pattern_id', '');
- $tableName = 'pattern-' . $params;
- // 连接 MongoDB
- $mongo = Db::connect('mongodb');
- // 查询指定 skc 的数据
- $data = $mongo->table($tableName)
- ->field('
- name,
- skc,
- file
- ')
- ->where("skc", '0853004152036')
- ->select();
- $data = json_decode(json_encode($data), true); // 数组
- return json([
- 'code' => 0,
- 'msg' => '获取成功',
- 'data' => $data
- ]);
- }
- }
|