| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use app\job\ImageJob;
- use app\service\AIGatewayService;
- use app\service\ImageService;
- use think\App;
- use think\Db;
- use think\Exception;
- use think\Log;
- use think\Queue;
- use think\queue\job\Redis;
- use think\Request;
- class WorkOrder extends Api{
- protected $noNeedLogin = ['*'];
- protected $noNeedRight = ['*'];
- public function index(){echo '访问成功';}
- /**
- * AI队列入口处理 出图接口
- * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
- */
- public function imageToText()
- {
- $params = $this->request->param();
- $service = new ImageService();
- $service->handleImage($params);
- $this->success('任务成功提交至队列');
- }
- /**
- * product 产品专用统一api调用接口
- * AI模型调用接口
- */
- public function GetTxtToTxt(){
- $params = $this->request->param();
- $prompt = $params['prompt'];//提示词
- $old_path = $params['path'] ?? '';//原图路径
- $model = $params['model'];//模型
- if(empty($model)) {
- return json(['code' => 1, 'msg' => '模型请求失败']);
- }
- $aiGateway = new AIGatewayService();
- $service = new ImageService();
- if($params['status_val'] == '图生文'){
- $service->handleImgToText($params);
- $res = [
- 'code' => 0,
- 'msg' => '正在优化提示词,请稍等.....'
- ];
- return json($res);
- }else if($params['status_val'] == '文生文'){
- $fullPrompt = $prompt;
- $fullPrompt .= "
- 请根据上述内容生成一段完整的话术,要求:
- 1. 内容必须是连贯的一段话,不要使用列表、分隔线或其他结构化格式
- 2. 不要包含非文本元素的描述
- 3. 不要添加任何额外的引导语、解释或开场白
- 4. 语言流畅自然";
- $result = $service->handleTextToText($fullPrompt, $model);
- if(!empty($params['id'])){
- Db::name('product')->where('id', $params['id'])->update(['content' => $result['data']]);
- }
- $res = [
- 'code' => 0,
- 'msg' => '优化成功',
- 'content' => $result['data']
- ];
- return json($res);
- }elseif($params['status_val'] == '文生图'){
- $service->handleTextToImg($params);
- $res = [
- 'code' => 0,
- 'msg' => '正在生成图片中,请稍等.....'
- ];
- return json($res);
- }else{
- $this->error('请求失败');
- }
- }
- /**
- * 即梦AI--创建视频任务接口
- * 首帧图 + 尾帧图 = 新效果视频
- */
- public function Create_ImgToVideo()
- {
- $aiGateway = new AIGatewayService();
- $apiUrl = $aiGateway->config['Create_ImgToVideo']['api_url'];
- $apiKey = $aiGateway->config['Create_ImgToVideo']['api_key'];
- $params = $this->request->param();
- $modelParams = [
- 'resolution' => $params['resolution'] ?? '720p', // 分辨率:480p, 720p, 1080p
- 'duration' => $params['duration'] ?? 5, // 视频时长(秒)
- 'camerafixed' => $params['camerafixed'] ?? false, // 相机固定
- 'watermark' => $params['watermark'] ?? true, // 水印
- 'aspect_ratio' => $params['aspect_ratio'] ?? '16:9' // 视频比例:16:9, 4:3, 1:1等
- ];
- // 构建提示词
- $prompt = $params['prompt'] ?? '';
- $prompt .= ' --resolution ' . $modelParams['resolution'];
- $prompt .= ' --duration ' . $modelParams['duration'];
- $prompt .= ' --camerafixed ' . ($modelParams['camerafixed'] ? 'true' : 'false');
- $prompt .= ' --watermark ' . ($modelParams['watermark'] ? 'true' : 'false');
- $prompt .= ' --aspect_ratio ' . $modelParams['aspect_ratio'];
- // 构建请求数据
- $data = [
- 'model' => 'doubao-seedance-1-0-pro-250528',//模型
- 'content' => [
- [
- 'type' => 'text',
- 'text' => $prompt
- ],
- [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $params['first_image_url']// 首帧图片URL(参数)
- ],
- 'role' => 'first_image'
- ],
- [
- 'type' => 'image_url',
- 'image_url' => [
- 'url' => $params['last_image_url'] // 尾帧图片URL(参数)
- ],
- 'role' => 'last_image'
- ]
- ]
- ];
- // 转换为 JSON 字符串
- $jsonData = json_encode($data);
- // 初始化 cURL
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $apiUrl);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
- curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 超时时间
- // 执行请求
- $response = curl_exec($ch);
- // 检查 cURL 错误
- if (curl_errno($ch)) {
- $error = curl_error($ch);
- curl_close($ch);
- return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
- }
- curl_close($ch);
- // 解析响应
- $responseData = json_decode($response, true);
- // 检查 API 错误
- if (isset($responseData['error'])) {
- return json(['code' => 0, 'msg' => 'API 错误: ' . $responseData['error']['message']]);
- }
- // 获取任务 ID
- $taskId = $responseData['id'] ?? '';
- if (empty($taskId)) {
- return json(['code' => 0, 'msg' => '获取任务 ID 失败']);
- }
- // 返回结果
- return json([
- 'code' => 1,
- 'data' => [
- 'task_id' => $taskId,
- 'status' => $responseData['status'] ?? '',
- 'created_at' => $responseData['created_at'] ?? ''
- ]
- ]);
- }
- /**
- * 即梦AI--获取视频接口
- * 首帧图 + 尾帧图 = 新效果视频
- */
- public function Get_ImgToVideo()
- {
- $aiGateway = new AIGatewayService();
- $apiUrl = $aiGateway->config['Create_ImgToVideo']['api_url'];
- $apiKey = $aiGateway->config['Create_ImgToVideo']['api_key'];
- $params = $this->request->param();
- $taskId = $params['task_id'] ?? '';
- if (empty($taskId)) {
- return json(['code' => 0, 'msg' => '任务 ID 不能为空']);
- }
- // 查询任务状态
- $queryUrl = $apiUrl . '/' . $taskId;
- $ch2 = curl_init();
- curl_setopt($ch2, CURLOPT_URL, $queryUrl);
- curl_setopt($ch2, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
- curl_setopt($ch2, CURLOPT_TIMEOUT, 60); // 超时时间
- $queryResponse = curl_exec($ch2);
- // 检查 cURL 错误
- if (curl_errno($ch2)) {
- $error = curl_error($ch2);
- curl_close($ch2);
- return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
- }
- curl_close($ch2);
- // 解析查询响应
- $queryData = json_decode($queryResponse, true);
- // print_r($queryData);die;
- // 轮询任务状态,直到完成
- $maxPolls = 30; // 最大轮询次数
- $pollCount = 0;
- $taskStatus = $queryData['status'] ?? '';
- while (!in_array($taskStatus, ['completed', 'succeeded']) && $pollCount < $maxPolls) {
- sleep(5); // 每5秒轮询一次
- $pollCount++;
- // 再次查询任务状态
- $ch3 = curl_init();
- curl_setopt($ch3, CURLOPT_URL, $queryUrl);
- curl_setopt($ch3, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch3, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch3, CURLOPT_TIMEOUT, 60);
- $pollResponse = curl_exec($ch3);
- curl_close($ch3);
- $pollData = json_decode($pollResponse, true);
- $taskStatus = $pollData['status'] ?? '';
- // 检查任务是否失败
- if ($taskStatus === 'failed') {
- return json(['code' => 0, 'msg' => '任务执行失败']);
- }
- }
- // 如果任务已经成功,直接使用 $queryData
- if (empty($pollData) && isset($queryData['status']) && $queryData['status'] === 'succeeded') {
- $pollData = $queryData;
- }
- // 检查轮询是否超时
- if (!in_array($taskStatus, ['completed', 'succeeded'])) {
- return json(['code' => 0, 'msg' => '任务执行超时']);
- }
- // 获取视频 URL
- $videoUrl = $pollData['content']['video_url'] ?? '';
- if (empty($videoUrl)) {
- return json(['code' => 0, 'msg' => '获取视频 URL 失败', 'data' => ['pollData' => $pollData]]);
- }
- // 确保保存目录存在
- $saveDir = ROOT_PATH . 'public/uploads/ceshi/';
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成保存文件名
- $fileName = $taskId . '.mp4';
- $savePath = $saveDir . '/' . $fileName;
- // 下载视频
- // 设置超时时间为300秒(5分钟)
- $context = stream_context_create(['http' => ['timeout' => 300]]);
- $videoContent = file_get_contents($videoUrl, false, $context);
- if ($videoContent === false) {
- return json(['code' => 0, 'msg' => '下载视频失败', 'data' => ['videoUrl' => $videoUrl]]);
- }
- // 保存视频到文件
- $saveResult = file_put_contents($savePath, $videoContent);
- if ($saveResult === false) {
- return json(['code' => 0, 'msg' => '保存视频失败', 'data' => ['savePath' => $savePath, 'dirWritable' => is_writable($saveDir)]]);
- }
- // 生成视频的访问 URL
- $videoAccessUrl = '/uploads/ceshi/' . $fileName;
- // 返回结果
- return json([
- 'code' => 1,
- 'data' => [
- 'task_id' => $taskId,
- 'status' => $taskStatus,
- 'video_url' => $videoAccessUrl,
- 'save_path' => $savePath
- ]
- ]);
- }
- /**
- * 九个分镜头生成流程
- * 模型:gemini-3-pro-image-preview
- * 说明:
- * 第一步:(提示词 + 原始图片 = 九个分镜头图片) 或 (提示词 = 九个分镜头图片)
- * 第二步:使用九个分镜头图进行裁剪单图生成连贯视频
- * 第三步:在通过分镜头视频拼接成一个完整的视频(列如每个分镜头视频为8秒,九个为72秒形成完整视频)
- */
- // public function Get_txttonineimg()
- // {
- // // 发起接口请求
- //// $apiUrl = 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:generateContent';
- // $apiUrl = 'https://chatapi.onechats.ai/v1beta/models/gemini-3-pro-image-preview:streamGenerateContent';
- // $apiKey = 'sk-9aIV9nx7pJxJFMrB8REtNbhjYuNBxCcnEOwiJDHd6UwmN2eJ';
- //
- //// $params = $this->request->param();
- // $prompt = '生成一个苹果(九个分镜头图片)';
- //
- // $requestData = [
- // "contents" => [
- // [
- // "role" => "user",
- // "parts" => [
- // ["text" => $prompt]
- // ]
- // ]
- // ],
- // "generationConfig" => [
- // "responseModalities" => ["TEXT", "IMAGE"],
- // "imageConfig" => [
- // "aspectRatio" => "1:1"
- // ]
- // ]
- // ];
- //
- // $ch = curl_init();
- // curl_setopt($ch, CURLOPT_URL, $apiUrl);
- // curl_setopt($ch, CURLOPT_POST, true);
- // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData, JSON_UNESCAPED_UNICODE));
- // curl_setopt($ch, CURLOPT_HTTPHEADER, [
- // 'Content-Type: application/json',
- // 'Authorization: Bearer ' . $apiKey
- // ]);
- // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
- // curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 生成图片超时时间(建议60秒)
- //
- // $response = curl_exec($ch);
- // $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- //
- // $error = curl_error($ch);
- // curl_close($ch);
- // $res = json_decode($response, true);
- //
- // // 构建URL路径(使用正斜杠)
- // $url_path = '/uploads/txtnewimg/';
- // // 构建物理路径(使用正斜杠确保统一格式)
- // $save_path = ROOT_PATH . 'public' . '/' . 'uploads' . '/' . 'txtnewimg' . '/';
- // // 移除ROOT_PATH中可能存在的反斜杠,确保统一使用正斜杠
- // $save_path = str_replace('\\', '/', $save_path);
- // // 自动创建文件夹(如果不存在)
- // if (!is_dir($save_path)) {
- // mkdir($save_path, 0755, true);
- // }
- //
- // // 提取base64图片数据
- // $text_content = $res['candidates'][0]['content']['parts'][0]['inlineData']['data'];
- // $str = 'data:image/jpeg;base64,';
- // $text_content = $str. $text_content;
- // // 匹配base64图片数据
- // preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $text_content, $matches);
- // if (empty($matches)) {
- // return '未找到图片数据';
- // }
- // $image_type = $matches[1];
- // $base64_data = $matches[2];
- //
- // // 解码base64数据
- // $image_data = base64_decode($base64_data);
- // if ($image_data === false) {
- // return '图片解码失败';
- // }
- //
- // // 生成唯一文件名(包含扩展名)
- // $file_name = uniqid() . '.' . $image_type;
- // $full_file_path = $save_path . $file_name;
- //
- // // 保存图片到文件系统
- // if (!file_put_contents($full_file_path, $image_data)) {
- // return '图片保存失败';
- // }
- // // 生成数据库存储路径(使用正斜杠格式)
- // $db_img_path = $url_path . $file_name;
- // return $db_img_path;
- // }
- public function GetTxtToImg(){
- $params = $this->request->param();
- $prompt = $params['prompt'];//提示词
- $model = $params['model'];//模型
- $size = $params['size'];//尺寸
- // 调用AI生成图片
- $aiGateway = new AIGatewayService();
- $res = $aiGateway->callDalleApi($prompt, $model, $size);
- // 提取base64图片数据
- $imageData = '';
- $imageType = 'png'; // 默认图片类型
- if (isset($res['candidates'][0]['content']['parts'][0]['text'])) {
- $text_content = $res['candidates'][0]['content']['parts'][0]['text'];
- // 匹配base64图片数据和类型
- if (preg_match('/data:image\/([a-zA-Z0-9]+);base64,([^\s]+)/', $text_content, $matches)) {
- $imageType = strtolower($matches[1]);
- $base64Data = $matches[2];
- // 解码base64数据
- $imageData = base64_decode($base64Data);
- }
- }
- if (!$imageData) {
- return json(['code' => 1, 'msg' => '图片生成失败,未找到有效图片数据']);
- }
- // 创建保存目录(public/uploads/log/YYYY-MM/)
- $yearMonth = date('Ym');
- $saveDir = ROOT_PATH . 'public/uploads/ceshi/' . $yearMonth . '/';
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $fileName = uniqid() . '.' . $imageType;
- $filePath = $saveDir . $fileName;
- // 保存图片到本地文件
- if (file_put_contents($filePath, $imageData) === false) {
- return json(['code' => 1, 'msg' => '图片保存失败']);
- }
- // 生成前端可访问的URL
- $imageUrl = '/uploads/ceshi/' . $yearMonth . '/' . $fileName;
- // 返回标准JSON响应
- return json([
- 'code' => 0,
- 'msg' => '图片生成成功',
- 'data' => [
- 'url' => $imageUrl
- ]
- ]);
- }
- /**
- * 学生端文生视频接口 - 用于生成视频
- */
- public function GetTxtToVideo(){
- $aiGateway = new AIGatewayService();
- $apiUrl = $aiGateway->config['videos']['api_url'];
- $apiKey = $aiGateway->config['videos']['api_key'];
- // 获取并验证参数
- $params = $this->request->param();
- // echo "<pre>";
- // print_r($params);
- // echo "<pre>";die;
- $postData = [
- 'prompt' => $params['prompt'],
- 'model' => $params['model'],
- 'seconds' => $params['duration'],
- 'size' => $params['size'],
- ];
- // 初始化CURL
- $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_POSTFIELDS, $postData);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
- curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
- // 创建临时文件来捕获详细的cURL输出
- $verbose = fopen('php://temp', 'w+');
- curl_setopt($ch, CURLOPT_STDERR, $verbose);
- // 执行请求
- $response = curl_exec($ch);
- //HTTP状态码
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // 获取详细的cURL调试信息
- rewind($verbose);
- //CURL调试信息
- $verboseLog = stream_get_contents($verbose);
- fclose($verbose);
- // 分离头部和主体
- $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- //响应头部
- $header = substr($response, 0, $header_size);
- //响应主体
- $body = substr($response, $header_size);
- // 检查CURL错误
- $curlError = curl_error($ch);
- curl_close($ch);
- $responseData = json_decode($body, true);
- // 检查API是否返回了错误信息
- if (isset($responseData['error'])) {
- $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
- 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
- 'error_message' => $errorMessage
- ]
- ]);
- }
- // 检查是否有自定义错误格式
- if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_code' => $responseData['code'],
- 'error_message' => $responseData['message']
- ]
- ]);
- }
- // 检查是否存在id字段
- if (!isset($responseData['id'])) {
- return json([
- 'code' => 1,
- 'msg' => '无法获取视频ID',
- 'data' => [
- 'response_data' => $responseData,
- 'http_code' => $httpCode
- ]
- ]);
- }
- // 1. 先检查视频状态
- $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'];
- $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
- // 检查视频状态
- if ($statusData['status'] !== 'completed') {
- return json([
- 'code' => 202,
- 'msg' => '视频尚未生成完成',
- 'data' => [
- 'video_id' => $responseData['id'],
- 'status' => $statusData['status'],
- 'progress' => $statusData['progress'],
- 'created_at' => $statusData['created_at'],
- 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
- ]
- ]);
- }
- // 2. 视频生成完成,准备下载
- $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $responseData['id'] . '/content';
- // 获取可选的variant参数
- $variant = $this->request->get('variant', '');
- if (!empty($variant)) {
- $apiUrl .= '?variant=' . urlencode($variant);
- }
- // 创建保存目录
- $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $filename = $responseData['id'] . '.mp4';
- $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
- $fullPath = $saveDir . DS . $filename;
- // 3. 下载视频
- $videoData = $this->downloadVideo($apiUrl, $apiKey);
- // 4. 保存视频文件
- if (file_put_contents($fullPath, $videoData) === false) {
- throw new Exception('视频保存失败');
- }
- // 确保路径使用正斜杠,并只保存相对路径部分
- $localPath = str_replace('\\', '/', $localPath);
- // 移除开头的斜杠,确保路径格式为uploads/videos/...
- $savePath = ltrim($localPath, '/');
- // 返回成功响应
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $responseData['id'],
- 'web_url' => $savePath
- ]
- ]);
- }
- /**
- * 学生端视频状态查询接口 - 用于通过video_id查询视频状态
- */
- public function Getvideo_id(){
- // 获取并验证参数
- $params = $this->request->param();
- $videoId = $params['video_id'] ?? '';
- // 验证video_id参数
- if (empty($videoId)) {
- return json([
- 'code' => 1,
- 'msg' => '缺少必要参数:video_id',
- 'data' => []
- ]);
- }
- $aiGateway = new AIGatewayService();
- // $apiUrl = $aiGateway->config['videos']['api_url'];
- $apiKey = $aiGateway->config['videos']['api_key'];
- $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId;
- // 先检查本地是否已经有该视频
- $localVideoPath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $videoId . '.mp4';
- if (file_exists($localVideoPath)) {
- // 视频已存在本地,直接返回
- $webPath = '/uploads/videos/' . date('Ymd') . '/' . $videoId . '.mp4';
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $videoId,
- 'web_url' => substr($webPath, 1) // 移除开头的斜杠
- ]
- ]);
- }
- // 检查视频状态
- $statusData = $this->fetchVideoStatus($apiUrl, $apiKey);
- // 检查视频状态
- if ($statusData['status'] !== 'completed') {
- return json([
- 'code' => 202,
- 'msg' => '视频尚未生成完成',
- 'data' => [
- 'video_id' => $videoId,
- 'status' => $statusData['status'],
- 'progress' => isset($statusData['progress']) ? $statusData['progress'] : 0,
- 'created_at' => $statusData['created_at'],
- 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
- ]
- ]);
- }
- // 视频生成完成,下载视频
- $downloadUrl = 'https://chatapi.onechats.ai/v1/videos/' . $videoId . '/content';
- // 获取可选的variant参数
- $variant = $this->request->get('variant', '');
- if (!empty($variant)) {
- $downloadUrl .= '?variant=' . urlencode($variant);
- }
- // 创建保存目录
- $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $filename = $videoId . '.mp4';
- $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
- $fullPath = $saveDir . DS . $filename;
- // 下载视频
- $videoData = $this->downloadVideo($downloadUrl, $apiKey);
- // 保存视频文件
- if (file_put_contents($fullPath, $videoData) === false) {
- throw new Exception('视频保存失败');
- }
- // 确保路径使用正斜杠,并只保存相对路径部分
- $localPath = str_replace(DIRECTORY_SEPARATOR, '/', $localPath);
- // 移除开头的斜杠,确保路径格式为uploads/videos/...
- $savePath = ltrim($localPath, '/');
- // 返回成功响应
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $videoId,
- 'web_url' => $savePath
- ]
- ]);
- }
- //获取视频列表
- public function Getvideolist(){
- if (!$this->request->isGet()) {
- $this->error('请求方式错误');
- }
- $params = $this->request->param();
- $search = input('search', '');
- $page = isset($params['page']) ? (int)$params['page'] : 1;
- $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
- $where = [];
- if (!empty($search)) {
- $where['prompt'] = ['like', '%' . $search . '%'];
- }
- $list = Db::name('video')->where('mod_rq', null)
- ->where($where)
- ->order('id desc')
- ->limit(($page - 1) * $limit, $limit)
- ->select();
- $total = Db::name('video')->where('mod_rq', null)
- ->where($where)
- ->count();
- $res['code'] = 0;
- $res['msg'] = '成功';
- $res['count'] = $total;
- $res['data'] = $list;
- return json($res);
- }
- /**
- * 文生视频/图生视频接口
- * @return \think\response\Json
- * @throws \Exception
- */
- //文生视频
- public function video(){
- $aiGateway = new AIGatewayService();
- $apiUrl = $aiGateway->config['videos']['api_url'];
- $apiKey = $aiGateway->config['videos']['api_key'];
- $params = $this->request->param();
- $postData = [
- 'prompt' => $params['prompt'],
- 'model' => $params['model'],
- 'seconds' => $params['seconds'],
- 'size' => $params['size'],
- ];
- // 初始化CURL
- $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_POSTFIELDS, $postData);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
- curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
- // 创建临时文件来捕获详细的cURL输出
- $verbose = fopen('php://temp', 'w+');
- curl_setopt($ch, CURLOPT_STDERR, $verbose);
- // 执行请求
- $response = curl_exec($ch);
- //HTTP状态码
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- // 获取详细的cURL调试信息
- rewind($verbose);
- //CURL调试信息
- $verboseLog = stream_get_contents($verbose);
- fclose($verbose);
- // 分离头部和主体
- $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- //响应头部
- $header = substr($response, 0, $header_size);
- //响应主体
- $body = substr($response, $header_size);
- // 检查CURL错误
- $curlError = curl_error($ch);
- curl_close($ch);
- $responseData = json_decode($body, true);
- // 检查API是否返回了错误信息
- if (isset($responseData['error'])) {
- $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
- 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
- 'error_message' => $errorMessage
- ]
- ]);
- }
- // 检查是否有自定义错误格式
- if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
- return json([
- 'code' => 1,
- 'msg' => '视频生成请求失败',
- 'data' => [
- 'error_code' => $responseData['code'],
- 'error_message' => $responseData['message']
- ]
- ]);
- }
- // 检查是否存在id字段
- if (!isset($responseData['id'])) {
- return json([
- 'code' => 1,
- 'msg' => '无法获取视频ID',
- 'data' => [
- 'response_data' => $responseData,
- 'http_code' => $httpCode
- ]
- ]);
- }
- $videoData = [
- 'video_id' => $responseData['id'],
- 'prompt' => $postData['prompt'],
- 'model' => $postData['model'],
- 'seconds' => $postData['seconds'],
- 'size' => $postData['size'],
- 'sys_rq' => date("Y-m-d H:i:s")
- ];
- // 尝试插入数据
- try {
- $res = Db::name('video')->insert($videoData);
- return json([
- 'code' => 0,
- 'msg' => '视频正在生成中',
- 'data ' => [
- 'video_id' => $responseData['id'],
- 'insert_result' => $res
- ]
- ]);
- } catch (Exception $e) {
- return json([
- 'code' => 1,
- 'msg' => '数据库操作失败',
- 'data' => [
- 'error_message' => $e->getMessage()
- ]
- ]);
- }
- }
- /**
- * 获取视频内容
- * 下载已完成的视频内容
- */
- public function videoContent(){
- // 从请求参数获取video_id,如果没有则使用默认值
- $video_id = input('get.video_id');
- $apiKey = 'sk-sWW1GFlnjbrDRb1DkMEzePIxgdvLK6cZt0Qg93yDMVP2z1yN';
- // 1. 先检查视频状态
- $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
- $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
- // 检查视频状态
- if ($statusData['status'] !== 'completed') {
- return json([
- 'code' => 202,
- 'msg' => '视频尚未生成完成',
- 'data' => [
- 'video_id' => $video_id,
- 'status' => $statusData['status'],
- 'progress' => $statusData['progress'],
- 'created_at' => $statusData['created_at'],
- 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
- ]
- ]);
- }
- // 2. 视频生成完成,准备下载
- $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
- // 获取可选的variant参数
- $variant = $this->request->get('variant', '');
- if (!empty($variant)) {
- $apiUrl .= '?variant=' . urlencode($variant);
- }
- // 创建保存目录
- $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
- if (!is_dir($saveDir)) {
- mkdir($saveDir, 0755, true);
- }
- // 生成唯一文件名
- $filename = $video_id . '.mp4';
- $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
- $fullPath = $saveDir . DS . $filename;
- // 3. 下载视频
- $videoData = $this->downloadVideo($apiUrl, $apiKey);
- // 4. 保存视频文件
- if (file_put_contents($fullPath, $videoData) === false) {
- throw new Exception('视频保存失败');
- }
- // 确保路径使用正斜杠,并只保存相对路径部分
- $localPath = str_replace('\\', '/', $localPath);
- // 移除开头的斜杠,确保路径格式为uploads/videos/...
- $savePath = ltrim($localPath, '/');
- // 将正确格式的文件路径存入数据库
- Db::name('video')->where('video_id', $video_id)->update([
- 'web_url' => $savePath
- ]);
- // 返回成功响应
- return json([
- 'code' => 0,
- 'msg' => '视频下载成功',
- 'data' => [
- 'video_id' => $video_id,
- 'local_path' => $localPath,
- 'web_url' => $savePath,
- 'file_size' => filesize($fullPath)
- ]
- ]);
- }
- /**
- * 获取视频状态
- */
- private function fetchVideoStatus($url, $apiKey) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPGET, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey,
- 'Accept: application/json'
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error) {
- throw new Exception('获取视频状态失败: ' . $error);
- }
- if ($httpCode < 200 || $httpCode >= 300) {
- throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
- }
- $data = json_decode($response, true);
- if (!is_array($data)) {
- throw new Exception('视频状态数据格式错误');
- }
- return $data;
- }
- /**
- * 下载视频文件
- */
- private function downloadVideo($url, $apiKey) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPGET, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer ' . $apiKey
- ]);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- $response = curl_exec($ch);
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error) {
- throw new Exception('视频下载失败: ' . $error);
- }
- if ($httpCode < 200 || $httpCode >= 300) {
- throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
- }
- return $response;
- }
- 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
- ];
- }
- /**
- * 查询队列列表
- * 统计文件对应的队列情况
- */
- 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
- ]
- ]);
- }
- /**
- * 获取 Redis 连接实例
- * @return \Redis|null Redis 实例或 null(如果连接失败)
- */
- private function getRedisConnection()
- {
- if (!class_exists('\Redis')) {
- return null;
- }
- $redis = new \Redis();
- $redis->connect('127.0.0.1', 6379);
- $redis->auth('123456');
- $redis->select(15);
- return $redis;
- }
- /**
- * 显示当前运行中的队列监听进程
- */
- public function viewQueueStatus()
- {
- $redis = $this->getRedisConnection();
- if (!$redis) {
- return json([
- 'code' => 1,
- 'msg' => 'Redis扩展未安装或未启用',
- 'data' => null
- ]);
- }
- $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 = $this->getRedisConnection();
- if (!$redis) {
- return json([
- 'code' => 1,
- 'msg' => 'Redis扩展未安装或未启用',
- 'data' => null
- ]);
- }
- $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
- // ]);
- // }
- // }
- /**
- * 新增模版
- */
- public function Add_Product_Template(){
- try {
- $params = $this->request->param();
- $chinese_description = $params['chinese_description'] ?? '';
- $template_image_url = $params['template_image_url'] ?? '';
- $template_name = $params['template_name'] ?? '';
- $size = $params['size'] ?? '';
- $style = $params['style'] ?? '';
- $type = $params['type'] ?? '';
- $user_id = $params['user_id'] ?? '';
- $seconds = $params['seconds'] ?? '';
- $video_id = $params['video_id'] ?? '';
- if (empty($template_name)) {
- return json(['code' => 1, 'msg' => '模板名称不能为空']);
- }
- $data = [
- 'toexamine' => "未审核",
- 'chinese_description' => $chinese_description,
- 'template_image_url' => $template_image_url,
- 'template_name' => $template_name,
- 'type' => $type,
- 'style' => $style,
- 'seconds' => $seconds,
- 'size' => $size,
- 'video_id' => $video_id,
- 'user_id' => $user_id,
- 'sys_rq' => date('Y-m-d'),
- 'create_time' => date('Y-m-d H:i:s')
- ];
- // echo "<pre>";
- // print_r($data);
- // echo "<pre>";die;
- $result = Db::name('product_template')->insert($data);
- if ($result) {
- return json(['code' => 0, 'msg' => '模板保存成功']);
- } else {
- return json(['code' => 1, 'msg' => '模板保存失败: 数据库操作未影响任何行']);
- }
- } catch (\Exception $e) {
- Log::record('模板保存异常: ' . $e->getMessage(), 'error');
- Log::record('异常堆栈: ' . $e->getTraceAsString(), 'error');
- return json(['code' => 1, 'msg' => '模板保存失败: ' . $e->getMessage()]);
- }
- }
- /**
- * 查询模版
- */
- public function product_template()
- {
- $params = $this->request->param();
- // 构建查询条件
- $where = [];
- if (!empty($params['search'])) {
- $where['chinese_description'] = ['like', '%' . $params['search'] . '%'];
- }
- // 查询模版表-style分类名称
- $products = Db::name('product_template')->order('id desc')->where($where)
- ->where('type','文生图')
- ->whereNull('mod_rq')
- ->select();
- $http_url = Db::name('http_url')->field('baseUrl,port')->find();
- if ($products && $http_url) {
- $base_url = !empty($http_url['baseUrl']) && !empty($http_url['port'])
- ? 'http://' . $http_url['baseUrl'] . ':' . $http_url['port'] : '';
- if ($base_url) {
- foreach ($products as &$val) {
- $val['template_image_url'] = $base_url . $val['template_image_url'];
- }
- }
- }
- return json([
- 'code' => 0,
- 'msg' => '请求成功',
- 'data' => $products
- ]);
- }
- /**
- *获取服务器URL地址和端口 IP地址:端口
- * 用于获取图片路径拼接时
- **/
- public function GetHttpUrl(){
- $data = Db::name('http_url')->find();
- $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
- $res = [
- 'code' => 0,
- 'msg' => '成功',
- 'data' => [
- 'id' => $data['id'],
- 'full_url' => $fullUrl,
- 'baseUrl' => $data['baseUrl'],
- 'port' => $data['port']
- ]
- ];
- return json($res);
- }
- }
|