WorkOrder.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793
  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. use app\api\controller\Common;
  15. class WorkOrder extends Api{
  16. protected $noNeedLogin = ['*'];
  17. protected $noNeedRight = ['*'];
  18. public function index(){echo '访问成功';}
  19. /**
  20. * AI队列入口处理 出图接口
  21. * 此方法处理图像转换为文本的请求,将图像信息存入队列以供后续处理。
  22. */
  23. public function imageToText()
  24. {
  25. $params = $this->request->param();
  26. $service = new ImageService();
  27. $service->handleImage($params);
  28. $this->success('任务成功提交至队列');
  29. }
  30. /**
  31. * task_id:查询获取任务图片
  32. */
  33. public function GetImageStatus(){
  34. $params = $this->request->param();
  35. $taskId = $params['task_id'];
  36. if (empty($taskId)) {
  37. $res = [
  38. 'code' => 1,
  39. 'msg' => '任务ID不能为空'
  40. ];
  41. return json($res);
  42. }
  43. //从Redis中获取任务状态
  44. $redis = getTaskRedis();
  45. $taskData = $redis->get("img_to_img_task:{$taskId}");
  46. if (!$taskData) {
  47. $taskData = $redis->get("text_to_image_task:{$taskId}");
  48. }
  49. if (!$taskData) {
  50. $res = [
  51. 'code' => 1,
  52. 'msg' => '任务不存在或已过期',
  53. ];
  54. return json($res);
  55. }
  56. $taskInfo = json_decode($taskData, true);
  57. if (!empty($taskInfo['image'])) {
  58. $taskInfo['image'] = Common::ossFullUrl((string)$taskInfo['image']);
  59. }
  60. if (!empty($taskInfo['image_url'])) {
  61. $taskInfo['image_url'] = Common::ossFullUrl((string)$taskInfo['image_url']);
  62. }
  63. $res = [
  64. 'code' => 0,
  65. 'msg' => '查询成功',
  66. 'data' => $taskInfo
  67. ];
  68. return json($res);
  69. }
  70. /**
  71. * 支持的AI任务类型枚举(前端传入的status_val需在该列表内)
  72. * 键:前端传入值,值:方法后缀( '前端传入值' => '方法后缀')
  73. */
  74. private static $AI_TASK_TYPES = [
  75. '图生文' => 'ImgToText',
  76. '文生文' => 'TextToText',
  77. '文生图' => 'TextToImg',
  78. '图生图' => 'ImgToImg'
  79. ];
  80. /**
  81. * AI模型接口统一调用入口
  82. * @description 接收前端AI请求,校验任务类型合法性,分发至对应处理方法,统一异常捕获
  83. * @return \think\response\Json 标准化JSON响应
  84. */
  85. public function callAIModelApi()
  86. {
  87. try {
  88. // 1. 获取并校验入参
  89. $params = $this->request->param();
  90. $statusVal = $this->validateAndGetStatusVal($params);
  91. // 2. 映射并校验处理方法
  92. $method = $this->getHandleMethod($statusVal);
  93. // 3. 执行对应处理逻辑并返回响应
  94. return $this->$method($params);
  95. } catch (\InvalidArgumentException $e) {
  96. // 参数/方法异常(用户侧错误)
  97. return $this->jsonResponse(1, $e->getMessage());
  98. } catch (\Throwable $e) {
  99. // 系统异常(服务侧错误)
  100. \think\Log::error('AI接口处理异常:' . $e->getMessage() . ' | 任务类型:' . ($params['status_val'] ?? '未知') . ' | 异常行:' . $e->getLine());
  101. return $this->jsonResponse(1, '服务异常,请稍后重试');
  102. }
  103. }
  104. // -------------------------- 私有核心方法(通用逻辑) --------------------------
  105. /**
  106. * 校验并获取合法的任务类型
  107. * @param array $params 前端入参
  108. * @return string 合法的status_val
  109. * @throws \InvalidArgumentException 任务类型不合法时抛出
  110. */
  111. private function validateAndGetStatusVal(array $params): string
  112. {
  113. $statusVal = trim($params['status_val'] ?? '');
  114. // 空值校验
  115. if (empty($statusVal)) {
  116. throw new \InvalidArgumentException('任务类型不能为空');
  117. }
  118. // 合法性校验
  119. if (!array_key_exists($statusVal, self::$AI_TASK_TYPES)) {
  120. throw new \InvalidArgumentException('不支持的任务类型:' . $statusVal);
  121. }
  122. return $statusVal;
  123. }
  124. /**
  125. * 获取任务对应的处理方法名
  126. * @param string $statusVal 合法的任务类型
  127. * @return string 处理方法名(如handleAiImgToText)
  128. * @throws \InvalidArgumentException 方法未实现时抛出
  129. */
  130. private function getHandleMethod(string $statusVal): string
  131. {
  132. $methodSuffix = self::$AI_TASK_TYPES[$statusVal];
  133. $method = 'handleAi' . $methodSuffix;
  134. if (!method_exists($this, $method)) {
  135. throw new \InvalidArgumentException('任务类型暂未实现:' . $statusVal);
  136. }
  137. return $method;
  138. }
  139. /**
  140. * 通用JSON响应封装
  141. * @param int $code 响应码(0=成功,1=失败)
  142. * @param string $msg 响应信息
  143. * @param array $data 响应数据(可选)
  144. * @return \think\response\Json
  145. */
  146. private function jsonResponse(int $code, string $msg, array $data = []): \think\response\Json
  147. {
  148. $response = [
  149. 'code' => $code,
  150. 'msg' => $msg,
  151. 'time' => date('Y-m-d H:i:s')
  152. ];
  153. if (!empty($data)) {
  154. $response['data'] = $data;
  155. }
  156. return json($response);
  157. }
  158. /**
  159. * 任务类接口统一响应(带task_id的场景)
  160. * @param array $result 业务处理结果(需包含success字段)
  161. * @param string $failMsg 失败提示语
  162. * @return \think\response\Json
  163. */
  164. private function jsonTaskResponse(array $result, string $failMsg = '任务提交失败'): \think\response\Json
  165. {
  166. $isSuccess = isset($result['success']) && $result['success'];
  167. $data = $isSuccess ? ['task_id' => $result['task_id'] ?? ''] : [];
  168. $msg = $isSuccess ? ($result['message'] ?? '提交成功') : ($result['message'] ?? $failMsg);
  169. return $this->jsonResponse($isSuccess ? 0 : 1, $msg, $data);
  170. }
  171. // -------------------------- 业务处理方法(按任务类型拆分) --------------------------
  172. /**
  173. * 图生文任务处理:提交队列并返回提示
  174. * @param array $params 前端入参
  175. * @return \think\response\Json
  176. */
  177. private function handleAiImgToText(array $params): \think\response\Json
  178. {
  179. (new ImageService())->handleImgToText($params);
  180. return $this->jsonResponse(0, '正在优化提示词,请稍等.....');
  181. }
  182. /**
  183. * 文生文任务处理:生成话术并返回内容(支持产品内容更新)
  184. * @param array $params 前端入参
  185. * @return \think\response\Json
  186. */
  187. private function handleAiTextToText(array $params): \think\response\Json
  188. {
  189. //构造生成提示词
  190. $promptTemplate = "\n请根据上述内容生成一段完整的话术,要求:\n"
  191. . "1. 内容必须是连贯的一段话,不要使用列表、分隔线或其他结构化格式\n"
  192. . "2. 不要包含非文本元素的描述\n"
  193. . "3. 不要添加任何额外的引导语、解释或开场白\n"
  194. . "4. 禁忌:不添加无关形容词,不修改产品核心信息,语言流畅自然";
  195. $prompt = ($params['prompt'] ?? '') . $promptTemplate;
  196. // 调用服务层生成内容
  197. $result = (new ImageService())->handleTextToText(
  198. $params['status_val'],
  199. $prompt,
  200. $params['model']
  201. );
  202. if (empty($result['success'])) {
  203. return $this->jsonResponse(1, $result['message'] ?? '生成失败');
  204. }
  205. $content = $result['data'] ?? '';
  206. //区分业务场景处理
  207. $isProductImageGeneration = ($params['status_type'] ?? '') === 'ProductImageGeneration';
  208. $isProductTemplateReplace = ($params['status_type'] ?? '') === 'ProductTemplateReplace';
  209. if (!$isProductImageGeneration && !$isProductTemplateReplace) {
  210. Db::name('product')->where('id', $params['id'])->update(['content' => $content]);
  211. }
  212. return $this->jsonResponse(0, '优化成功', ['content' => $content]);
  213. }
  214. /**
  215. * 文生图任务处理:提交任务并返回task_id
  216. * @param array $params 前端入参
  217. * @return \think\response\Json
  218. */
  219. private function handleAiTextToImg(array $params): \think\response\Json
  220. {
  221. $serviceResult = (new ImageService())->handleTextToImg($params);
  222. return $this->jsonTaskResponse($serviceResult, '文生图任务提交失败');
  223. }
  224. /**
  225. * 图生图任务处理:提交任务并返回task_id
  226. * @param array $params 前端入参
  227. * @return \think\response\Json
  228. */
  229. private function handleAiImgToImg(array $params): \think\response\Json
  230. {
  231. $serviceResult = (new ImageService())->handleImgToImg($params);
  232. return $this->jsonTaskResponse($serviceResult, '图生图任务提交失败');
  233. }
  234. /**
  235. * 即梦AI--创建视频任务接口
  236. * 支持:单张首帧图 / 首尾双帧图
  237. * 图片入参:form-data 文件(first_image/last_image)、base64、或 http(s) URL
  238. */
  239. public function Create_ImgToVideo()
  240. {
  241. $apiUrl = 'https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks';
  242. $apiKey = 'ark-1ca8aa97-3663-4bc7-8c53-d4ab516883f1-d2339';
  243. $params = $this->request->param();
  244. // halt($params);
  245. $prompt = trim((string)($params['prompt'] ?? ''));
  246. if ($prompt === '') {
  247. return json(['code' => 0, 'msg' => 'prompt 不能为空']);
  248. }
  249. $firstError = '';
  250. $firstFrame = $this->resolveFrameImagePayload($params, 'first', $firstError);
  251. if (($firstFrame['api_url'] ?? '') === '') {
  252. $hint = Common::isOssEnabled()
  253. ? '请用 form-data 上传 first_image(类型选文件),并查看 runtime/log'
  254. : '请在 application/config.php 配置 oss(accessKeyId、endpoint、bucket、host)';
  255. $detail = $firstError !== '' ? '(' . $firstError . ')' : '';
  256. return json(['code' => 0, 'msg' => '首帧图片无效或上传 OSS 失败。' . $hint . $detail]);
  257. }
  258. $lastFrame = $this->resolveFrameImagePayload($params, 'last');
  259. $firstImageUrl = $firstFrame['api_url'];
  260. $lastImageUrl = $lastFrame['api_url'];
  261. $content = $this->buildImgToVideoContent($prompt, $firstImageUrl, $lastImageUrl);
  262. $data = [
  263. 'model' => 'doubao-seedance-1-5-pro-251215',
  264. 'content' => $content,
  265. 'generate_audio' => filter_var($params['generate_audio'] ?? true, FILTER_VALIDATE_BOOLEAN),
  266. 'ratio' => $params['ratio'] ?? $params['aspect_ratio'] ?? 'adaptive',
  267. 'duration' => (int)($params['duration'] ?? 5),
  268. 'watermark' => filter_var($params['watermark'] ?? false, FILTER_VALIDATE_BOOLEAN),
  269. ];
  270. $ch = curl_init();
  271. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  272. curl_setopt($ch, CURLOPT_POST, true);
  273. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
  274. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  275. 'Content-Type: application/json',
  276. 'Authorization: Bearer ' . $apiKey
  277. ]);
  278. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  279. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  280. curl_setopt($ch, CURLOPT_TIMEOUT, 60);
  281. $response = curl_exec($ch);
  282. if (curl_errno($ch)) {
  283. $error = curl_error($ch);
  284. curl_close($ch);
  285. return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
  286. }
  287. curl_close($ch);
  288. $responseData = json_decode($response, true);
  289. if (isset($responseData['error'])) {
  290. $msg = $responseData['error']['message'] ?? 'API 请求失败';
  291. return json(['code' => 0, 'msg' => 'API 错误: ' . $msg]);
  292. }
  293. $taskId = $responseData['id'] ?? '';
  294. if ($taskId === '') {
  295. return json(['code' => 0, 'msg' => '获取任务 ID 失败']);
  296. }
  297. $firstImageUrl = $this->finalizeFrameImageToOss($firstFrame, $taskId);
  298. $lastImageUrl = $this->finalizeFrameImageToOss($lastFrame, $taskId);
  299. $videoData = [
  300. 'video_id' => $taskId,
  301. 'prompt' => $prompt,
  302. 'first_image_url' => $firstImageUrl,
  303. 'last_image_url' => $lastImageUrl,
  304. 'model' => $data['model'],
  305. 'seconds' => (string)$data['duration'],
  306. 'size' => (string)$data['ratio'],
  307. 'sys_rq' => date('Y-m-d H:i:s'),
  308. ];
  309. try {
  310. Db::name('video')->insert($videoData);
  311. } catch (Exception $e) {
  312. return json([
  313. 'code' => 0,
  314. 'msg' => '任务已创建,但数据库保存失败',
  315. 'data' => [
  316. 'task_id' => $taskId,
  317. 'error_message' => $e->getMessage(),
  318. ],
  319. ]);
  320. }
  321. return json([
  322. 'code' => 1,
  323. 'msg' => '任务创建成功',
  324. 'data' => [
  325. 'task_id' => $taskId,
  326. 'video_id' => $taskId,
  327. 'status' => $responseData['status'] ?? '',
  328. 'created_at' => $responseData['created_at'] ?? '',
  329. 'mode' => $lastImageUrl !== '' ? 'first_last_frame' : 'single_frame',
  330. 'first_image_url' => $firstImageUrl,
  331. 'last_image_url' => $lastImageUrl,
  332. ]
  333. ]);
  334. }
  335. /**
  336. * 即梦AI--获取视频接口
  337. * 首帧图 + 尾帧图 = 新效果视频
  338. */
  339. public function Get_ImgToVideo()
  340. {
  341. $apiUrl = 'https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks';
  342. $apiKey = 'ark-1ca8aa97-3663-4bc7-8c53-d4ab516883f1-d2339';
  343. $params = $this->request->param();
  344. $taskId = $params['task_id'] ?? $params['video_id'] ?? '';
  345. if ($taskId === '') {
  346. return json(['code' => 0, 'msg' => '任务 ID 不能为空']);
  347. }
  348. // 查询任务状态
  349. $queryUrl = $apiUrl . '/' . $taskId;
  350. $ch2 = curl_init();
  351. curl_setopt($ch2, CURLOPT_URL, $queryUrl);
  352. curl_setopt($ch2, CURLOPT_HTTPHEADER, [
  353. 'Content-Type: application/json',
  354. 'Authorization: Bearer ' . $apiKey
  355. ]);
  356. curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
  357. curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false); // 开发环境临时关闭SSL验证
  358. curl_setopt($ch2, CURLOPT_TIMEOUT, 60); // 超时时间
  359. $queryResponse = curl_exec($ch2);
  360. // 检查 cURL 错误
  361. if (curl_errno($ch2)) {
  362. $error = curl_error($ch2);
  363. curl_close($ch2);
  364. return json(['code' => 0, 'msg' => 'Curl 错误: ' . $error]);
  365. }
  366. curl_close($ch2);
  367. // 解析查询响应
  368. $queryData = json_decode($queryResponse, true);
  369. // print_r($queryData);die;
  370. // 轮询任务状态,直到完成
  371. $maxPolls = 30;
  372. $pollCount = 0;
  373. $pollData = is_array($queryData) ? $queryData : [];
  374. $taskStatus = $pollData['status'] ?? '';
  375. while (!in_array($taskStatus, ['completed', 'succeeded']) && $pollCount < $maxPolls) {
  376. sleep(5); // 每5秒轮询一次
  377. $pollCount++;
  378. // 再次查询任务状态
  379. $ch3 = curl_init();
  380. curl_setopt($ch3, CURLOPT_URL, $queryUrl);
  381. curl_setopt($ch3, CURLOPT_HTTPHEADER, [
  382. 'Content-Type: application/json',
  383. 'Authorization: Bearer ' . $apiKey
  384. ]);
  385. curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
  386. curl_setopt($ch3, CURLOPT_SSL_VERIFYPEER, false);
  387. curl_setopt($ch3, CURLOPT_TIMEOUT, 60);
  388. $pollResponse = curl_exec($ch3);
  389. curl_close($ch3);
  390. $pollData = json_decode($pollResponse, true);
  391. $taskStatus = $pollData['status'] ?? '';
  392. // 检查任务是否失败
  393. if ($taskStatus === 'failed') {
  394. return json(['code' => 0, 'msg' => '任务执行失败']);
  395. }
  396. }
  397. // 如果任务已经成功,直接使用 $queryData
  398. if (empty($pollData) && isset($queryData['status']) && $queryData['status'] === 'succeeded') {
  399. $pollData = $queryData;
  400. }
  401. // 检查轮询是否超时
  402. if (!in_array($taskStatus, ['completed', 'succeeded'])) {
  403. return json(['code' => 0, 'msg' => '任务执行超时']);
  404. }
  405. // 获取视频 URL(兼容不同响应结构)
  406. $videoUrl = $pollData['content']['video_url']
  407. ?? $pollData['output']['video_url']
  408. ?? $pollData['video_url']
  409. ?? '';
  410. if ($videoUrl === '') {
  411. return json(['code' => 0, 'msg' => '获取视频 URL 失败', 'data' => ['pollData' => $pollData]]);
  412. }
  413. $fileName = $this->sanitizeTaskIdSegment($taskId) . '.mp4';
  414. $saveDir = $this->buildTaskMediaLocalDir($taskId);
  415. if (!is_dir($saveDir)) {
  416. mkdir($saveDir, 0755, true);
  417. }
  418. $savePath = $saveDir . $fileName;
  419. $videoContent = $this->downloadRemoteFile($videoUrl);
  420. if ($videoContent === false) {
  421. return json(['code' => 0, 'msg' => '下载视频失败', 'data' => ['videoUrl' => $videoUrl]]);
  422. }
  423. if (file_put_contents($savePath, $videoContent) === false) {
  424. return json(['code' => 0, 'msg' => '保存视频失败', 'data' => ['savePath' => $savePath]]);
  425. }
  426. $objectKey = $this->buildTaskMediaObjectKey($taskId, $fileName);
  427. $upload = $this->uploadToOSS($savePath, $objectKey);
  428. if ($upload['success']) {
  429. $webUrl = $upload['url'] !== '' ? $upload['url'] : Common::ossFullUrl($objectKey);
  430. } else {
  431. $webUrl = $objectKey;
  432. Log::write('[Get_ImgToVideo] OSS上传失败,使用本地相对路径: ' . $objectKey, 'error');
  433. }
  434. try {
  435. Db::name('video')->where('video_id', $taskId)->update(['web_url' => $webUrl]);
  436. } catch (Exception $e) {
  437. return json([
  438. 'code' => 0,
  439. 'msg' => '视频已生成,但数据库更新失败',
  440. 'data' => [
  441. 'task_id' => $taskId,
  442. 'web_url' => $webUrl,
  443. 'error_message' => $e->getMessage(),
  444. ],
  445. ]);
  446. }
  447. return json([
  448. 'code' => 1,
  449. 'msg' => '视频获取成功',
  450. 'data' => [
  451. 'task_id' => $taskId,
  452. 'video_id' => $taskId,
  453. 'status' => $taskStatus,
  454. 'web_url' => $webUrl,
  455. 'oss_object_key' => $upload['object_key'] ?? $objectKey,
  456. 'oss_uploaded' => $upload['success'] ?? false,
  457. 'local_path' => $objectKey,
  458. ],
  459. ]);
  460. }
  461. /**
  462. * 下载远程文件(视频等)
  463. * @return string|false
  464. */
  465. private function downloadRemoteFile(string $url)
  466. {
  467. $ch = curl_init();
  468. curl_setopt($ch, CURLOPT_URL, $url);
  469. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  470. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  471. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  472. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  473. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  474. $body = curl_exec($ch);
  475. if (curl_errno($ch)) {
  476. Log::write('[downloadRemoteFile] ' . curl_error($ch) . ' | url=' . $url, 'error');
  477. curl_close($ch);
  478. return false;
  479. }
  480. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  481. curl_close($ch);
  482. if ($httpCode < 200 || $httpCode >= 300 || $body === false) {
  483. return false;
  484. }
  485. return $body;
  486. }
  487. //获取视频列表
  488. public function Getvideolist(){
  489. if (!$this->request->isGet()) {
  490. $this->error('请求方式错误');
  491. }
  492. $params = $this->request->param();
  493. $search = input('search', '');
  494. $page = isset($params['page']) ? (int)$params['page'] : 1;
  495. $limit = isset($params['limit']) ? (int)$params['limit'] : 50;
  496. $where = [];
  497. if (!empty($search)) {
  498. $where['prompt'] = ['like', '%' . $search . '%'];
  499. }
  500. $list = Db::name('video')->where('mod_rq', null)
  501. ->where($where)
  502. ->order('id desc')
  503. ->limit(($page - 1) * $limit, $limit)
  504. ->select();
  505. $total = Db::name('video')->where('mod_rq', null)
  506. ->where($where)
  507. ->count();
  508. $res['code'] = 0;
  509. $res['msg'] = '成功';
  510. $res['count'] = $total;
  511. $res['data'] = $list;
  512. return json($res);
  513. }
  514. /**
  515. * 文生视频/图生视频接口
  516. */
  517. //文生视频
  518. public function video(){
  519. $apiUrl = 'https://ark.cn-beijing.volces.com/api/v3/contents/generations/tasks';
  520. $apiKey = 'ark-1ca8aa97-3663-4bc7-8c53-d4ab516883f1-d2339';
  521. $params = $this->request->param();
  522. $postData = [
  523. 'prompt' => $params['prompt'],
  524. 'model' => 'doubao-seedance-1-5-pro-251215',
  525. 'seconds' => $params['seconds'],
  526. 'size' => $params['size'],
  527. ];
  528. // 初始化CURL
  529. $ch = curl_init();
  530. curl_setopt($ch, CURLOPT_URL, $apiUrl);
  531. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  532. curl_setopt($ch, CURLOPT_POST, true);
  533. curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
  534. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  535. 'Authorization: Bearer ' . $apiKey
  536. ]);
  537. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  538. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  539. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  540. curl_setopt($ch, CURLOPT_HEADER, true); // 获取响应头
  541. curl_setopt($ch, CURLOPT_VERBOSE, true); // 启用详细输出以进行调试
  542. // 创建临时文件来捕获详细的cURL输出
  543. $verbose = fopen('php://temp', 'w+');
  544. curl_setopt($ch, CURLOPT_STDERR, $verbose);
  545. // 执行请求
  546. $response = curl_exec($ch);
  547. //HTTP状态码
  548. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  549. // 获取详细的cURL调试信息
  550. rewind($verbose);
  551. //CURL调试信息
  552. $verboseLog = stream_get_contents($verbose);
  553. fclose($verbose);
  554. // 分离头部和主体
  555. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  556. //响应头部
  557. $header = substr($response, 0, $header_size);
  558. //响应主体
  559. $body = substr($response, $header_size);
  560. // 检查CURL错误
  561. $curlError = curl_error($ch);
  562. curl_close($ch);
  563. $responseData = json_decode($body, true);
  564. echo "<pre>";
  565. print_r($responseData);
  566. echo "<pre>";die;
  567. // 检查API是否返回了错误信息
  568. if (isset($responseData['error'])) {
  569. $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : 'API请求失败';
  570. return json([
  571. 'code' => 1,
  572. 'msg' => '视频生成请求失败',
  573. 'data' => [
  574. 'error_type' => isset($responseData['error']['type']) ? $responseData['error']['type'] : 'unknown',
  575. 'error_code' => isset($responseData['error']['code']) ? $responseData['error']['code'] : 'unknown',
  576. 'error_message' => $errorMessage
  577. ]
  578. ]);
  579. }
  580. // 检查是否有自定义错误格式
  581. if (isset($responseData['code']) && $responseData['code'] === 'fail_to_fetch_task' && isset($responseData['message'])) {
  582. return json([
  583. 'code' => 1,
  584. 'msg' => '视频生成请求失败',
  585. 'data' => [
  586. 'error_code' => $responseData['code'],
  587. 'error_message' => $responseData['message']
  588. ]
  589. ]);
  590. }
  591. // 检查是否存在id字段
  592. if (!isset($responseData['id'])) {
  593. return json([
  594. 'code' => 1,
  595. 'msg' => '无法获取视频ID',
  596. 'data' => [
  597. 'response_data' => $responseData,
  598. 'http_code' => $httpCode
  599. ]
  600. ]);
  601. }
  602. $videoData = [
  603. 'video_id' => $responseData['id'],
  604. 'prompt' => $postData['prompt'],
  605. 'model' => $postData['model'],
  606. 'seconds' => $postData['seconds'],
  607. 'size' => $postData['size'],
  608. 'sys_rq' => date("Y-m-d H:i:s")
  609. ];
  610. // 尝试插入数据
  611. try {
  612. $res = Db::name('video')->insert($videoData);
  613. return json([
  614. 'code' => 0,
  615. 'msg' => '视频正在生成中',
  616. 'data ' => [
  617. 'video_id' => $responseData['id'],
  618. 'insert_result' => $res
  619. ]
  620. ]);
  621. } catch (Exception $e) {
  622. return json([
  623. 'code' => 1,
  624. 'msg' => '数据库操作失败',
  625. 'data' => [
  626. 'error_message' => $e->getMessage()
  627. ]
  628. ]);
  629. }
  630. }
  631. /**
  632. * 获取视频内容
  633. * 下载已完成的视频内容
  634. */
  635. public function videoContent(){
  636. // 从请求参数获取video_id,如果没有则使用默认值
  637. $video_id = input('get.video_id');
  638. $apiKey = '';
  639. // 1. 先检查视频状态
  640. $statusUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id;
  641. $statusData = $this->fetchVideoStatus($statusUrl, $apiKey);
  642. // 检查视频状态
  643. if ($statusData['status'] !== 'completed') {
  644. return json([
  645. 'code' => 202,
  646. 'msg' => '视频尚未生成完成',
  647. 'data' => [
  648. 'video_id' => $video_id,
  649. 'status' => $statusData['status'],
  650. 'progress' => $statusData['progress'],
  651. 'created_at' => $statusData['created_at'],
  652. 'message' => '请稍后再试,视频仍在' . ($statusData['status'] === 'queued' ? '排队中' : '处理中')
  653. ]
  654. ]);
  655. }
  656. // 2. 视频生成完成,准备下载
  657. $apiUrl = 'https://chatapi.onechats.ai/v1/videos/' . $video_id . '/content';
  658. // 获取可选的variant参数
  659. $variant = $this->request->get('variant', '');
  660. if (!empty($variant)) {
  661. $apiUrl .= '?variant=' . urlencode($variant);
  662. }
  663. // 创建保存目录
  664. $saveDir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'videos' . DS . date('Ymd');
  665. if (!is_dir($saveDir)) {
  666. mkdir($saveDir, 0755, true);
  667. }
  668. // 生成唯一文件名
  669. $filename = $video_id . '.mp4';
  670. $localPath = DS . 'uploads' . DS . 'videos' . DS . date('Ymd') . DS . $filename;
  671. $fullPath = $saveDir . DS . $filename;
  672. // 3. 下载视频
  673. $videoData = $this->downloadVideo($apiUrl, $apiKey);
  674. // 4. 保存视频文件
  675. if (file_put_contents($fullPath, $videoData) === false) {
  676. throw new Exception('视频保存失败');
  677. }
  678. // 确保路径使用正斜杠,并只保存相对路径部分
  679. $localPath = str_replace('\\', '/', $localPath);
  680. // 移除开头的斜杠,确保路径格式为uploads/videos/...
  681. $savePath = ltrim($localPath, '/');
  682. // 将正确格式的文件路径存入数据库
  683. Db::name('video')->where('video_id', $video_id)->update([
  684. 'web_url' => $savePath
  685. ]);
  686. // 返回成功响应
  687. return json([
  688. 'code' => 0,
  689. 'msg' => '视频下载成功',
  690. 'data' => [
  691. 'video_id' => $video_id,
  692. 'local_path' => $localPath,
  693. 'web_url' => $savePath,
  694. 'file_size' => filesize($fullPath)
  695. ]
  696. ]);
  697. }
  698. /**
  699. * 获取视频状态
  700. */
  701. private function fetchVideoStatus($url, $apiKey) {
  702. $ch = curl_init();
  703. curl_setopt($ch, CURLOPT_URL, $url);
  704. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  705. curl_setopt($ch, CURLOPT_HTTPGET, true);
  706. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  707. 'Authorization: Bearer ' . $apiKey,
  708. 'Accept: application/json'
  709. ]);
  710. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  711. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  712. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  713. $response = curl_exec($ch);
  714. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  715. $error = curl_error($ch);
  716. curl_close($ch);
  717. if ($error) {
  718. throw new Exception('获取视频状态失败: ' . $error);
  719. }
  720. if ($httpCode < 200 || $httpCode >= 300) {
  721. throw new Exception('获取视频状态失败,HTTP状态码: ' . $httpCode);
  722. }
  723. $data = json_decode($response, true);
  724. if (!is_array($data)) {
  725. throw new Exception('视频状态数据格式错误');
  726. }
  727. return $data;
  728. }
  729. /**
  730. * 下载视频文件
  731. */
  732. private function downloadVideo($url, $apiKey) {
  733. $ch = curl_init();
  734. curl_setopt($ch, CURLOPT_URL, $url);
  735. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  736. curl_setopt($ch, CURLOPT_HTTPGET, true);
  737. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  738. 'Authorization: Bearer ' . $apiKey
  739. ]);
  740. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  741. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  742. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  743. $response = curl_exec($ch);
  744. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  745. $error = curl_error($ch);
  746. curl_close($ch);
  747. if ($error) {
  748. throw new Exception('视频下载失败: ' . $error);
  749. }
  750. if ($httpCode < 200 || $httpCode >= 300) {
  751. throw new Exception('视频下载失败,HTTP状态码: ' . $httpCode);
  752. }
  753. return $response;
  754. }
  755. private function sendPostRequest($url, $data, $apiKey)
  756. {
  757. $ch = curl_init();
  758. curl_setopt($ch, CURLOPT_URL, $url);
  759. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  760. curl_setopt($ch, CURLOPT_POST, true);
  761. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  762. 'Authorization: Bearer ' . $apiKey,
  763. 'Accept: application/json',
  764. 'Content-Type: application/json'
  765. ]);
  766. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
  767. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  768. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  769. curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 延长超时时间
  770. $response = curl_exec($ch);
  771. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  772. $error = curl_error($ch);
  773. curl_close($ch);
  774. return [
  775. 'response' => $response,
  776. 'http_code' => $httpCode,
  777. 'error' => $error
  778. ];
  779. }
  780. /**
  781. * 查询模版
  782. */
  783. public function product_template()
  784. {
  785. $params = $this->request->param();
  786. if (!$this->request->isGet()) {
  787. $this->error('请求方法错误');
  788. }
  789. $page = isset($params['page']) ? (int)$params['page'] : 1;
  790. $limit = isset($params['limit']) ? (int)$params['limit'] : 30;
  791. $where = [];
  792. if (!empty($params['search'])) {
  793. $where['id|chinese_description|template_name|style'] = ['like', '%' . $params['search'] . '%'];
  794. }
  795. // toexamine / release:用 isset + 非空串,避免 empty(0) 导致「未发布」无法筛选;release 建议库中为 0/1
  796. if (isset($params['toexamine']) && $params['toexamine'] !== '') {
  797. $where['toexamine'] = $params['toexamine'];
  798. }
  799. if (isset($params['release']) && $params['release'] !== '') {
  800. $where['release'] = is_numeric($params['release']) ? (int) $params['release'] : $params['release'];
  801. }
  802. $isSuperAdmin = false;
  803. if (!empty($params['sys_id']) && $params['sys_id'] == '超级管理员') {
  804. $isSuperAdmin = true;
  805. }
  806. if (!$isSuperAdmin && !empty($params['sys_id'])) {
  807. $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
  808. $products = Db::name('product_template')->order('id desc')->where($where)
  809. ->whereNull('mod_rq')
  810. ->limit(($page - 1) * $limit, $limit)
  811. ->select();
  812. }else{
  813. $products = Db::name('product_template')->order('id desc')->where($where)
  814. ->whereNull('mod_rq')
  815. ->limit(($page - 1) * $limit, $limit)
  816. ->select();
  817. }
  818. $total = Db::name('product_template')->where($where)
  819. ->whereNull('mod_rq')
  820. ->count();
  821. foreach ($products as &$item) {
  822. if (!empty($item['template_image_url'])) {
  823. $item['template_image_url'] = Common::ossFullUrl((string)$item['template_image_url']);
  824. }
  825. if (!empty($item['thumbnail_image'])) {
  826. $item['thumbnail_image'] = Common::ossFullUrl((string)$item['thumbnail_image']);
  827. }
  828. }
  829. unset($item);
  830. return json([
  831. 'code' => 0,
  832. 'msg' => '请求成功',
  833. 'count' => $total,
  834. 'data' => $products
  835. ]);
  836. }
  837. /**
  838. * 获取 AI 模型配置
  839. * status 1 = 启用 0 = 禁用(同一模型内的优先级,数值越小越优先)
  840. * model_type 支持多能力逗号间隔(如 文生图,图生图),传参精确匹配某一能力
  841. * 可选参数:manage=1 时返回全部(含禁用),用于管理端
  842. */
  843. public function GetAIModel(){
  844. $params = $this->request->param();
  845. $query = Db::name('ai_model');
  846. if (empty($params['manage'])) {
  847. $query->where('status', '1');
  848. }
  849. if (!empty($params['model_type'])) {
  850. $query->whereRaw('FIND_IN_SET(:mt, model_type) > 0', ['mt' => trim($params['model_type'])]);
  851. }
  852. if (!empty($params['supplier'])) {
  853. $query->where('supplier', 'like', '%' . $params['supplier'] . '%');
  854. }
  855. if (!empty($params['model_name'])) {
  856. $query->where('model_name|model_alias', 'like', '%' . $params['model_name'] . '%');
  857. }
  858. $list = $query
  859. ->field('id,model_alias,model_group,model_name,model_type,sort,status,supplier')
  860. ->order('sort ASC, id ASC')->select();
  861. return json([
  862. 'code' => 0,
  863. 'msg' => '成功',
  864. 'data' => $list
  865. ]);
  866. }
  867. /**
  868. * 新增 AI 模型配置
  869. * POST: status, supplier, api_key, api_url, model_group, model_name, model_alias, model_type, sort
  870. * model_type 多能力用逗号间隔,如:文生图,图生图
  871. */
  872. public function AddAIModel(){
  873. $params = $this->request->param();
  874. $required = ['api_url', 'api_key', 'model_name', 'model_type'];
  875. foreach ($required as $k) {
  876. if (empty(trim($params[$k] ?? ''))) {
  877. return json(['code' => 1, 'msg' => $k . ' 不能为空']);
  878. }
  879. }
  880. $insert = [
  881. 'status' => $params['status'],
  882. 'supplier' => trim($params['supplier']),
  883. 'api_key' => trim($params['api_key']),
  884. 'api_url' => trim($params['api_url']),
  885. 'model_group' => trim($params['model_group']),
  886. 'model_name' => trim($params['model_name']),
  887. 'model_alias' => trim($params['model_alias']),
  888. 'model_type' => trim($params['model_type']),
  889. 'sort' => isset($params['sort']) ? intval($params['sort']) : 0,
  890. ];
  891. try {
  892. Db::name('ai_model')->insert($insert);
  893. return json(['code' => 0, 'msg' => '新增成功']);
  894. } catch (\Exception $e) {
  895. return json(['code' => 1, 'msg' => '新增失败: ' . $e->getMessage()]);
  896. }
  897. }
  898. /**
  899. * 修改 AI 模型配置
  900. * POST: id(必填), 其余字段同新增
  901. */
  902. public function UpdateAIModel(){
  903. $params = $this->request->param();
  904. if (empty($params['id'])) {
  905. return json(['code' => 1, 'msg' => 'id 不能为空']);
  906. }
  907. $id = intval($params['id']);
  908. $exists = Db::name('ai_model')->where('id', $id)->find();
  909. if (!$exists) {
  910. return json(['code' => 1, 'msg' => '记录不存在']);
  911. }
  912. $update = [];
  913. $fields = ['status', 'supplier', 'api_key', 'api_url', 'model_group', 'model_name', 'model_alias', 'model_type', 'sort'];
  914. foreach ($fields as $f) {
  915. if (array_key_exists($f, $params)) {
  916. $update[$f] = $f === 'sort' ? intval($params[$f]) : trim($params[$f] ?? '');
  917. }
  918. }
  919. if (empty($update)) {
  920. return json(['code' => 1, 'msg' => '无有效修改字段']);
  921. }
  922. try {
  923. Db::name('ai_model')->where('id', $id)->update($update);
  924. return json(['code' => 0, 'msg' => '修改成功']);
  925. } catch (\Exception $e) {
  926. return json(['code' => 1, 'msg' => '修改失败: ' . $e->getMessage()]);
  927. }
  928. }
  929. /**
  930. * 用于获取所有产品记录
  931. **/
  932. public function GetProductList(){
  933. $params = $this->request->param();
  934. $page = max(1, intval($params['page'] ?? 1));
  935. $pageSize = min(100, max(1, intval($params['limit'] ?? 30)));
  936. // 构建查询条件
  937. $where = [];
  938. if (!empty($params['search'])) {
  939. $where['prompt|model'] = ['like', '%' . $params['search'] . '%'];
  940. }
  941. if (!empty($params['sys_id'])) {
  942. $where['sys_id'] = ['like', '%' . $params['sys_id'] . '%'];
  943. }
  944. $prompt = Db::name('product_image_generate')->field('prompt')->where($where)->group('prompt')->order('id desc')->select();
  945. $data = Db::name('product_image_generate')->where($where)->order('id desc')->page($page, $pageSize)->select();
  946. $count = Db::name('product_image_generate')->field('prompt')->where($where)->order('id desc')->count();
  947. foreach ($data as &$item) {
  948. if (!empty($item['generated_image']) || !empty($item['product_img']) || !empty($item['reference_image'])) {
  949. $item['generated_image'] = Common::ossFullUrl((string)$item['generated_image']);
  950. $item['product_img'] = Common::ossFullUrl((string)$item['product_img']);
  951. $item['reference_image'] = Common::ossFullUrl((string)$item['reference_image']);
  952. }
  953. }
  954. unset($item);
  955. return json([
  956. 'code' => 0,
  957. 'msg' => '成功',
  958. 'count' => $count,
  959. 'prompt' => $prompt,
  960. 'data' => $data
  961. ]);
  962. }
  963. /**
  964. * 查询队列列表
  965. * 统计文件对应的队列情况
  966. */
  967. public function get_queue_logs()
  968. {
  969. $params = $this->request->param('old_image_file', '');
  970. $queue_logs = Db::name('queue_logs')
  971. ->where('old_image_file', $params)
  972. ->order('id desc')
  973. ->select();
  974. $result = []; //初始化变量,避免未定义错误
  975. foreach ($queue_logs as &$log) {
  976. $taskId = $log['id'];
  977. $statusCount = Db::name('image_task_log')
  978. ->field('status, COUNT(*) as count')
  979. ->where('task_id', $taskId)
  980. ->where('mod_rq', null)
  981. ->group('status')
  982. ->select();
  983. $log['已完成数量'] = 0;
  984. $log['处理中数量'] = 0;
  985. $log['排队中的数量'] = 0;
  986. $log['失败数量'] = 0;
  987. foreach ($statusCount as $item) {
  988. switch ($item['status']) {
  989. case 0:
  990. $log['排队中的数量'] = $item['count'];
  991. break;
  992. case 1:
  993. $log['处理中数量'] = $item['count'];
  994. break;
  995. case 2:
  996. $log['已完成数量'] = $item['count'];
  997. break;
  998. case -1:
  999. $log['失败数量'] = $item['count'];
  1000. break;
  1001. }
  1002. }
  1003. // if ($log['排队中的数量'] >$log['已完成数量']) {
  1004. // $result[] = $log;
  1005. // }
  1006. if ($log['排队中的数量']) {
  1007. $result[] = $log;
  1008. }
  1009. // if ($log['处理中数量'] >= 0) {
  1010. // $result[] = $log;
  1011. // }
  1012. }
  1013. return json([
  1014. 'code' => 0,
  1015. 'msg' => '查询成功',
  1016. 'data' => $result,
  1017. 'count' => count($result)
  1018. ]);
  1019. }
  1020. /**
  1021. * 查询总队列状态(统计当前处理的数据量)
  1022. */
  1023. public function queueStats()
  1024. {
  1025. $statusList = Db::name('image_task_log')
  1026. ->field('status, COUNT(*) as total')
  1027. ->where('mod_rq', null)
  1028. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1029. ->group('status')
  1030. ->select();
  1031. $statusCount = [];
  1032. foreach ($statusList as $item) {
  1033. $statusCount[$item['status']] = $item['total'];
  1034. }
  1035. // 总数为所有状态和
  1036. $total = array_sum($statusCount);
  1037. //获取队列当前状态
  1038. $statusText = Db::name('queue_logs')->order('id desc')->value('status');
  1039. return json([
  1040. 'code' => 0,
  1041. 'msg' => '获取成功',
  1042. 'data' => [
  1043. '总任务数' => $total,
  1044. '待处理' => $statusCount[0] ?? 0,
  1045. '处理中' => $statusCount[1] ?? 0,
  1046. '成功' => $statusCount[2] ?? 0,
  1047. '失败' => $statusCount[-1] ?? 0,
  1048. '当前状态' => $statusText
  1049. ]
  1050. ]);
  1051. }
  1052. /**
  1053. * 获取 Redis 连接实例
  1054. * @return \Redis|null Redis 实例或 null(如果连接失败)
  1055. */
  1056. private function getRedisConnection()
  1057. {
  1058. if (!class_exists('\Redis')) {
  1059. return null;
  1060. }
  1061. return getTaskRedis();
  1062. }
  1063. /**
  1064. * 显示当前运行中的队列监听进程
  1065. */
  1066. public function viewQueueStatus()
  1067. {
  1068. $redis = $this->getRedisConnection();
  1069. if (!$redis) {
  1070. return json([
  1071. 'code' => 1,
  1072. 'msg' => 'Redis扩展未安装或未启用',
  1073. 'data' => null
  1074. ]);
  1075. }
  1076. $key = 'queues:imgtotxt';
  1077. // 判断 key 是否存在,避免报错
  1078. if (!$redis->exists($key)) {
  1079. return json([
  1080. 'code' => 0,
  1081. 'msg' => '查询成功,队列为空',
  1082. 'count' => 0,
  1083. 'tasks_preview' => []
  1084. ]);
  1085. }
  1086. $count = $redis->lLen($key);
  1087. $list = $redis->lRange($key, 0, 9);
  1088. // 解码 JSON 内容,确保每一项都有效
  1089. $parsed = array_filter(array_map(function ($item) {
  1090. return json_decode($item, true);
  1091. }, $list), function ($item) {
  1092. return !is_null($item);
  1093. });
  1094. return json([
  1095. 'code' => 0,
  1096. 'msg' => '查询成功',
  1097. 'count' => $count,
  1098. 'tasks_preview' => $parsed
  1099. ]);
  1100. }
  1101. /**
  1102. * 清空队列并删除队列日志记录
  1103. */
  1104. public function stopQueueProcesses()
  1105. {
  1106. Db::name('image_task_log')
  1107. ->where('log', '队列中')
  1108. ->whereOr('status', 1)
  1109. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1110. ->update([
  1111. 'status' => "-1",
  1112. 'log' => '清空取消队列',
  1113. 'mod_rq' => date('Y-m-d H:i:s')
  1114. ]);
  1115. Db::name('image_task_log')
  1116. ->whereLike('log', '%处理中%')
  1117. ->where('create_time', '>=', date('Y-m-d 00:00:00'))
  1118. ->update([
  1119. 'status' => "-1",
  1120. 'log' => '清空取消队列',
  1121. 'mod_rq' => date('Y-m-d H:i:s')
  1122. ]);
  1123. $redis = $this->getRedisConnection();
  1124. if (!$redis) {
  1125. return json([
  1126. 'code' => 1,
  1127. 'msg' => 'Redis扩展未安装或未启用',
  1128. 'data' => null
  1129. ]);
  1130. }
  1131. $key_txttoimg = 'queues:txttoimg:reserved';
  1132. $key_txttotxt = 'queues:txttotxt:reserved';
  1133. $key_imgtotxt = 'queues:imgtotxt:reserved';
  1134. $key_imgtoimg = 'queues:imgtoimg:reserved';
  1135. // 清空 Redis 队列
  1136. $redis->del($key_txttoimg);
  1137. $redis->del($key_txttotxt);
  1138. $redis->del($key_imgtotxt);
  1139. $redis->del($key_imgtoimg);
  1140. $count = $redis->lLen($key_txttoimg) + $redis->lLen($key_txttotxt) + $redis->lLen($key_imgtotxt) + $redis->lLen($key_imgtoimg);
  1141. return json([
  1142. 'code' => 0,
  1143. 'msg' => '成功停止队列任务'
  1144. ]);
  1145. }
  1146. /**
  1147. *获取服务器URL地址和端口 IP地址:端口
  1148. * 用于获取图片路径拼接时
  1149. **/
  1150. public function GetHttpUrl(){
  1151. $data = Db::name('http_url')->find();
  1152. $fullUrl = "http://" . $data['baseUrl'] . ":" . $data['port'];
  1153. $res = [
  1154. 'code' => 0,
  1155. 'msg' => '成功',
  1156. 'data' => [
  1157. 'id' => $data['id'],
  1158. 'full_url' => $fullUrl,
  1159. 'baseUrl' => $data['baseUrl'],
  1160. 'port' => $data['port']
  1161. ]
  1162. ];
  1163. return json($res);
  1164. }
  1165. /**
  1166. * 构建图生视频 content:单帧无 role,双帧带 first_frame / last_frame
  1167. */
  1168. private function buildImgToVideoContent(string $prompt, string $firstImageUrl, string $lastImageUrl): array
  1169. {
  1170. $content = [
  1171. ['type' => 'text', 'text' => $prompt],
  1172. ];
  1173. if ($lastImageUrl !== '') {
  1174. $content[] = [
  1175. 'type' => 'image_url',
  1176. 'image_url' => ['url' => $firstImageUrl],
  1177. 'role' => 'first_frame',
  1178. ];
  1179. $content[] = [
  1180. 'type' => 'image_url',
  1181. 'image_url' => ['url' => $lastImageUrl],
  1182. 'role' => 'last_frame',
  1183. ];
  1184. return $content;
  1185. }
  1186. $content[] = [
  1187. 'type' => 'image_url',
  1188. 'image_url' => ['url' => $firstImageUrl],
  1189. ];
  1190. return $content;
  1191. }
  1192. /** 图生视频创建前,帧图暂存 OSS 子目录(AI 返回 id 后会迁移到正式目录) */
  1193. private const FRAME_OSS_STAGING_ID = '_staging';
  1194. /**
  1195. * 任务 id 用于路径的安全片段
  1196. */
  1197. private function sanitizeTaskIdSegment(string $taskId): string
  1198. {
  1199. $segment = preg_replace('/[\\\\\/:*?"<>|]/u', '_', trim($taskId));
  1200. return $segment !== '' ? $segment : '_unknown';
  1201. }
  1202. /**
  1203. * 图生视频任务媒体本地目录:public/uploads/videos/{日期}/{taskId}/
  1204. */
  1205. private function buildTaskMediaLocalDir(string $taskId): string
  1206. {
  1207. return str_replace('\\', '/', ROOT_PATH . 'public/uploads/videos/' . date('Ymd') . '/' . $this->sanitizeTaskIdSegment($taskId) . '/');
  1208. }
  1209. /**
  1210. * 图生视频任务媒体 OSS 对象键:uploads/videos/{日期}/{taskId}/{文件名}(帧图与生成视频同目录)
  1211. */
  1212. private function buildTaskMediaObjectKey(string $taskId, string $fileName): string
  1213. {
  1214. return 'uploads/videos/' . date('Ymd') . '/' . $this->sanitizeTaskIdSegment($taskId) . '/' . ltrim($fileName, '/');
  1215. }
  1216. /**
  1217. * 解析帧图片(含本地路径与暂存 OSS 信息,供创建任务后按 AI id 归档)
  1218. * @return array{type:string,api_url:string,local_path:string,staging_object_key:string}
  1219. */
  1220. private function resolveFrameImagePayload(array $params, string $role, string &$error = ''): array
  1221. {
  1222. $empty = ['type' => 'empty', 'api_url' => '', 'local_path' => '', 'staging_object_key' => ''];
  1223. $prefix = $role === 'last' ? 'last' : 'first';
  1224. $error = '';
  1225. $taskId = trim((string)($params['task_id'] ?? $params['video_id'] ?? ''));
  1226. $ossTaskId = $taskId !== '' ? $taskId : self::FRAME_OSS_STAGING_ID;
  1227. $uploadedFile = $this->request->file("{$prefix}_image");
  1228. if (!empty($uploadedFile)) {
  1229. $fileList = is_array($uploadedFile) ? $uploadedFile : [$uploadedFile];
  1230. foreach ($fileList as $file) {
  1231. if (!$file) {
  1232. continue;
  1233. }
  1234. $fileError = '';
  1235. $result = $this->uploadFrameFileToOss($file, $prefix, $fileError, $ossTaskId);
  1236. if (($result['url'] ?? '') !== '') {
  1237. return [
  1238. 'type' => 'local',
  1239. 'api_url' => $result['url'],
  1240. 'local_path' => $result['local_path'] ?? '',
  1241. 'staging_object_key' => $result['object_key'] ?? '',
  1242. ];
  1243. }
  1244. if ($fileError !== '') {
  1245. $error = $fileError;
  1246. }
  1247. }
  1248. }
  1249. $base64Keys = ["{$prefix}_image", "{$prefix}_image_base64"];
  1250. foreach ($base64Keys as $key) {
  1251. if (empty($params[$key]) || !is_string($params[$key])) {
  1252. continue;
  1253. }
  1254. $raw = trim($params[$key]);
  1255. if ($raw === '' || strlen($raw) < 50) {
  1256. continue;
  1257. }
  1258. preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $raw, $bm);
  1259. if (empty($bm)) {
  1260. $error = ($prefix === 'first' ? '首帧图' : '尾帧图') . '未找到图片数据';
  1261. continue;
  1262. }
  1263. $result = $this->uploadBase64ImageToOss($raw, $prefix, $ossTaskId, $error);
  1264. if (($result['url'] ?? '') !== '') {
  1265. return [
  1266. 'type' => 'local',
  1267. 'api_url' => $result['url'],
  1268. 'local_path' => $result['local_path'] ?? '',
  1269. 'staging_object_key' => $result['object_key'] ?? '',
  1270. ];
  1271. }
  1272. }
  1273. $urlKey = "{$prefix}_image_url";
  1274. if (!empty($params[$urlKey])) {
  1275. $url = trim((string)$params[$urlKey]);
  1276. if (stripos($url, 'http://') === 0 || stripos($url, 'https://') === 0) {
  1277. return ['type' => 'external', 'api_url' => $url, 'local_path' => '', 'staging_object_key' => ''];
  1278. }
  1279. }
  1280. return $empty;
  1281. }
  1282. /**
  1283. * AI 返回任务 id 后,将本地帧图上传到 uploads/videos/{日期}/{taskId}/(与生成视频同目录)
  1284. */
  1285. private function finalizeFrameImageToOss(array $payload, string $taskId): string
  1286. {
  1287. if (($payload['type'] ?? '') === 'external') {
  1288. return (string)($payload['api_url'] ?? '');
  1289. }
  1290. if (($payload['type'] ?? '') !== 'local') {
  1291. return '';
  1292. }
  1293. $localPath = (string)($payload['local_path'] ?? '');
  1294. if ($localPath === '' || !is_file($localPath)) {
  1295. return (string)($payload['api_url'] ?? '');
  1296. }
  1297. $objectKey = $this->buildTaskMediaObjectKey($taskId, basename($localPath));
  1298. $stagingKey = (string)($payload['staging_object_key'] ?? '');
  1299. if ($stagingKey !== '' && $stagingKey === $objectKey) {
  1300. return (string)($payload['api_url'] ?? '') ?: Common::ossFullUrl($objectKey);
  1301. }
  1302. $upload = $this->uploadToOSS($localPath, $objectKey);
  1303. if (!$upload['success']) {
  1304. Log::write('[finalizeFrameImageToOss] OSS上传失败: ' . $objectKey, 'error');
  1305. return (string)($payload['api_url'] ?? '');
  1306. }
  1307. if ($stagingKey !== '' && $stagingKey !== $objectKey) {
  1308. Common::deleteOssObject($stagingKey);
  1309. }
  1310. return $upload['url'] !== '' ? $upload['url'] : Common::ossFullUrl($objectKey);
  1311. }
  1312. /**
  1313. * 解析帧图片:form-data 文件 > base64 > http(s) URL
  1314. */
  1315. private function resolveFrameImageUrl(array $params, string $role, string &$error = ''): string
  1316. {
  1317. $payload = $this->resolveFrameImagePayload($params, $role, $error);
  1318. return (string)($payload['api_url'] ?? '');
  1319. }
  1320. /**
  1321. * form-data 上传的图片落盘并同步 OSS
  1322. * @return array{url:string,local_path:string,object_key:string}
  1323. */
  1324. private function uploadFrameFileToOss($file, string $roleLabel, string &$error = '', string $taskId = ''): array
  1325. {
  1326. $empty = ['url' => '', 'local_path' => '', 'object_key' => ''];
  1327. if ($taskId === '') {
  1328. $taskId = self::FRAME_OSS_STAGING_ID;
  1329. }
  1330. $error = '';
  1331. $ext = $this->resolveUploadedImageExt($file);
  1332. if ($ext === '') {
  1333. $error = '不支持的图片格式';
  1334. Log::write('[uploadFrameFileToOss] ' . $error, 'error');
  1335. return $empty;
  1336. }
  1337. $uploadInfo = $file->getInfo();
  1338. $tmpPath = isset($uploadInfo['tmp_name']) ? (string)$uploadInfo['tmp_name'] : '';
  1339. if ($tmpPath === '' || !is_file($tmpPath)) {
  1340. $tmpPath = (string)($file->getRealPath() ?: '');
  1341. }
  1342. if ($tmpPath === '' || !is_file($tmpPath)) {
  1343. $uploadErr = $uploadInfo['error'] ?? UPLOAD_ERR_NO_FILE;
  1344. $error = '未接收到上传文件(错误码' . $uploadErr . ')';
  1345. Log::write('[uploadFrameFileToOss] ' . $error, 'error');
  1346. return $empty;
  1347. }
  1348. $saveDir = $this->buildTaskMediaLocalDir($taskId);
  1349. if (!is_dir($saveDir)) {
  1350. mkdir($saveDir, 0755, true);
  1351. }
  1352. $saveFileName = $roleLabel . '_' . str_replace('.', '', uniqid('', true)) . '.' . $ext;
  1353. $localFullPath = $saveDir . $saveFileName;
  1354. $saved = false;
  1355. if (method_exists($file, 'isValid') && $file->isValid()) {
  1356. $info = $file->move($saveDir, $saveFileName);
  1357. if ($info) {
  1358. $localFullPath = $saveDir . $info->getFilename();
  1359. $saved = true;
  1360. }
  1361. }
  1362. if (!$saved && !@copy($tmpPath, $localFullPath)) {
  1363. $moveErr = method_exists($file, 'getError') ? (string)$file->getError() : 'copy失败';
  1364. $error = '图片保存失败: ' . $moveErr;
  1365. Log::write('[uploadFrameFileToOss] ' . $error, 'error');
  1366. return $empty;
  1367. }
  1368. $objectKey = $this->buildTaskMediaObjectKey($taskId, basename($localFullPath));
  1369. $upload = $this->uploadToOSS($localFullPath, $objectKey);
  1370. if (!$upload['success']) {
  1371. $error = 'OSS上传失败';
  1372. Log::write('[uploadFrameFileToOss] ' . $error . ' | ' . $objectKey, 'error');
  1373. return $empty;
  1374. }
  1375. $url = $upload['url'] !== '' ? $upload['url'] : Common::ossFullUrl($objectKey);
  1376. return [
  1377. 'url' => $url,
  1378. 'local_path' => $localFullPath,
  1379. 'object_key' => $upload['object_key'] ?? $objectKey,
  1380. ];
  1381. }
  1382. /**
  1383. * 解析上传图片扩展名
  1384. */
  1385. private function resolveUploadedImageExt($file): string
  1386. {
  1387. $name = $file->getInfo('name') ?? '';
  1388. $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
  1389. if ($ext === 'jpeg') {
  1390. $ext = 'jpg';
  1391. }
  1392. $allowed = ['jpg', 'png', 'gif', 'webp', 'bmp'];
  1393. if ($ext && in_array($ext, $allowed, true)) {
  1394. return $ext;
  1395. }
  1396. $mime = method_exists($file, 'getMime') ? strtolower((string)$file->getMime()) : '';
  1397. $map = [
  1398. 'image/jpeg' => 'jpg',
  1399. 'image/png' => 'png',
  1400. 'image/gif' => 'gif',
  1401. 'image/webp' => 'webp',
  1402. 'image/bmp' => 'bmp',
  1403. ];
  1404. return $map[$mime] ?? '';
  1405. }
  1406. /**
  1407. * base64 图片落盘并上传 OSS(前端传 data:image/...;base64,...)
  1408. * @return array{url:string,local_path:string,object_key:string}
  1409. */
  1410. private function uploadBase64ImageToOss(string $base64Input, string $roleLabel, string $taskId = '', string &$error = ''): array
  1411. {
  1412. $empty = ['url' => '', 'local_path' => '', 'object_key' => ''];
  1413. if ($taskId === '') {
  1414. $taskId = self::FRAME_OSS_STAGING_ID;
  1415. }
  1416. $error = '';
  1417. $parsed = $this->parseBase64Image($base64Input);
  1418. if ($parsed === null) {
  1419. $error = '图片Base64解析失败';
  1420. Log::write('[uploadBase64ImageToOss] ' . $error, 'error');
  1421. return $empty;
  1422. }
  1423. [$ext, $imageData] = $parsed;
  1424. $saveDir = $this->buildTaskMediaLocalDir($taskId);
  1425. if (!is_dir($saveDir)) {
  1426. mkdir($saveDir, 0755, true);
  1427. }
  1428. $fileName = $roleLabel . '_' . str_replace('.', '', uniqid('', true)) . '.' . $ext;
  1429. $localFullPath = $saveDir . $fileName;
  1430. if (file_put_contents($localFullPath, $imageData) === false) {
  1431. Log::write('[uploadBase64ImageToOss] 本地保存失败: ' . $localFullPath, 'error');
  1432. return $empty;
  1433. }
  1434. $objectKey = $this->buildTaskMediaObjectKey($taskId, $fileName);
  1435. $upload = $this->uploadToOSS($localFullPath, $objectKey);
  1436. if (!$upload['success']) {
  1437. Log::write('[uploadBase64ImageToOss] OSS上传失败: ' . $objectKey, 'error');
  1438. return $empty;
  1439. }
  1440. $url = $upload['url'] !== '' ? $upload['url'] : Common::ossFullUrl($objectKey);
  1441. return [
  1442. 'url' => $url,
  1443. 'local_path' => $localFullPath,
  1444. 'object_key' => $upload['object_key'] ?? $objectKey,
  1445. ];
  1446. }
  1447. /**
  1448. * 解析 base64 图片(与 ImageToImageJob 一致:data:image/(png|jpg|jpeg);base64,...)
  1449. * @return array{0:string,1:string}|null [扩展名, 二进制内容]
  1450. */
  1451. private function parseBase64Image(string $base64Input): ?array
  1452. {
  1453. $base64Input = trim($base64Input);
  1454. if ($base64Input === '') {
  1455. return null;
  1456. }
  1457. preg_match('/data:image\/(png|jpg|jpeg);base64,([^"]+)/', $base64Input, $m);
  1458. if (empty($m)) {
  1459. return null;
  1460. }
  1461. $rawBase64 = preg_replace('/\s+/', '', $m[2]);
  1462. $ext = $m[1];
  1463. $imageData = base64_decode($rawBase64, true);
  1464. if ($imageData === false || strlen($imageData) < 100) {
  1465. return null;
  1466. }
  1467. return [$ext, $imageData];
  1468. }
  1469. /**
  1470. * 将本地文件上传到阿里云 OSS
  1471. *
  1472. * @param string $file 本地完整路径,或 public 下相对路径(如 uploads/videos/20260604/xxx.mp4)
  1473. * @param string $objectKey OSS 对象键;传 uploads/ 开头或带扩展名则视为完整键,否则作为子目录标识(如 task_id)
  1474. * @return array{success:bool,object_key:string,url:string}
  1475. */
  1476. private function uploadToOSS(string $file, string $objectKey = ''): array
  1477. {
  1478. $localFullPath = $this->resolvePublicLocalPath($file);
  1479. if ($localFullPath === '') {
  1480. Log::write('[uploadToOSS] 本地文件不存在: ' . $file, 'error');
  1481. return ['success' => false, 'object_key' => '', 'url' => ''];
  1482. }
  1483. $fileName = basename($localFullPath);
  1484. if ($objectKey !== '' && (strpos($objectKey, 'uploads/') === 0 || preg_match('/\.[a-z0-9]{1,8}$/i', $objectKey))) {
  1485. $ossObjectKey = Common::normalizeOssObjectKey($objectKey);
  1486. } else {
  1487. $segments = ['uploads', 'videos', date('Ymd')];
  1488. if ($objectKey !== '') {
  1489. $segments[] = preg_replace('/[\\\\\/:*?"<>|]/u', '_', $objectKey);
  1490. }
  1491. $segments[] = $fileName;
  1492. $ossObjectKey = implode('/', $segments);
  1493. }
  1494. $success = $this->uploadLocalFileToAliyunOss($localFullPath, $ossObjectKey);
  1495. return [
  1496. 'success' => $success,
  1497. 'object_key' => $ossObjectKey,
  1498. 'url' => $success ? Common::ossFullUrl($ossObjectKey) : '',
  1499. ];
  1500. }
  1501. /**
  1502. * 上传本地文件到阿里云 OSS(仅 WorkOrder 内实现,不修改 Common)
  1503. */
  1504. private function uploadLocalFileToAliyunOss(string $localFullPath, string $objectKey): bool
  1505. {
  1506. if (!Common::isOssEnabled() || !is_file($localFullPath)) {
  1507. return false;
  1508. }
  1509. $objectKey = Common::normalizeOssObjectKey($objectKey);
  1510. if ($objectKey === '') {
  1511. return false;
  1512. }
  1513. if (class_exists(\OSS\OssClient::class, true)) {
  1514. try {
  1515. $config = Common::getOssConfig();
  1516. $client = new \OSS\OssClient(
  1517. $config['accessKeyId'],
  1518. $config['accessKeySecret'],
  1519. $config['endpoint']
  1520. );
  1521. $client->uploadFile($config['bucket'], $objectKey, $localFullPath);
  1522. return true;
  1523. } catch (\Throwable $e) {
  1524. Log::write('[uploadLocalFileToAliyunOss SDK] ' . $e->getMessage() . ' | ' . $objectKey, 'error');
  1525. }
  1526. }
  1527. return $this->putLocalFileToAliyunOssByCurl($localFullPath, $objectKey);
  1528. }
  1529. /**
  1530. * 无 OSS SDK 时通过 REST PUT 上传
  1531. */
  1532. private function putLocalFileToAliyunOssByCurl(string $localFullPath, string $objectKey): bool
  1533. {
  1534. $config = Common::getOssConfig();
  1535. $content = file_get_contents($localFullPath);
  1536. if ($content === false) {
  1537. return false;
  1538. }
  1539. $mime = function_exists('mime_content_type') ? (mime_content_type($localFullPath) ?: '') : '';
  1540. if ($mime === '') {
  1541. $ext = strtolower(pathinfo($localFullPath, PATHINFO_EXTENSION));
  1542. $mimeMap = [
  1543. 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1544. 'gif' => 'image/gif', 'webp' => 'image/webp', 'mp4' => 'video/mp4',
  1545. ];
  1546. $mime = $mimeMap[$ext] ?? 'application/octet-stream';
  1547. }
  1548. $date = gmdate('D, d M Y H:i:s \G\M\T');
  1549. $bucket = $config['bucket'];
  1550. $endpoint = ltrim((string)$config['endpoint'], 'https://');
  1551. $endpoint = ltrim($endpoint, 'http://');
  1552. $canonicalizedResource = '/' . $bucket . '/' . $objectKey;
  1553. $stringToSign = "PUT\n\n{$mime}\n{$date}\n{$canonicalizedResource}";
  1554. $signature = base64_encode(hash_hmac('sha1', $stringToSign, $config['accessKeySecret'], true));
  1555. $urlPath = implode('/', array_map('rawurlencode', explode('/', $objectKey)));
  1556. $url = 'https://' . $bucket . '.' . $endpoint . '/' . $urlPath;
  1557. $ch = curl_init($url);
  1558. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  1559. curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
  1560. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1561. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  1562. curl_setopt($ch, CURLOPT_HTTPHEADER, [
  1563. 'Date: ' . $date,
  1564. 'Content-Type: ' . $mime,
  1565. 'Authorization: OSS ' . $config['accessKeyId'] . ':' . $signature,
  1566. ]);
  1567. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  1568. $response = curl_exec($ch);
  1569. $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
  1570. $curlError = curl_error($ch);
  1571. curl_close($ch);
  1572. if ($httpCode >= 200 && $httpCode < 300) {
  1573. return true;
  1574. }
  1575. Log::write(
  1576. '[putLocalFileToAliyunOssByCurl] http=' . $httpCode
  1577. . ' err=' . $curlError
  1578. . ' resp=' . substr((string)$response, 0, 500)
  1579. . ' | objectKey=' . $objectKey,
  1580. 'error'
  1581. );
  1582. return false;
  1583. }
  1584. /**
  1585. * 解析为 public 目录下的本地绝对路径
  1586. */
  1587. private function resolvePublicLocalPath(string $file): string
  1588. {
  1589. $file = str_replace('\\', '/', trim($file));
  1590. if ($file === '') {
  1591. return '';
  1592. }
  1593. if (is_file($file)) {
  1594. return $file;
  1595. }
  1596. $publicPath = str_replace('\\', '/', ROOT_PATH . 'public/' . ltrim($file, '/'));
  1597. return is_file($publicPath) ? $publicPath : '';
  1598. }
  1599. }