WorkOrder.php 64 KB

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