WorkOrder.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\job\ImageJob;
  5. use app\service\AIGatewayService;
  6. use app\service\ImageService;
  7. use think\App;
  8. use think\Db;
  9. use think\Exception;
  10. use think\Log;
  11. use think\Queue;
  12. use think\queue\job\Redis;
  13. use think\Request;
  14. class WorkOrder extends Api{
  15. protected $noNeedLogin = ['*'];
  16. protected $noNeedRight = ['*'];
  17. public function index(){echo '访问成功';}
  18. /**
  19. * AI队列入口处理 出图接口
  20. * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
  21. */
  22. public function imageToText()
  23. {
  24. $params = $this->request->param();
  25. $service = new ImageService();
  26. $service->handleImage($params);
  27. $this->success('任务成功提交至队列');
  28. }
  29. /**
  30. * task_id:查询获取任务图片
  31. */
  32. public function GetImageStatus(){
  33. // //测试模拟返回前端图片数据
  34. // $taskInfo = [
  35. // 'status' => 'completed',
  36. // 'image' => '/uploads/Product/img2img-20260317152818-69b902924548d.png',
  37. // 'image_url' => '/uploads/Product/img2img-20260317152818-69b902924548d.png',
  38. // 'completed_at' => date('Y-m-d H:i:s')
  39. // ];
  40. // $taskInfo['image'] = Common::ossFullUrl((string)$taskInfo['image']);
  41. // $taskInfo['image_url'] = Common::ossFullUrl((string)$taskInfo['image_url']);
  42. // $res = [
  43. // 'code' => 0,
  44. // 'msg' => '查询成功',
  45. // 'data' => $taskInfo
  46. // ];
  47. // return json($res);die;
  48. $params = $this->request->param();
  49. $taskId = $params['task_id'];
  50. if (empty($taskId)) {
  51. $res = [
  52. 'code' => 1,
  53. 'msg' => '任务ID不能为空'
  54. ];
  55. return json($res);
  56. }
  57. //从Redis中获取任务状态
  58. $redis = getTaskRedis();
  59. $taskData = $redis->get("img_to_img_task:{$taskId}");
  60. if (!$taskData) {
  61. $taskData = $redis->get("text_to_image_task:{$taskId}");
  62. }
  63. if (!$taskData) {
  64. $res = [
  65. 'code' => 1,
  66. 'msg' => '任务不存在或已过期',
  67. ];
  68. return json($res);
  69. }
  70. $taskInfo = json_decode($taskData, true);
  71. if (!empty($taskInfo['image'])) {
  72. $taskInfo['image'] = Common::ossFullUrl((string)$taskInfo['image']);
  73. }
  74. if (!empty($taskInfo['image_url'])) {
  75. $taskInfo['image_url'] = Common::ossFullUrl((string)$taskInfo['image_url']);
  76. }
  77. $res = [
  78. 'code' => 0,
  79. 'msg' => '查询成功',
  80. 'data' => $taskInfo
  81. ];
  82. return json($res);
  83. }
  84. /**
  85. * 支持的AI任务类型枚举(前端传入的status_val需在该列表内)
  86. * 键:前端传入值,值:方法后缀( '前端传入值' => '方法后缀')
  87. */
  88. private static $AI_TASK_TYPES = [
  89. '图生文' => 'ImgToText',
  90. '文生文' => 'TextToText',
  91. '文生图' => 'TextToImg',
  92. '图生图' => 'ImgToImg'
  93. ];
  94. /**
  95. * AI模型接口统一调用入口
  96. * @description 接收前端AI请求,校验任务类型合法性,分发至对应处理方法,统一异常捕获
  97. * @return \think\response\Json 标准化JSON响应
  98. */
  99. public function callAIModelApi()
  100. {
  101. try {
  102. // 1. 获取并校验入参
  103. $params = $this->request->param();
  104. // echo "<pre>";
  105. // print_r($params);
  106. // echo "<pre>";die;
  107. $statusVal = $this->validateAndGetStatusVal($params);
  108. // 2. 映射并校验处理方法
  109. $method = $this->getHandleMethod($statusVal);
  110. // 3. 执行对应处理逻辑并返回响应
  111. return $this->$method($params);
  112. } catch (\InvalidArgumentException $e) {
  113. // 参数/方法异常(用户侧错误)
  114. return $this->jsonResponse(1, $e->getMessage());
  115. } catch (\Throwable $e) {
  116. // 系统异常(服务侧错误)
  117. \think\Log::error('AI接口处理异常:' . $e->getMessage() . ' | 任务类型:' . ($params['status_val'] ?? '未知') . ' | 异常行:' . $e->getLine());
  118. return $this->jsonResponse(1, '服务异常,请稍后重试');
  119. }
  120. }
  121. // -------------------------- 私有核心方法(通用逻辑) --------------------------
  122. /**
  123. * 校验并获取合法的任务类型
  124. * @param array $params 前端入参
  125. * @return string 合法的status_val
  126. * @throws \InvalidArgumentException 任务类型不合法时抛出
  127. */
  128. private function validateAndGetStatusVal(array $params): string
  129. {
  130. $statusVal = trim($params['status_val'] ?? '');
  131. // 空值校验
  132. if (empty($statusVal)) {
  133. throw new \InvalidArgumentException('任务类型不能为空');
  134. }
  135. // 合法性校验
  136. if (!array_key_exists($statusVal, self::$AI_TASK_TYPES)) {
  137. throw new \InvalidArgumentException('不支持的任务类型:' . $statusVal);
  138. }
  139. return $statusVal;
  140. }
  141. /**
  142. * 获取任务对应的处理方法名
  143. * @param string $statusVal 合法的任务类型
  144. * @return string 处理方法名(如handleAiImgToText)
  145. * @throws \InvalidArgumentException 方法未实现时抛出
  146. */
  147. private function getHandleMethod(string $statusVal): string
  148. {
  149. $methodSuffix = self::$AI_TASK_TYPES[$statusVal];
  150. $method = 'handleAi' . $methodSuffix;
  151. if (!method_exists($this, $method)) {
  152. throw new \InvalidArgumentException('任务类型暂未实现:' . $statusVal);
  153. }
  154. return $method;
  155. }
  156. /**
  157. * 通用JSON响应封装
  158. * @param int $code 响应码(0=成功,1=失败)
  159. * @param string $msg 响应信息
  160. * @param array $data 响应数据(可选)
  161. * @return \think\response\Json
  162. */
  163. private function jsonResponse(int $code, string $msg, array $data = []): \think\response\Json
  164. {
  165. $response = [
  166. 'code' => $code,
  167. 'msg' => $msg,
  168. 'time' => date('Y-m-d H:i:s')
  169. ];
  170. if (!empty($data)) {
  171. $response['data'] = $data;
  172. }
  173. return json($response);
  174. }
  175. /**
  176. * 任务类接口统一响应(带task_id的场景)
  177. * @param array $result 业务处理结果(需包含success字段)
  178. * @param string $failMsg 失败提示语
  179. * @return \think\response\Json
  180. */
  181. private function jsonTaskResponse(array $result, string $failMsg = '任务提交失败'): \think\response\Json
  182. {
  183. $isSuccess = isset($result['success']) && $result['success'];
  184. $data = $isSuccess ? ['task_id' => $result['task_id'] ?? ''] : [];
  185. $msg = $isSuccess ? ($result['message'] ?? '提交成功') : ($result['message'] ?? $failMsg);
  186. return $this->jsonResponse($isSuccess ? 0 : 1, $msg, $data);
  187. }
  188. // -------------------------- 业务处理方法(按任务类型拆分) --------------------------
  189. /**
  190. * 图生文任务处理:提交队列并返回提示
  191. * @param array $params 前端入参
  192. * @return \think\response\Json
  193. */
  194. private function handleAiImgToText(array $params): \think\response\Json
  195. {
  196. (new ImageService())->handleImgToText($params);
  197. return $this->jsonResponse(0, '正在优化提示词,请稍等.....');
  198. }
  199. /**
  200. * 文生文任务处理:生成话术并返回内容(支持产品内容更新)
  201. * @param array $params 前端入参
  202. * @return \think\response\Json
  203. */
  204. private function handleAiTextToText(array $params): \think\response\Json
  205. {
  206. // echo "<pre>";
  207. // print_r($params);
  208. // echo "<pre>";die;
  209. //构造生成提示词
  210. $promptTemplate = "\n请根据上述内容生成一段完整的话术,要求:\n"
  211. . "1. 内容必须是连贯的一段话,不要使用列表、分隔线或其他结构化格式\n"
  212. . "2. 不要包含非文本元素的描述\n"
  213. . "3. 不要添加任何额外的引导语、解释或开场白\n"
  214. . "4. 禁忌:不添加无关形容词,不修改产品核心信息,语言流畅自然";
  215. $prompt = ($params['prompt'] ?? '') . $promptTemplate;
  216. // 调用服务层生成内容
  217. $result = (new ImageService())->handleTextToText(
  218. $params['status_val'],
  219. $prompt,
  220. $params['model']
  221. );
  222. if (empty($result['success'])) {
  223. return $this->jsonResponse(1, $result['message'] ?? '生成失败');
  224. }
  225. $content = $result['data'] ?? '';
  226. //区分业务场景处理
  227. $isProductImageGeneration = ($params['status_type'] ?? '') === 'ProductImageGeneration';
  228. $isProductTemplateReplace = ($params['status_type'] ?? '') === 'ProductTemplateReplace';
  229. if (!$isProductImageGeneration && !$isProductTemplateReplace) {
  230. Db::name('product')->where('id', $params['id'])->update(['content' => $content]);
  231. }
  232. return $this->jsonResponse(0, '优化成功', ['content' => $content]);
  233. }
  234. /**
  235. * 文生图任务处理:提交任务并返回task_id
  236. * @param array $params 前端入参
  237. * @return \think\response\Json
  238. */
  239. private function handleAiTextToImg(array $params): \think\response\Json
  240. {
  241. $serviceResult = (new ImageService())->handleTextToImg($params);
  242. return $this->jsonTaskResponse($serviceResult, '文生图任务提交失败');
  243. }
  244. /**
  245. * 图生图任务处理:提交任务并返回task_id
  246. * @param array $params 前端入参
  247. * @return \think\response\Json
  248. */
  249. private function handleAiImgToImg(array $params): \think\response\Json
  250. {
  251. $serviceResult = (new ImageService())->handleImgToImg($params);
  252. return $this->jsonTaskResponse($serviceResult, '图生图任务提交失败');
  253. }
  254. /**
  255. * 即梦AI--创建视频任务接口
  256. * 首帧图 + 尾帧图 = 新效果视频
  257. */
  258. public function Create_ImgToVideo()
  259. {
  260. $apiUrl = '';
  261. $apiKey = '';
  262. $params = $this->request->param();
  263. $modelParams = [
  264. 'resolution' => $params['resolution'] ?? '720p', // 分辨率:480p, 720p, 1080p
  265. 'duration' => $params['duration'] ?? 5, // 视频时长(秒)
  266. 'camerafixed' => $params['camerafixed'] ?? false, // 相机固定
  267. 'watermark' => $params['watermark'] ?? true, // 水印
  268. 'aspect_ratio' => $params['aspect_ratio'] ?? '16:9' // 视频比例:16:9, 4:3, 1:1等
  269. ];
  270. // 构建提示词
  271. $prompt = $params['prompt'] ?? '';
  272. $prompt .= ' --resolution ' . $modelParams['resolution'];
  273. $prompt .= ' --duration ' . $modelParams['duration'];
  274. $prompt .= ' --camerafixed ' . ($modelParams['camerafixed'] ? 'true' : 'false');
  275. $prompt .= ' --watermark ' . ($modelParams['watermark'] ? 'true' : 'false');
  276. $prompt .= ' --aspect_ratio ' . $modelParams['aspect_ratio'];
  277. // 构建请求数据
  278. $data = [
  279. 'model' => 'doubao-seedance-1-0-pro-250528',//模型
  280. 'content' => [
  281. [
  282. 'type' => 'text',
  283. 'text' => $prompt
  284. ],
  285. [
  286. 'type' => 'image_url',
  287. 'image_url' => [
  288. 'url' => $params['first_image_url']// 首帧图片URL(参数)
  289. ],
  290. 'role' => 'first_image'
  291. ],
  292. [
  293. 'type' => 'image_url',
  294. 'image_url' => [
  295. 'url' => $params['last_image_url'] // 尾帧图片URL(参数)
  296. ],
  297. 'role' => 'last_image'
  298. ]
  299. ]
  300. ];
  301. // 转换为 JSON 字符串
  302. $jsonData = json_encode($data);
  303. // 初始化 cURL
  304. $ch = curl_init();
  305. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  306. curl_setopt($ch, CURLOPT_POST, true);
  307. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
  308. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  309. 'Content-Type: application/json',
  310. 'Authorization: Bearer ' . $apiKey
  311. ]);
  312. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  313. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
  314. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 超时时间
  315. // 执行请求
  316. $response = curl_exec($ch);
  317. // 检查 cURL 错误
  318. if (curl_errno($ch)) {
  319. $error = curl_error($ch);
  320. curl_close($ch);
  321. return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
  322. }
  323. curl_close($ch);
  324. // 解析响应
  325. $responseData = json_decode($response, true);
  326. // 检查 API 错误
  327. if (isset($responseData['error'])) {
  328. return json(['code' => 0, 'msg' => 'API 错误: ' . $responseData['error']['message']]);
  329. }
  330. // 获取任务 ID
  331. $taskId = $responseData['id'] ?? '';
  332. if (empty($taskId)) {
  333. return json(['code' => 0, 'msg' => '获取任务 ID 失败']);
  334. }
  335. // 返回结果
  336. return json([
  337. 'code' => 1,
  338. 'data' => [
  339. 'task_id' => $taskId,
  340. 'status' => $responseData['status'] ?? '',
  341. 'created_at' => $responseData['created_at'] ?? ''
  342. ]
  343. ]);
  344. }
  345. /**
  346. * 即梦AI--获取视频接口
  347. * 首帧图 + 尾帧图 = 新效果视频
  348. */
  349. public function Get_ImgToVideo()
  350. {
  351. $apiUrl = '';
  352. $apiKey = '';
  353. $params = $this->request->param();
  354. $taskId = $params['task_id'] ?? '';
  355. if (empty($taskId)) {
  356. return json(['code' => 0, 'msg' => '任务 ID 不能为空']);
  357. }
  358. // 查询任务状态
  359. $queryUrl = $apiUrl . '/' . $taskId;
  360. $ch2 = curl_init();
  361. curl_setopt($ch2, CURLOPT_URL, $queryUrl);
  362. curl_setopt($ch2, CURLOPT_HTTPHEADER, [
  363. 'Content-Type: application/json',
  364. 'Authorization: Bearer ' . $apiKey
  365. ]);
  366. curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
  367. curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
  368. curl_setopt($ch2, CURLOPT_TIMEOUT, 60); // 超时时间
  369. $queryResponse = curl_exec($ch2);
  370. // 检查 cURL 错误
  371. if (curl_errno($ch2)) {
  372. $error = curl_error($ch2);
  373. curl_close($ch2);
  374. return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
  375. }
  376. curl_close($ch2);
  377. // 解析查询响应
  378. $queryData = json_decode($queryResponse, true);
  379. // print_r($queryData);die;
  380. // 轮询任务状态,直到完成
  381. $maxPolls = 30; // 最大轮询次数
  382. $pollCount = 0;
  383. $taskStatus = $queryData['status'] ?? '';
  384. while (!in_array($taskStatus, ['completed', 'succeeded']) && $pollCount < $maxPolls) {
  385. sleep(5); // 每5秒轮询一次
  386. $pollCount++;
  387. // 再次查询任务状态
  388. $ch3 = curl_init();
  389. curl_setopt($ch3, CURLOPT_URL, $queryUrl);
  390. curl_setopt($ch3, CURLOPT_HTTPHEADER, [
  391. 'Content-Type: application/json',
  392. 'Authorization: Bearer ' . $apiKey
  393. ]);
  394. curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
  395. curl_setopt($ch3, CURLOPT_SSL_VERIFYPEER, false);
  396. curl_setopt($ch3, CURLOPT_TIMEOUT, 60);
  397. $pollResponse = curl_exec($ch3);
  398. curl_close($ch3);
  399. $pollData = json_decode($pollResponse, true);
  400. $taskStatus = $pollData['status'] ?? '';
  401. // 检查任务是否失败
  402. if ($taskStatus === 'failed') {
  403. return json(['code' => 0, 'msg' => '任务执行失败']);
  404. }
  405. }
  406. // 如果任务已经成功,直接使用 $queryData
  407. if (empty($pollData) && isset($queryData['status']) && $queryData['status'] === 'succeeded') {
  408. $pollData = $queryData;
  409. }
  410. // 检查轮询是否超时
  411. if (!in_array($taskStatus, ['completed', 'succeeded'])) {
  412. return json(['code' => 0, 'msg' => '任务执行超时']);
  413. }
  414. // 获取视频 URL
  415. $videoUrl = $pollData['content']['video_url'] ?? '';
  416. if (empty($videoUrl)) {
  417. return json(['code' => 0, 'msg' => '获取视频 URL 失败', 'data' => ['pollData' => $pollData]]);
  418. }
  419. // 确保保存目录存在
  420. $saveDir = ROOT_PATH . 'public/uploads/ceshi/';
  421. if (!is_dir($saveDir)) {
  422. mkdir($saveDir, 0755, true);
  423. }
  424. // 生成保存文件名
  425. $fileName = $taskId . '.mp4';
  426. $savePath = $saveDir . '/' . $fileName;
  427. // 下载视频
  428. // 设置超时时间为300秒(5分钟)
  429. $context = stream_context_create(['http' => ['timeout' => 300]]);
  430. $videoContent = file_get_contents($videoUrl, false, $context);
  431. if ($videoContent === false) {
  432. return json(['code' => 0, 'msg' => '下载视频失败', 'data' => ['videoUrl' => $videoUrl]]);
  433. }
  434. // 保存视频到文件
  435. $saveResult = file_put_contents($savePath, $videoContent);
  436. if ($saveResult === false) {
  437. return json(['code' => 0, 'msg' => '保存视频失败', 'data' => ['savePath' => $savePath, 'dirWritable' => is_writable($saveDir)]]);
  438. }
  439. // 生成视频的访问 URL
  440. $videoAccessUrl = '/uploads/ceshi/' . $fileName;
  441. // 返回结果
  442. return json([
  443. 'code' => 1,
  444. 'data' => [
  445. 'task_id' => $taskId,
  446. 'status' => $taskStatus,
  447. 'video_url' => $videoAccessUrl,
  448. 'save_path' => $savePath
  449. ]
  450. ]);
  451. }
  452. //获取视频列表
  453. public function Getvideolist(){
  454. if (!$this->request->isGet()) {
  455. $this->error('请求方式错误');
  456. }
  457. $params = $this->request->param();
  458. $search = input('search', '');
  459. $page = isset($params['page']) ? (int)$params['page'] : 1;
  460. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  461. $where = [];
  462. if (!empty($search)) {
  463. $where['prompt'] = ['like', '%' . $search . '%'];
  464. }
  465. $list = Db::name('video')->where('mod_rq', null)
  466. ->where($where)
  467. ->order('id desc')
  468. ->limit(($page - 1) * $limit, $limit)
  469. ->select();
  470. $total = Db::name('video')->where('mod_rq', null)
  471. ->where($where)
  472. ->count();
  473. $res['code'] = 0;
  474. $res['msg'] = '成功';
  475. $res['count'] = $total;
  476. $res['data'] = $list;
  477. return json($res);
  478. }
  479. /**
  480. * 文生视频/图生视频接口
  481. */
  482. //文生视频
  483. public function video(){
  484. $apiUrl = '';
  485. $apiKey = '';
  486. $params = $this->request->param();
  487. $postData = [
  488. 'prompt' => $params['prompt'],
  489. 'model' => $params['model'],
  490. 'seconds' => $params['seconds'],
  491. 'size' => $params['size'],
  492. ];
  493. // 初始化CURL
  494. $ch = curl_init();
  495. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  496. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  497. curl_setopt($ch, CURLOPT_POST, true);
  498. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  499. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  500. 'Authorization: Bearer ' . $apiKey
  501. ]);
  502. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  503. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  504. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  505. curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
  506. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
  507. // 创建临时文件来捕获详细的cURL输出
  508. $verbose = fopen('php://temp', 'w+');
  509. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  510. // 执行请求
  511. $response = curl_exec($ch);
  512. //HTTP状态码
  513. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  514. // 获取详细的cURL调试信息
  515. rewind($verbose);
  516. //CURL调试信息
  517. $verboseLog = stream_get_contents($verbose);
  518. fclose($verbose);
  519. // 分离头部和主体
  520. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  521. //响应头部
  522. $header = substr($response, 0, $header_size);
  523. //响应主体
  524. $body = substr($response, $header_size);
  525. // 检查CURL错误
  526. $curlError = curl_error($ch);
  527. curl_close($ch);
  528. $responseData = json_decode($body, true);
  529. echo "<pre>";
  530. print_r($responseData);
  531. echo "<pre>";die;
  532. // 检查API是否返回了错误信息
  533. if (isset($responseData['error'])) {
  534. $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
  535. return json([
  536. 'code' => 1,
  537. 'msg' => '视频生成请求失败',
  538. 'data' => [
  539. 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
  540. 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
  541. 'error_message' => $errorMessage
  542. ]
  543. ]);
  544. }
  545. // 检查是否有自定义错误格式
  546. if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
  547. return json([
  548. 'code' => 1,
  549. 'msg' => '视频生成请求失败',
  550. 'data' => [
  551. 'error_code' => $responseData['code'],
  552. 'error_message' => $responseData['message']
  553. ]
  554. ]);
  555. }
  556. // 检查是否存在id字段
  557. if (!isset($responseData['id'])) {
  558. return json([
  559. 'code' => 1,
  560. 'msg' => '无法获取视频ID',
  561. 'data' => [
  562. 'response_data' => $responseData,
  563. 'http_code' => $httpCode
  564. ]
  565. ]);
  566. }
  567. $videoData = [
  568. 'video_id' => $responseData['id'],
  569. 'prompt' => $postData['prompt'],
  570. 'model' => $postData['model'],
  571. 'seconds' => $postData['seconds'],
  572. 'size' => $postData['size'],
  573. 'sys_rq' => date("Y-m-d H:i:s")
  574. ];
  575. echo "<pre>";
  576. print_r($videoData);
  577. echo "<pre>";die;
  578. // 尝试插入数据
  579. try {
  580. $res = Db::name('video')->insert($videoData);
  581. return json([
  582. 'code' => 0,
  583. 'msg' => '视频正在生成中',
  584. 'data ' => [
  585. 'video_id' => $responseData['id'],
  586. 'insert_result' => $res
  587. ]
  588. ]);
  589. } catch (Exception $e) {
  590. return json([
  591. 'code' => 1,
  592. 'msg' => '数据库操作失败',
  593. 'data' => [
  594. 'error_message' => $e->getMessage()
  595. ]
  596. ]);
  597. }
  598. }
  599. /**
  600. * 获取视频内容
  601. * 下载已完成的视频内容
  602. */
  603. public function videoContent(){
  604. // 从请求参数获取video_id,如果没有则使用默认值
  605. $video_id = input('get.video_id');
  606. $apiKey = '';
  607. // 1. 先检查视频状态
  608. $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
  609. $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
  610. // 检查视频状态
  611. if ($statusData['status'] !== 'completed') {
  612. return json([
  613. 'code' => 202,
  614. 'msg' => '视频尚未生成完成',
  615. 'data' => [
  616. 'video_id' => $video_id,
  617. 'status' => $statusData['status'],
  618. 'progress' => $statusData['progress'],
  619. 'created_at' => $statusData['created_at'],
  620. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  621. ]
  622. ]);
  623. }
  624. // 2. 视频生成完成,准备下载
  625. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
  626. // 获取可选的variant参数
  627. $variant = $this->request->get('variant', '');
  628. if (!empty($variant)) {
  629. $apiUrl .= '?variant=' . urlencode($variant);
  630. }
  631. // 创建保存目录
  632. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  633. if (!is_dir($saveDir)) {
  634. mkdir($saveDir, 0755, true);
  635. }
  636. // 生成唯一文件名
  637. $filename = $video_id . '.mp4';
  638. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  639. $fullPath = $saveDir . DS . $filename;
  640. // 3. 下载视频
  641. $videoData = $this->downloadVideo($apiUrl, $apiKey);
  642. // 4. 保存视频文件
  643. if (file_put_contents($fullPath, $videoData) === false) {
  644. throw new Exception('视频保存失败');
  645. }
  646. // 确保路径使用正斜杠,并只保存相对路径部分
  647. $localPath = str_replace('\\', '/', $localPath);
  648. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  649. $savePath = ltrim($localPath, '/');
  650. // 将正确格式的文件路径存入数据库
  651. Db::name('video')->where('video_id', $video_id)->update([
  652. 'web_url' => $savePath
  653. ]);
  654. // 返回成功响应
  655. return json([
  656. 'code' => 0,
  657. 'msg' => '视频下载成功',
  658. 'data' => [
  659. 'video_id' => $video_id,
  660. 'local_path' => $localPath,
  661. 'web_url' => $savePath,
  662. 'file_size' => filesize($fullPath)
  663. ]
  664. ]);
  665. }
  666. /**
  667. * 获取视频状态
  668. */
  669. private function fetchVideoStatus($url, $apiKey) {
  670. $ch = curl_init();
  671. curl_setopt($ch, CURLOPT_URL, $url);
  672. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  673. curl_setopt($ch, CURLOPT_HTTPGET, true);
  674. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  675. 'Authorization: Bearer ' . $apiKey,
  676. 'Accept: application/json'
  677. ]);
  678. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  679. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  680. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  681. $response = curl_exec($ch);
  682. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  683. $error = curl_error($ch);
  684. curl_close($ch);
  685. if ($error) {
  686. throw new Exception('获取视频状态失败: ' . $error);
  687. }
  688. if ($httpCode < 200 || $httpCode >= 300) {
  689. throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
  690. }
  691. $data = json_decode($response, true);
  692. if (!is_array($data)) {
  693. throw new Exception('视频状态数据格式错误');
  694. }
  695. return $data;
  696. }
  697. /**
  698. * 下载视频文件
  699. */
  700. private function downloadVideo($url, $apiKey) {
  701. $ch = curl_init();
  702. curl_setopt($ch, CURLOPT_URL, $url);
  703. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  704. curl_setopt($ch, CURLOPT_HTTPGET, true);
  705. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  706. 'Authorization: Bearer ' . $apiKey
  707. ]);
  708. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  709. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  710. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  711. $response = curl_exec($ch);
  712. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  713. $error = curl_error($ch);
  714. curl_close($ch);
  715. if ($error) {
  716. throw new Exception('视频下载失败: ' . $error);
  717. }
  718. if ($httpCode < 200 || $httpCode >= 300) {
  719. throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
  720. }
  721. return $response;
  722. }
  723. private function sendPostRequest($url, $data, $apiKey)
  724. {
  725. $ch = curl_init();
  726. curl_setopt($ch, CURLOPT_URL, $url);
  727. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  728. curl_setopt($ch, CURLOPT_POST, true);
  729. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  730. 'Authorization: Bearer ' . $apiKey,
  731. 'Accept: application/json',
  732. 'Content-Type: application/json'
  733. ]);
  734. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  735. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  736. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  737. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
  738. $response = curl_exec($ch);
  739. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  740. $error = curl_error($ch);
  741. curl_close($ch);
  742. return [
  743. 'response' => $response,
  744. 'http_code' => $httpCode,
  745. 'error' => $error
  746. ];
  747. }
  748. /**
  749. * 查询模版
  750. */
  751. public function product_template()
  752. {
  753. $params = $this->request->param();
  754. if (!$this->request->isGet()) {
  755. $this->error('请求方法错误');
  756. }
  757. $page = isset($params['page']) ? (int)$params['page'] : 1;
  758. $limit = isset($params['limit']) ? (int)$params['limit'] : 30;
  759. $where = [];
  760. if (!empty($params['search'])) {
  761. $where['id|chinese_description|template_name|style'] = ['like', '%' . $params['search'] . '%'];
  762. }
  763. // toexamine / release:用 isset + 非空串,避免 empty(0) 导致「未发布」无法筛选;release 建议库中为 0/1
  764. if (isset($params['toexamine']) && $params['toexamine'] !== '') {
  765. $where['toexamine'] = $params['toexamine'];
  766. }
  767. if (isset($params['release']) && $params['release'] !== '') {
  768. $where['release'] = is_numeric($params['release']) ? (int) $params['release'] : $params['release'];
  769. }
  770. $isSuperAdmin = false;
  771. if (!empty($params['sys_id']) && $params['sys_id'] == '超级管理员') {
  772. $isSuperAdmin = true;
  773. }
  774. if (!$isSuperAdmin && !empty($params['sys_id'])) {
  775. $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
  776. $products = Db::name('product_template')->order('id desc')->where($where)
  777. ->whereNull('mod_rq')
  778. ->limit(($page - 1) * $limit, $limit)
  779. ->select();
  780. }else{
  781. $products = Db::name('product_template')->order('id desc')->where($where)
  782. ->whereNull('mod_rq')
  783. ->limit(($page - 1) * $limit, $limit)
  784. ->select();
  785. }
  786. $total = Db::name('product_template')->where($where)
  787. ->whereNull('mod_rq')
  788. ->count();
  789. foreach ($products as &$item) {
  790. if (!empty($item['template_image_url'])) {
  791. $item['template_image_url'] = Common::ossFullUrl((string)$item['template_image_url']);
  792. }
  793. if (!empty($item['thumbnail_image'])) {
  794. $item['thumbnail_image'] = Common::ossFullUrl((string)$item['thumbnail_image']);
  795. }
  796. if (array_key_exists('chinese_description', $item)) {
  797. $item['chinese_description'] = Common::decodeChineseDescriptionForApi($item['chinese_description']);
  798. }
  799. if (!empty($item['page_image_urls'])) {
  800. $arr = json_decode((string) $item['page_image_urls'], true);
  801. if (is_array($arr)) {
  802. foreach ($arr as &$pu) {
  803. if ($pu !== null && $pu !== '') {
  804. $pu = Common::ossFullUrl((string) $pu);
  805. }
  806. }
  807. unset($pu);
  808. $item['page_image_urls'] = $arr;
  809. }
  810. }
  811. }
  812. unset($item);
  813. return json([
  814. 'code' => 0,
  815. 'msg' => '请求成功',
  816. 'count' => $total,
  817. 'data' => $products
  818. ]);
  819. }
  820. /**
  821. * 新增模版
  822. * (暂时无用)
  823. */
  824. // public function Add_Product_Template(){
  825. // try {
  826. // $params = $this->request->param();
  827. //
  828. // $chinese_description = $params['chinese_description'] ?? '';
  829. // $template_image_url = $params['template_image_url'] ?? '';
  830. // $template_name = $params['template_name'] ?? '';
  831. // $size = $params['size'] ?? '';
  832. // $style = $params['style'] ?? '';
  833. // $type = $params['type'] ?? '';
  834. // $user_id = $params['user_id'] ?? '';
  835. // $seconds = $params['seconds'] ?? '';
  836. // $video_id = $params['video_id'] ?? '';
  837. //
  838. // if (empty($template_name)) {
  839. // return json(['code' => 1, 'msg' => '模板名称不能为空']);
  840. // }
  841. //
  842. // $data = [
  843. // 'toexamine' => "未审核",
  844. // 'chinese_description' => $chinese_description,
  845. // 'template_image_url' => $template_image_url,
  846. // 'template_name' => $template_name,
  847. // 'type' => $type,
  848. // 'style' => $style,
  849. // 'seconds' => $seconds,
  850. // 'size' => $size,
  851. // 'video_id' => $video_id,
  852. // 'user_id' => $user_id,
  853. // 'sys_rq' => date('Y-m-d'),
  854. // 'create_time' => date('Y-m-d H:i:s')
  855. // ];
  856. // $result = Db::name('product_template')->insert($data);
  857. // if ($result) {
  858. // return json(['code' => 0, 'msg' => '模板保存成功']);
  859. // } else {
  860. // return json(['code' => 1, 'msg' => '模板保存失败: 数据库操作未影响任何行']);
  861. // }
  862. // } catch (\Exception $e) {
  863. // Log::record('模板保存异常: ' . $e->getMessage(), 'error');
  864. // Log::record('异常堆栈: ' . $e->getTraceAsString(), 'error');
  865. // return json(['code' => 1, 'msg' => '模板保存失败: ' . $e->getMessage()]);
  866. // }
  867. // }
  868. /**
  869. * 获取 AI 模型配置
  870. * status 1 = 启用 0 = 禁用(同一模型内的优先级,数值越小越优先)
  871. * model_type 支持多能力逗号间隔(如 文生图,图生图),传参精确匹配某一能力
  872. * 可选参数:manage=1 时返回全部(含禁用),用于管理端
  873. */
  874. public function GetAIModel(){
  875. $params = $this->request->param();
  876. $query = Db::name('ai_model');
  877. if (empty($params['manage'])) {
  878. $query->where('status', '1');
  879. }
  880. if (!empty($params['model_type'])) {
  881. $query->whereRaw('FIND_IN_SET(:mt, model_type) > 0', ['mt' => trim($params['model_type'])]);
  882. }
  883. if (!empty($params['supplier'])) {
  884. $query->where('supplier', 'like', '%' . $params['supplier'] . '%');
  885. }
  886. if (!empty($params['model_name'])) {
  887. $query->where('model_name|model_alias', 'like', '%' . $params['model_name'] . '%');
  888. }
  889. $list = $query
  890. ->field('id,model_alias,model_group,model_name,model_type,sort,status,supplier')
  891. ->order('sort ASC, id ASC')->select();
  892. return json([
  893. 'code' => 0,
  894. 'msg' => '成功',
  895. 'data' => $list
  896. ]);
  897. }
  898. /**
  899. * 新增 AI 模型配置
  900. * POST: status, supplier, api_key, api_url, model_group, model_name, model_alias, model_type, sort
  901. * model_type 多能力用逗号间隔,如:文生图,图生图
  902. */
  903. public function AddAIModel(){
  904. $params = $this->request->param();
  905. $required = ['api_url', 'api_key', 'model_name', 'model_type'];
  906. foreach ($required as $k) {
  907. if (empty(trim($params[$k] ?? ''))) {
  908. return json(['code' => 1, 'msg' => $k . ' 不能为空']);
  909. }
  910. }
  911. $insert = [
  912. 'status' => $params['status'],
  913. 'supplier' => trim($params['supplier']),
  914. 'api_key' => trim($params['api_key']),
  915. 'api_url' => trim($params['api_url']),
  916. 'model_group' => trim($params['model_group']),
  917. 'model_name' => trim($params['model_name']),
  918. 'model_alias' => trim($params['model_alias']),
  919. 'model_type' => trim($params['model_type']),
  920. 'sort' => isset($params['sort']) ? intval($params['sort']) : 0,
  921. ];
  922. try {
  923. Db::name('ai_model')->insert($insert);
  924. return json(['code' => 0, 'msg' => '新增成功']);
  925. } catch (\Exception $e) {
  926. return json(['code' => 1, 'msg' => '新增失败: ' . $e->getMessage()]);
  927. }
  928. }
  929. /**
  930. * 修改 AI 模型配置
  931. * POST: id(必填), 其余字段同新增
  932. */
  933. public function UpdateAIModel(){
  934. $params = $this->request->param();
  935. if (empty($params['id'])) {
  936. return json(['code' => 1, 'msg' => 'id 不能为空']);
  937. }
  938. $id = intval($params['id']);
  939. $exists = Db::name('ai_model')->where('id', $id)->find();
  940. if (!$exists) {
  941. return json(['code' => 1, 'msg' => '记录不存在']);
  942. }
  943. $update = [];
  944. $fields = ['status', 'supplier', 'api_key', 'api_url', 'model_group', 'model_name', 'model_alias', 'model_type', 'sort'];
  945. foreach ($fields as $f) {
  946. if (array_key_exists($f, $params)) {
  947. $update[$f] = $f === 'sort' ? intval($params[$f]) : trim($params[$f] ?? '');
  948. }
  949. }
  950. if (empty($update)) {
  951. return json(['code' => 1, 'msg' => '无有效修改字段']);
  952. }
  953. try {
  954. Db::name('ai_model')->where('id', $id)->update($update);
  955. return json(['code' => 0, 'msg' => '修改成功']);
  956. } catch (\Exception $e) {
  957. return json(['code' => 1, 'msg' => '修改失败: ' . $e->getMessage()]);
  958. }
  959. }
  960. /**
  961. * 用于获取所有产品记录
  962. **/
  963. public function GetProductList(){
  964. $params = $this->request->param();
  965. $page = max(1, intval($params['page'] ?? 1));
  966. $pageSize = min(100, max(1, intval($params['limit'] ?? 30)));
  967. // 构建查询条件
  968. $where = [];
  969. if (!empty($params['search'])) {
  970. $where['prompt|model'] = ['like', '%' . $params['search'] . '%'];
  971. }
  972. if (!empty($params['sys_id'])) {
  973. $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
  974. }
  975. // $isSuperAdmin = false;
  976. // if (!empty($params['sys_id']) && $params['sys_id'] == '超级管理员') {
  977. // $isSuperAdmin = true;
  978. // }
  979. //
  980. // if (!$isSuperAdmin && !empty($params['sys_id'])) {
  981. // 普通
  982. // }else{
  983. //
  984. // }
  985. $prompt = Db::name('product_image_generate')->field('prompt')->where($where)->group('prompt')->order('id desc')->select();
  986. $data = Db::name('product_image_generate')->where($where)->order('id desc')->page($page, $pageSize)->select();
  987. $count = Db::name('product_image_generate')->field('prompt')->where($where)->order('id desc')->count();
  988. foreach ($data as &$item) {
  989. if (!empty($item['generated_image']) || !empty($item['product_img']) || !empty($item['reference_image'])) {
  990. $item['generated_image'] = Common::ossFullUrl((string)$item['generated_image']);
  991. $item['product_img'] = Common::ossFullUrl((string)$item['product_img']);
  992. $item['reference_image'] = Common::ossFullUrl((string)$item['reference_image']);
  993. }
  994. }
  995. unset($item);
  996. return json([
  997. 'code' => 0,
  998. 'msg' => '成功',
  999. 'count' => $count,
  1000. 'prompt' => $prompt,
  1001. 'data' => $data
  1002. ]);
  1003. }
  1004. /**
  1005. * 查询队列列表
  1006. * 统计文件对应的队列情况
  1007. */
  1008. public function get_queue_logs()
  1009. {
  1010. $params = $this->request->param('old_image_file', '');
  1011. $queue_logs = Db::name('queue_logs')
  1012. ->where('old_image_file', $params)
  1013. ->order('id desc')
  1014. ->select();
  1015. $result = []; //初始化变量,避免未定义错误
  1016. foreach ($queue_logs as &$log) {
  1017. $taskId = $log['id'];
  1018. $statusCount = Db::name('image_task_log')
  1019. ->field('status, COUNT(*) as count')
  1020. ->where('task_id', $taskId)
  1021. ->where('mod_rq', null)
  1022. ->group('status')
  1023. ->select();
  1024. $log['已完成数量'] = 0;
  1025. $log['处理中数量'] = 0;
  1026. $log['排队中的数量'] = 0;
  1027. $log['失败数量'] = 0;
  1028. foreach ($statusCount as $item) {
  1029. switch ($item['status']) {
  1030. case 0:
  1031. $log['排队中的数量'] = $item['count'];
  1032. break;
  1033. case 1:
  1034. $log['处理中数量'] = $item['count'];
  1035. break;
  1036. case 2:
  1037. $log['已完成数量'] = $item['count'];
  1038. break;
  1039. case -1:
  1040. $log['失败数量'] = $item['count'];
  1041. break;
  1042. }
  1043. }
  1044. // if ($log['排队中的数量'] >$log['已完成数量']) {
  1045. // $result[] = $log;
  1046. // }
  1047. if ($log['排队中的数量']) {
  1048. $result[] = $log;
  1049. }
  1050. // if ($log['处理中数量'] >= 0) {
  1051. // $result[] = $log;
  1052. // }
  1053. }
  1054. return json([
  1055. 'code' => 0,
  1056. 'msg' => '查询成功',
  1057. 'data' => $result,
  1058. 'count' => count($result)
  1059. ]);
  1060. }
  1061. /**
  1062. * 查询总队列状态(统计当前处理的数据量)
  1063. */
  1064. public function queueStats()
  1065. {
  1066. $statusList = Db::name('image_task_log')
  1067. ->field('status, COUNT(*) as total')
  1068. ->where('mod_rq', null)
  1069. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1070. ->group('status')
  1071. ->select();
  1072. $statusCount = [];
  1073. foreach ($statusList as $item) {
  1074. $statusCount[$item['status']] = $item['total'];
  1075. }
  1076. // 总数为所有状态和
  1077. $total = array_sum($statusCount);
  1078. //获取队列当前状态
  1079. $statusText = Db::name('queue_logs')->order('id desc')->value('status');
  1080. return json([
  1081. 'code' => 0,
  1082. 'msg' => '获取成功',
  1083. 'data' => [
  1084. '总任务数' => $total,
  1085. '待处理' => $statusCount[0] ?? 0,
  1086. '处理中' => $statusCount[1] ?? 0,
  1087. '成功' => $statusCount[2] ?? 0,
  1088. '失败' => $statusCount[-1] ?? 0,
  1089. '当前状态' => $statusText
  1090. ]
  1091. ]);
  1092. }
  1093. /**
  1094. * 获取 Redis 连接实例
  1095. * @return \Redis|null Redis 实例或 null(如果连接失败)
  1096. */
  1097. private function getRedisConnection()
  1098. {
  1099. if (!class_exists('\Redis')) {
  1100. return null;
  1101. }
  1102. return getTaskRedis();
  1103. }
  1104. /**
  1105. * 显示当前运行中的队列监听进程
  1106. */
  1107. public function viewQueueStatus()
  1108. {
  1109. $redis = $this->getRedisConnection();
  1110. if (!$redis) {
  1111. return json([
  1112. 'code' => 1,
  1113. 'msg' => 'Redis扩展未安装或未启用',
  1114. 'data' => null
  1115. ]);
  1116. }
  1117. $key = 'queues:imgtotxt';
  1118. // 判断 key 是否存在,避免报错
  1119. if (!$redis->exists($key)) {
  1120. return json([
  1121. 'code' => 0,
  1122. 'msg' => '查询成功,队列为空',
  1123. 'count' => 0,
  1124. 'tasks_preview' => []
  1125. ]);
  1126. }
  1127. $count = $redis->lLen($key);
  1128. $list = $redis->lRange($key, 0, 9);
  1129. // 解码 JSON 内容,确保每一项都有效
  1130. $parsed = array_filter(array_map(function ($item) {
  1131. return json_decode($item, true);
  1132. }, $list), function ($item) {
  1133. return !is_null($item);
  1134. });
  1135. return json([
  1136. 'code' => 0,
  1137. 'msg' => '查询成功',
  1138. 'count' => $count,
  1139. 'tasks_preview' => $parsed
  1140. ]);
  1141. }
  1142. /**
  1143. * 清空队列并删除队列日志记录
  1144. */
  1145. public function stopQueueProcesses()
  1146. {
  1147. Db::name('image_task_log')
  1148. ->where('log', '队列中')
  1149. ->whereOr('status', 1)
  1150. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1151. ->update([
  1152. 'status' => "-1",
  1153. 'log' => '清空取消队列',
  1154. 'mod_rq' => date('Y-m-d H:i:s')
  1155. ]);
  1156. Db::name('image_task_log')
  1157. ->whereLike('log', '%处理中%')
  1158. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1159. ->update([
  1160. 'status' => "-1",
  1161. 'log' => '清空取消队列',
  1162. 'mod_rq' => date('Y-m-d H:i:s')
  1163. ]);
  1164. $redis = $this->getRedisConnection();
  1165. if (!$redis) {
  1166. return json([
  1167. 'code' => 1,
  1168. 'msg' => 'Redis扩展未安装或未启用',
  1169. 'data' => null
  1170. ]);
  1171. }
  1172. $key_txttoimg = 'queues:txttoimg:reserved';
  1173. $key_txttotxt = 'queues:txttotxt:reserved';
  1174. $key_imgtotxt = 'queues:imgtotxt:reserved';
  1175. $key_imgtoimg = 'queues:imgtoimg:reserved';
  1176. // 清空 Redis 队列
  1177. $redis->del($key_txttoimg);
  1178. $redis->del($key_txttotxt);
  1179. $redis->del($key_imgtotxt);
  1180. $redis->del($key_imgtoimg);
  1181. $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);
  1182. // if ($count === 0) {
  1183. // return json([
  1184. // 'code' => 1,
  1185. // 'msg' => '暂无队列需要停止'
  1186. // ]);
  1187. // }
  1188. return json([
  1189. 'code' => 0,
  1190. 'msg' => '成功停止队列任务'
  1191. ]);
  1192. }
  1193. /**
  1194. * 开启队列任务
  1195. * 暂时用不到、服务器已开启自动开启队列模式
  1196. */
  1197. // public function kaiStats()
  1198. // {
  1199. // // 判断是否已有监听进程在运行
  1200. // $check = shell_exec("ps aux | grep 'queue:listen' | grep -v grep");
  1201. // if ($check) {
  1202. // return json([
  1203. // 'code' => 1,
  1204. // 'msg' => '监听进程已存在,请勿重复启动'
  1205. // ]);
  1206. // }
  1207. // // 启动监听
  1208. // $command = 'nohup php think queue:listen --queue --timeout=300 --sleep=3 --memory=256 > /var/log/job_queue.log 2>&1 &';
  1209. // exec($command, $output, $status);
  1210. // if ($status === 0) {
  1211. // return json([
  1212. // 'code' => 0,
  1213. // 'msg' => '队列监听已启动'
  1214. // ]);
  1215. // } else {
  1216. // return json([
  1217. // 'code' => 1,
  1218. // 'msg' => '队列启动失败',
  1219. // 'output' => $output
  1220. // ]);
  1221. // }
  1222. // }
  1223. /**
  1224. *获取服务器URL地址和端口 IP地址:端口
  1225. * 用于获取图片路径拼接时
  1226. **/
  1227. public function GetHttpUrl(){
  1228. $data = Db::name('http_url')->find();
  1229. $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
  1230. $res = [
  1231. 'code' => 0,
  1232. 'msg' => '成功',
  1233. 'data' => [
  1234. 'id' => $data['id'],
  1235. 'full_url' => $fullUrl,
  1236. 'baseUrl' => $data['baseUrl'],
  1237. 'port' => $data['port']
  1238. ]
  1239. ];
  1240. return json($res);
  1241. }
  1242. }