Client.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. <?php
  2. namespace Qcloud\Cos;
  3. use GuzzleHttp\Client as HttpClient;
  4. use GuzzleHttp\Exception\RequestException;
  5. use GuzzleHttp\HandlerStack;
  6. use Psr\Http\Message\RequestInterface;
  7. use Psr\Http\Message\ResponseInterface;
  8. use GuzzleHttp\Command\Guzzle\Description;
  9. use GuzzleHttp\Command\Guzzle\GuzzleClient;
  10. use GuzzleHttp\Command\Guzzle\Deserializer;
  11. use GuzzleHttp\Command\CommandInterface;
  12. use GuzzleHttp\Exception\ConnectException;
  13. use GuzzleHttp\Middleware;
  14. use GuzzleHttp\Psr7;
  15. use GuzzleHttp\Psr7\Uri;
  16. /**
  17. * @method object AbortMultipartUpload(array $args) 舍弃一个分块上传且删除已上传的分片块
  18. * @method object CreateBucket(array $args) 创建存储桶(Bucket)
  19. * @method object CompleteMultipartUpload(array $args) 完成整个分块上传
  20. * @method object CreateMultipartUpload(array $args) 初始化分块上传
  21. * @method object CopyObject(array $args) 复制对象
  22. * @method object DeleteBucket(array $args) 删除存储桶 (Bucket)
  23. * @method object DeleteBucketCors(array $args) 删除跨域访问配置信息
  24. * @method object DeleteBucketTagging(array $args) 删除存储桶标签信息
  25. * @method object DeleteBucketInventory(array $args) 删除存储桶标清单任务
  26. * @method object DeleteObject(array $args) 删除 COS 上单个对象
  27. * @method object DeleteObjects(array $args) 批量删除 COS 对象
  28. * @method object DeleteBucketWebsite(array $args) 删除存储桶(Bucket)的website
  29. * @method object DeleteBucketLifecycle(array $args) 删除存储桶(Bucket)的生命周期配置
  30. * @method object DeleteBucketReplication(array $args) 删除跨区域复制配置
  31. * @method object PutObjectTagging(array $args) 配置对象标签
  32. * @method object GetObjectTagging(array $args) 获取对象标签信息
  33. * @method object DeleteObjectTagging(array $args) 删除对象标签
  34. * @method object GetObject(array $args) 下载对象
  35. * @method object GetObjectAcl(array $args) 获取 COS 对象的访问权限信息(Access Control List, ACL)
  36. * @method object GetBucketAcl(array $args) 获取存储桶(Bucket)的访问权限信息(Access Control List, ACL)
  37. * @method object GetBucketCors(array $args) 查询存储桶(Bucket)跨域访问配置信息
  38. * @method object GetBucketDomain(array $args) 查询存储桶(Bucket)Domain配置信息
  39. * @method object GetBucketAccelerate(array $args) 查询存储桶(Bucket)Accelerate配置信息
  40. * @method object GetBucketWebsite(array $args) 查询存储桶(Bucket)Website配置信息
  41. * @method object GetBucketLifecycle(array $args) 查询存储桶(Bucket)的生命周期配置
  42. * @method object GetBucketVersioning(array $args) 获取存储桶(Bucket)版本控制信息
  43. * @method object GetBucketReplication(array $args) 获取存储桶(Bucket)跨区域复制配置信息
  44. * @method object GetBucketLocation(array $args) 获取存储桶(Bucket)所在的地域信息
  45. * @method object GetBucketNotification(array $args) 获取存储桶(Bucket)Notification信息
  46. * @method object GetBucketLogging(array $args) 获取存储桶(Bucket)日志信息
  47. * @method object GetBucketInventory(array $args) 获取存储桶(Bucket)清单信息
  48. * @method object GetBucketTagging(array $args) 获取存储桶(Bucket)标签信息
  49. * @method object UploadPart(array $args) 分块上传
  50. * @method object PutObject(array $args) 上传对象
  51. * @method object AppendObject(array $args) 追加对象
  52. * @method object PutObjectAcl(array $args) 设置 COS 对象的访问权限信息(Access Control List, ACL)
  53. * @method object PutBucketAcl(array $args) 设置存储桶(Bucket)的访问权限 (Access Control List, ACL)
  54. * @method object PutBucketCors(array $args) 设置存储桶(Bucket)的跨域配置信息
  55. * @method object PutBucketDomain(array $args) 设置存储桶(Bucket)的Domain信息
  56. * @method object PutBucketLifecycle(array $args) 设置存储桶(Bucket)生命周期配置
  57. * @method object PutBucketVersioning(array $args) 存储桶(Bucket)版本控制
  58. * @method object PutBucketAccelerate(array $args) 配置存储桶(Bucket)Accelerate
  59. * @method object PutBucketWebsite(array $args) 配置存储桶(Bucket)website
  60. * @method object PutBucketReplication(array $args) 配置存储桶(Bucket)跨区域复制
  61. * @method object PutBucketNotification(array $args) 设置存储桶(Bucket)的回调设置
  62. * @method object PutBucketTagging(array $args) 配置存储桶(Bucket)标签
  63. * @method object PutBucketLogging(array $args) 开启存储桶(Bucket)日志服务
  64. * @method object PutBucketInventory(array $args) 配置存储桶(Bucket)清单
  65. * @method object RestoreObject(array $args) 回热归档对象
  66. * @method object ListParts(array $args) 查询存储桶(Bucket)中正在进行中的分块上传对象
  67. * @method object ListObjects(array $args) 查询存储桶(Bucket)下的部分或者全部对象
  68. * @method object ListBuckets 获取所属账户的所有存储空间列表
  69. * @method object ListObjectVersions(array $args) 获取多版本对象
  70. * @method object ListMultipartUploads(array $args) 获取已上传分块列表
  71. * @method object ListBucketInventoryConfigurations(array $args) 获取清单列表
  72. * @method object HeadObject(array $args) 获取对象的meta信息
  73. * @method object HeadBucket(array $args) 存储桶(Bucket)是否存在
  74. * @method object UploadPartCopy(array $args) 分块copy
  75. * @method object SelectObjectContent(array $args) 检索对象内容
  76. * @method object PutBucketIntelligentTiering(array $args) 存储桶(Bucket)开启智能分层
  77. * @method object GetBucketIntelligentTiering(array $args) 查询存储桶(Bucket)智能分层
  78. * @method object ImageInfo(array $args) 万象-获取图片基本信息
  79. * @method object ImageExif(array $args) 万象-获取图片EXIF信息
  80. * @method object ImageAve(array $args) 万象-获取图片主色调信息
  81. * @method object ImageProcess(array $args) 万象-云上数据处理
  82. * @method object Qrcode(array $args) 万象-二维码下载时识别
  83. * @method object QrcodeGenerate(array $args) 万象-二维码生成
  84. * @method object DetectLabel(array $args) 万象-图片标签
  85. * @method object PutBucketImageStyle(array $args) 万象-增加样式
  86. * @method object GetBucketImageStyle(array $args) 万象-查询样式
  87. * @method object DeleteBucketImageStyle(array $args) 万象-删除样式
  88. * @method object PutBucketGuetzli(array $args) 万象-开通Guetzli压缩
  89. * @method object GetBucketGuetzli(array $args) 万象-查询Guetzli状态
  90. * @method object DeleteBucketGuetzli(array $args) 万象-关闭Guetzli压缩
  91. * @method object GetObjectSensitiveContentRecognition(array $args) 图片审核
  92. * @method object DetectText(array $args) 文本审核
  93. * @method object GetSnapshot(array $args) 媒体截图
  94. * @method object PutBucketReferer(array $args) 添加防盗链
  95. * @method object GetBucketReferer(array $args) 获取防盗链规则
  96. * @method object GetMediaInfo(array $args) 获取媒体信息
  97. * @method object CreateMediaTranscodeJobs(array $args) 媒体转码
  98. * @method object CreateMediaJobs(array $args) 媒体任务
  99. * @method object DescribeMediaJob(array $args) 查询指定的媒体任务
  100. * @method object DescribeMediaJobs(array $args) 拉取拉取符合条件的媒体任务
  101. * @method object CreateMediaSnapshotJobs(array $args) 媒体截图
  102. * @method object CreateMediaConcatJobs(array $args) 媒体拼接
  103. * @method object DetectAudio(array $args) 音频审核
  104. * @method object GetDetectAudioResult(array $args) 主动获取音频审核结果
  105. * @method object GetDetectTextResult(array $args) 主动获取文本文件审核结果
  106. * @method object DetectVideo(array $args) 视频审核
  107. * @method object GetDetectVideoResult(array $args) 主动获取视频审核结果
  108. * @method object DetectDocument(array $args) 文档审核
  109. * @method object GetDetectDocumentResult(array $args) 主动获取文档审核结果
  110. * @method object CreateDocProcessJobs(array $args) 提交文档转码任务
  111. * @method object DescribeDocProcessQueues(array $args) 查询文档转码队列
  112. * @method object DescribeDocProcessJob(array $args) 查询文档转码任务
  113. * @method object GetDescribeDocProcessJobs(array $args) 拉取符合条件的文档转码任务
  114. * @method object DetectImage(array $args) 图片审核
  115. * @method object DetectImages(array $args) 图片审核-批量
  116. * @method object DetectVirus(array $args) 云查毒
  117. * @method object GetDetectVirusResult(array $args) 查询病毒检测任务结果
  118. * @method object GetDetectImageResult(array $args) 主动获取图片审核结果
  119. * @method object CreateMediaVoiceSeparateJobs(array $args) 提交人声分离任务
  120. * @method object DescribeMediaVoiceSeparateJob(array $args) 查询指定的人声分离任务
  121. * @method object DetectWebpage(array $args) 提交网页审核任务
  122. * @method object GetDetectWebpageResult(array $args) 查询网页审核任务结果
  123. * @method object DescribeMediaBuckets(array $args) 查询媒体处理开通状态
  124. * @method object GetPrivateM3U8(array $args) 获取私有 M3U8 ts 资源的下载授权
  125. * @method object DescribeMediaQueues(array $args) 搜索媒体处理队列
  126. * @method object UpdateMediaQueue(array $args) 更新媒体处理队列
  127. * @method object CreateMediaSmartCoverJobs(array $args) 提交智能封面任务
  128. * @method object CreateMediaVideoProcessJobs(array $args) 提交视频增强任务
  129. * @method object CreateMediaVideoMontageJobs(array $args) 提交精彩集锦任务
  130. * @method object CreateMediaAnimationJobs(array $args) 提交动图任务
  131. * @method object CreateMediaPicProcessJobs(array $args) 提交图片处理任务
  132. * @method object CreateMediaSegmentJobs(array $args) 提交转封装任务
  133. * @method object CreateMediaVideoTagJobs(array $args) 提交视频标签任务
  134. * @method object CreateMediaSuperResolutionJobs(array $args) 提交超分辨率任务
  135. * @method object CreateMediaSDRtoHDRJobs(array $args) 提交 SDR to HDR 任务
  136. * @method object CreateMediaDigitalWatermarkJobs(array $args) 嵌入数字水印任务(添加水印)
  137. * @method object CreateMediaExtractDigitalWatermarkJobs(array $args) 提取数字水印任务(提取水印)
  138. * @method object DetectLiveVideo(array $args) 直播流审核
  139. * @method object CancelLiveVideoAuditing(array $args) 取消直播流审核
  140. * @method object OpticalOcrRecognition(array $args) 通用文字识别
  141. * @method object TriggerWorkflow(array $args) 手动触发工作流
  142. * @method object GetWorkflowInstances(array $args) 获取工作流实例列表
  143. * @method object GetWorkflowInstance(array $args) 获取工作流实例详情
  144. * @method object CreateMediaSnapshotTemplate(array $args) 新增截图模板
  145. * @method object UpdateMediaSnapshotTemplate(array $args) 更新截图模板
  146. * @method object CreateMediaTranscodeTemplate(array $args) 新增转码模板
  147. * @method object UpdateMediaTranscodeTemplate(array $args) 更新转码模板
  148. * @method object CreateMediaHighSpeedHdTemplate(array $args) 新增极速高清转码模板
  149. * @method object UpdateMediaHighSpeedHdTemplate(array $args) 更新极速高清转码模板
  150. * @method object CreateMediaAnimationTemplate(array $args) 新增动图模板
  151. * @method object UpdateMediaAnimationTemplate(array $args) 更新动图模板
  152. * @method object CreateMediaConcatTemplate(array $args) 新增拼接模板
  153. * @method object UpdateMediaConcatTemplate(array $args) 更新拼接模板
  154. * @method object CreateMediaVideoProcessTemplate(array $args) 新增视频增强模板
  155. * @method object UpdateMediaVideoProcessTemplate(array $args) 更新视频增强模板
  156. * @method object CreateMediaVideoMontageTemplate(array $args) 新增精彩集锦模板
  157. * @method object UpdateMediaVideoMontageTemplate(array $args) 更新精彩集锦模板
  158. * @method object CreateMediaVoiceSeparateTemplate(array $args) 新增人声分离模板
  159. * @method object UpdateMediaVoiceSeparateTemplate(array $args) 更新人声分离模板
  160. * @method object CreateMediaSuperResolutionTemplate(array $args) 新增超分辨率模板
  161. * @method object UpdateMediaSuperResolutionTemplate(array $args) 更新超分辨率模板
  162. * @method object CreateMediaPicProcessTemplate(array $args) 新增图片处理模板
  163. * @method object UpdateMediaPicProcessTemplate(array $args) 更新图片处理模板
  164. * @method object CreateMediaWatermarkTemplate(array $args) 新增水印模板
  165. * @method object UpdateMediaWatermarkTemplate(array $args) 更新水印模板
  166. * @method object DescribeMediaTemplates(array $args) 查询模板列表
  167. * @method object DescribeWorkflow(array $args) 搜索工作流
  168. * @method object DeleteWorkflow(array $args) 删除工作流
  169. * @method object CreateInventoryTriggerJob(array $args) 触发批量存量任务
  170. * @method object DescribeInventoryTriggerJobs(array $args) 批量拉取存量任务
  171. * @method object DescribeInventoryTriggerJob(array $args) 查询存量任务
  172. * @method object CancelInventoryTriggerJob(array $args) 取消存量任务
  173. * @method object CreateMediaNoiseReductionJobs(array $args) 提交音频降噪任务
  174. * @method object ImageRepairProcess(array $args) 图片水印修复
  175. * @method object ImageDetectCarProcess(array $args) 车辆车牌检测
  176. * @method object ImageAssessQualityProcess(array $args) 图片质量评估
  177. * @method object ImageSearchOpen(array $args) 开通以图搜图
  178. * @method object ImageSearchAdd(array $args) 添加图库图片
  179. * @method object ImageSearch(array $args) 图片搜索接口
  180. * @method object ImageSearchDelete(array $args) 图片搜索接口
  181. * @method object BindCiService(array $args) 绑定数据万象服务
  182. * @method object GetCiService(array $args) 查询数据万象服务
  183. * @method object UnBindCiService(array $args) 解绑数据万象服务
  184. * @method object GetHotLink(array $args) 查询防盗链
  185. * @method object AddHotLink(array $args) 查询防盗链
  186. * @method object OpenOriginProtect(array $args) 开通原图保护
  187. * @method object GetOriginProtect(array $args) 查询原图保护状态
  188. * @method object CloseOriginProtect(array $args) 关闭原图保护
  189. * @method object ImageDetectFace(array $args) 人脸检测
  190. * @method object ImageFaceEffect(array $args) 人脸特效
  191. * @method object IDCardOCR(array $args) 身份证识别
  192. * @method object IDCardOCRByUpload(array $args) 身份证识别-上传时处理
  193. * @method object GetLiveCode(array $args) 获取数字验证码
  194. * @method object GetActionSequence(array $args) 获取动作顺序
  195. * @method object DescribeDocProcessBuckets(array $args) 查询文档预览开通状态
  196. * @method object UpdateDocProcessQueue(array $args) 更新文档转码队列
  197. * @method object CreateMediaQualityEstimateJobs(array $args) 提交视频质量评分任务
  198. * @method object CreateMediaStreamExtractJobs(array $args) 提交音视频流分离任务
  199. * @method object FileJobs4Hash(array $args) 哈希值计算同步请求
  200. * @method object OpenFileProcessService(array $args) 开通文件处理服务
  201. * @method object GetFileProcessQueueList(array $args) 搜索文件处理队列
  202. * @method object UpdateFileProcessQueue(array $args) 更新文件处理的队列
  203. * @method object CreateFileHashCodeJobs(array $args) 提交哈希值计算任务
  204. * @method object GetFileHashCodeResult(array $args) 查询哈希值计算结果
  205. * @method object CreateFileUncompressJobs(array $args) 提交文件解压任务
  206. * @method object GetFileUncompressResult(array $args) 查询文件解压结果
  207. * @method object CreateFileCompressJobs(array $args) 提交多文件打包压缩任务
  208. * @method object GetFileCompressResult(array $args) 查询多文件打包压缩结果
  209. * @method object CreateM3U8PlayListJobs(array $args) 获取指定hls/m3u8文件指定时间区间内的ts资源
  210. * @method object GetPicQueueList(array $args) 搜索图片处理队列
  211. * @method object UpdatePicQueue(array $args) 更新图片处理队列
  212. * @method object GetPicBucketList(array $args) 查询图片处理服务状态
  213. * @method object GetAiBucketList(array $args) 查询 AI 内容识别服务状态
  214. * @method object OpenAiService(array $args) 开通 AI 内容识别
  215. * @method object CloseAiService(array $args) 关闭AI内容识别服务
  216. * @method object GetAiQueueList(array $args) 搜索 AI 内容识别队列
  217. * @method object UpdateAiQueue(array $args) 更新 AI 内容识别队列
  218. * @method object CreateMediaTranscodeProTemplate(array $args) 创建音视频转码 pro 模板
  219. * @method object UpdateMediaTranscodeProTemplate(array $args) 更新音视频转码 pro 模板
  220. * @method object CreateVoiceTtsTemplate(array $args) 创建语音合成模板
  221. * @method object UpdateVoiceTtsTemplate(array $args) 更新语音合成模板
  222. * @method object CreateMediaSmartCoverTemplate(array $args) 创建智能封面模板
  223. * @method object UpdateMediaSmartCoverTemplate(array $args) 更新智能封面模板
  224. * @method object CreateVoiceSpeechRecognitionTemplate(array $args) 创建语音识别模板
  225. * @method object UpdateVoiceSpeechRecognitionTemplate(array $args) 更新语音识别模板
  226. * @method object CreateVoiceTtsJobs(array $args) 提交一个语音合成任务
  227. * @method object CreateAiTranslationJobs(array $args) 提交一个翻译任务
  228. * @method object CreateVoiceSpeechRecognitionJobs(array $args) 提交一个语音识别任务
  229. * @method object CreateAiWordsGeneralizeJobs(array $args) 提交一个分词任务
  230. * @method object CreateMediaVideoEnhanceJobs(array $args) 提交画质增强任务
  231. * @method object CreateMediaVideoEnhanceTemplate(array $args) 创建画质增强模板
  232. * @method object UpdateMediaVideoEnhanceTemplate(array $args) 更新画质增强模板
  233. * @method object OpenImageSlim(array $args) 开通图片瘦身
  234. * @method object CloseImageSlim(array $args) 关闭图片瘦身
  235. * @method object GetImageSlim(array $args) 查询图片瘦身状态
  236. * @method object AutoTranslationBlockProcess(array $args) 实时文字翻译
  237. * @method object RecognizeLogoProcess(array $args) Logo 识别
  238. * @method object DetectLabelProcess(array $args) 图片标签
  239. * @method object AIGameRecProcess(array $args) 游戏场景识别
  240. * @method object AIBodyRecognitionProcess(array $args) 人体识别
  241. * @method object DetectPetProcess(array $args) 宠物识别
  242. * @method object AILicenseRecProcess(array $args) 卡证识别
  243. * @method object CreateMediaTargetRecTemplate(array $args) 创建视频目标检测模板
  244. * @method object UpdateMediaTargetRecTemplate(array $args) 更新视频目标检测模板
  245. * @method object CreateMediaTargetRecJobs(array $args) 提交视频目标检测任务
  246. * @method object CreateMediaSegmentVideoBodyJobs(array $args) 提交视频人像抠图任务
  247. * @method object OpenAsrService(array $args) 开通智能语音服务
  248. * @method object GetAsrBucketList(array $args) 查询智能语音服务
  249. * @method object CloseAsrService(array $args) 关闭智能语音服务
  250. * @method object GetAsrQueueList(array $args) 查询智能语音队列
  251. * @method object UpdateAsrQueue(array $args) 更新智能语音队列
  252. * @method object CreateMediaNoiseReductionTemplate(array $args) 创建音频降噪模板
  253. * @method object UpdateMediaNoiseReductionTemplate(array $args) 更新音频降噪模板
  254. * @method object CreateVoiceSoundHoundJobs(array $args) 提交听歌识曲任务
  255. * @method object CreateVoiceVocalScoreJobs(array $args) 提交音乐评分任务
  256. * @method object CreateDataset(array $args) 创建数据集
  257. * @method object CreateDatasetBinding(array $args) 绑定存储桶与数据集
  258. * @method object CreateFileMetaIndex(array $args) 创建元数据索引
  259. * @method object DatasetFaceSearch(array $args) 人脸搜索
  260. * @method object DatasetSimpleQuery(array $args) 简单查询
  261. * @method object DeleteDataset(array $args) 删除数据集
  262. * @method object DeleteDatasetBinding(array $args) 解绑存储桶与数据集
  263. * @method object DeleteFileMetaIndex(array $args) 删除元数据索引
  264. * @method object DescribeDataset(array $args) 查询数据集
  265. * @method object DescribeDatasetBinding(array $args) 查询数据集与存储桶的绑定关系
  266. * @method object DescribeDatasetBindings(array $args) 查询绑定关系列表
  267. * @method object DescribeDatasets(array $args) 列出数据集
  268. * @method object DescribeFileMetaIndex(array $args) 查询元数据索引
  269. * @method object SearchImage(array $args) 图像检索
  270. * @method object UpdateDataset(array $args) 更新数据集
  271. * @method object UpdateFileMetaIndex(array $args) 更新元数据索引
  272. * @method object ZipFilePreview(array $args) 压缩包预览同步请求
  273. * @method object GetHLSPlayKey(array $args) 获取hls播放密钥
  274. * @method object PostWatermarkJobs(array $args) 视频明水印-提交任务
  275. * @method object GeneratePlayList(array $args) 生成播放列表
  276. * @method object CreateWatermarkTemplate(array $args) 创建明水印模板
  277. * @see \Qcloud\Cos\Service::getService()
  278. */
  279. class Client extends GuzzleClient {
  280. const VERSION = '2.6.14';
  281. public $httpClient;
  282. private $api;
  283. private $desc;
  284. private $action;
  285. private $operation;
  286. private $signature;
  287. private $rawCosConfig;
  288. private $cosConfig = [
  289. 'scheme' => 'http',
  290. 'region' => null,
  291. 'credentials' => [
  292. 'appId' => null,
  293. 'secretId' => '',
  294. 'secretKey' => '',
  295. 'anonymous' => false,
  296. 'token' => null,
  297. ],
  298. 'timeout' => 3600,
  299. 'connect_timeout' => 3600,
  300. 'ip' => null,
  301. 'port' => null,
  302. 'endpoint' => null,
  303. 'domain' => null,
  304. 'proxy' => null,
  305. 'retry' => 6,
  306. 'userAgent' => 'cos-php-sdk-v5.' . Client::VERSION,
  307. 'pathStyle' => false,
  308. 'signHost' => true,
  309. 'allow_redirects' => false,
  310. 'allow_accelerate' => false,
  311. 'timezone' => 'PRC',
  312. 'locationWithScheme' => false,
  313. 'autoChange' => false,
  314. 'limit_flag' => false,
  315. 'isCheckRequestPath' => true,
  316. ];
  317. public function __construct(array $cosConfig) {
  318. $this->rawCosConfig = $cosConfig;
  319. $this->cosConfig = processCosConfig(array_replace_recursive($this->cosConfig, $cosConfig));
  320. global $globalCosConfig;
  321. $globalCosConfig = $this->cosConfig;
  322. // check config
  323. $this->inputCheck();
  324. $service = Service::getService();
  325. $handler = HandlerStack::create();
  326. $handler->push(Middleware::retry(function ($retries, $request, $response, $exception) use (&$retryCount) {
  327. $this->cosConfig['limit_flag'] = false;
  328. $retryCount = $retries;
  329. if ($retryCount >= $this->cosConfig['retry']) {
  330. return false;
  331. }
  332. if ($response) {
  333. if ($response->getStatusCode() >= 300 && !$response->hasHeader('x-cos-request-id')) {
  334. $this->cosConfig['limit_flag'] = true;
  335. return true;
  336. }
  337. if ($response->getStatusCode() >= 500 ) {
  338. return true;
  339. }
  340. } elseif ($exception) {
  341. if ($exception instanceof Exception\ServiceResponseException) {
  342. if ($exception->getStatusCode() >= 500) {
  343. $this->cosConfig['limit_flag'] = true;
  344. return true;
  345. }
  346. }
  347. if ($exception instanceof ConnectException) {
  348. return true;
  349. }
  350. }
  351. return false;
  352. }, $this->retryDelay()));
  353. $handler->push(Middleware::mapRequest(function (RequestInterface $request) use (&$retryCount) {
  354. // 获取域名
  355. $origin_host = $request->getUri()->getHost();
  356. // 匹配 *.cos.{Region}.myqcloud.com
  357. $pattern1 = '/\.cos\.[a-z0-9-]+\.myqcloud\.com$/';
  358. if ($retryCount > 2 && $this->cosConfig['autoChange'] && $this->cosConfig['limit_flag'] && preg_match($pattern1, $origin_host)) {
  359. $origin = $request->getUri();
  360. $host = str_replace("myqcloud.com", "tencentcos.cn", $origin->getHost());
  361. // 将 URI 转换为字符串,然后替换主机名
  362. $originUriString = (string) $origin;
  363. $originUriString = str_replace("myqcloud.com", "tencentcos.cn", $originUriString);
  364. $originUriString = str_replace($origin->getScheme() . "://", "", $originUriString);
  365. // 创建新的 URI 对象
  366. $uri = new Uri($originUriString);
  367. // 获取路径,并从路径中移除主机名
  368. $path = $uri->getPath();
  369. $path = str_replace($host, '', $path);
  370. // 使用新的路径创建新的 URI
  371. $uri = $uri->withPath($path);
  372. $uri = $uri->withHost($host)->withScheme($origin->getScheme());
  373. // 更新请求的 URI 和主机头
  374. $request = $request->withUri($uri)->withHeader('Host', $host);
  375. return $request;
  376. }
  377. return $request;
  378. }));
  379. $handler->push(Middleware::mapRequest(function (RequestInterface $request) {
  380. return $request->withHeader('User-Agent', $this->cosConfig['userAgent']);
  381. }));
  382. if ($this->cosConfig['anonymous'] != true) {
  383. $handler->push($this::handleSignature($this->cosConfig['secretId'], $this->cosConfig['secretKey'], $this->cosConfig));
  384. }
  385. if ($this->cosConfig['token'] != null) {
  386. $handler->push(Middleware::mapRequest(function (RequestInterface $request) {
  387. $request = $request->withHeader('x-ci-security-token', $this->cosConfig['token']);
  388. return $request->withHeader('x-cos-security-token', $this->cosConfig['token']);
  389. }));
  390. }
  391. $handler->push($this::handleErrors());
  392. $this->signature = new Signature($this->cosConfig['secretId'], $this->cosConfig['secretKey'], $this->cosConfig, $this->cosConfig['token']);
  393. $area = $this->cosConfig['allow_accelerate'] ? 'accelerate' : $this->cosConfig['region'];
  394. $this->httpClient = new HttpClient([
  395. 'base_uri' => "{$this->cosConfig['scheme']}://cos.{$area}.myqcloud.com/",
  396. 'timeout' => $this->cosConfig['timeout'],
  397. 'handler' => $handler,
  398. 'proxy' => $this->cosConfig['proxy'],
  399. 'allow_redirects' => $this->cosConfig['allow_redirects']
  400. ]);
  401. $this->desc = new Description($service);
  402. $this->api = (array) $this->desc->getOperations();
  403. parent::__construct($this->httpClient, $this->desc, [$this,
  404. 'commandToRequestTransformer'], [$this, 'responseToResultTransformer'],
  405. null);
  406. }
  407. public function inputCheck() {
  408. $message = null;
  409. //检查Region
  410. if (empty($this->cosConfig['region']) &&
  411. empty($this->cosConfig['domain']) &&
  412. empty($this->cosConfig['endpoint']) &&
  413. empty($this->cosConfig['ip']) &&
  414. !$this->cosConfig['allow_accelerate']) {
  415. $message = 'Region is empty';
  416. }
  417. //检查Secret
  418. if (empty($this->cosConfig['secretId']) || empty($this->cosConfig['secretKey'])) {
  419. $message = 'Secret is empty';
  420. }
  421. if ($message !== null) {
  422. $e = new Exception\CosException($message);
  423. $e->setExceptionCode('Invalid Argument');
  424. throw $e;
  425. }
  426. }
  427. public function retryDelay() {
  428. return function ($numberOfRetries) {
  429. return 1000 * $numberOfRetries;
  430. };
  431. }
  432. public function commandToRequestTransformer(CommandInterface $command)
  433. {
  434. $this->action = $command->GetName();
  435. $this->operation = $this->api[$this->action];
  436. $transformer = new CommandToRequestTransformer($this->cosConfig, $this->operation);
  437. $seri = new Serializer($this->desc);
  438. $request = $seri($command);
  439. $request = $transformer->bucketStyleTransformer($command, $request);
  440. $request = $transformer->uploadBodyTransformer($command, $request);
  441. $request = $transformer->metadataTransformer($command, $request);
  442. $request = $transformer->queryStringTransformer($command, $request);
  443. $request = $transformer->headerTransformer($command, $request);
  444. $request = $transformer->md5Transformer($command, $request);
  445. $request = $transformer->specialParamTransformer($command, $request);
  446. $request = $transformer->ciParamTransformer($command, $request);
  447. $request = $transformer->cosDomain2CiTransformer($command, $request);
  448. return $request;
  449. }
  450. public function responseToResultTransformer(ResponseInterface $response, RequestInterface $request, CommandInterface $command)
  451. {
  452. $transformer = new ResultTransformer($this->cosConfig, $this->operation);
  453. $transformer->writeDataToLocal($command, $request, $response);
  454. $deseri = new Deserializer($this->desc, true);
  455. $result = $deseri($response, $request, $command);
  456. $result = $transformer->metaDataTransformer($command, $response, $result);
  457. $result = $transformer->extraHeadersTransformer($command, $request, $result);
  458. $result = $transformer->selectContentTransformer($command, $result);
  459. $result = $transformer->ciContentInfoTransformer($command, $result);
  460. return $result;
  461. }
  462. public function __destruct() {
  463. }
  464. public function __call($method, array $args) {
  465. try {
  466. $rt = parent::__call(ucfirst($method), $args);
  467. return $rt;
  468. } catch (\Exception $e) {
  469. $previous = $e->getPrevious();
  470. if ($previous !== null) {
  471. throw $previous;
  472. } else {
  473. throw $e;
  474. }
  475. }
  476. }
  477. public function getApi() {
  478. return $this->api;
  479. }
  480. /**
  481. * Get the config of the cos client.
  482. *
  483. * @param array|string $option
  484. * @return mixed
  485. */
  486. public function getCosConfig($option = null)
  487. {
  488. return $option === null
  489. ? $this->cosConfig
  490. : (isset($this->cosConfig[$option]) ? $this->cosConfig[$option] : array());
  491. }
  492. public function setCosConfig($option, $value)
  493. {
  494. $this->cosConfig[$option] = $value;
  495. }
  496. private function createPresignedUrl(RequestInterface $request, $expires) {
  497. return $this->signature->createPresignedUrl($request, $expires);
  498. }
  499. public function getPresignedUrl($method, $args, $expires = "+30 minutes") {
  500. $command = $this->getCommand($method, $args);
  501. $request = $this->commandToRequestTransformer($command);
  502. return $this->createPresignedUrl($request, $expires);
  503. }
  504. public function getObjectUrl($bucket, $key, $expires = "+30 minutes", array $args = array()) {
  505. $command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key));
  506. $request = $this->commandToRequestTransformer($command);
  507. return $this->createPresignedUrl($request, $expires)->__toString();
  508. }
  509. public function getObjectUrlWithoutSign($bucket, $key, array $args = array()) {
  510. $command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key));
  511. $request = $this->commandToRequestTransformer($command);
  512. return $request->getUri()->__toString();
  513. }
  514. public function upload($bucket, $key, $body, $options = array()) {
  515. $body = Psr7\Utils::streamFor($body);
  516. $options['Retry'] = $this->cosConfig['retry'];
  517. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : MultipartUpload::DEFAULT_PART_SIZE;
  518. if ($body->getSize() < $options['PartSize']) {
  519. $rt = $this->putObject(array(
  520. 'Bucket' => $bucket,
  521. 'Key' => $key,
  522. 'Body' => $body,
  523. ) + $options);
  524. }
  525. else {
  526. $multipartUpload = new MultipartUpload($this, $body, array(
  527. 'Bucket' => $bucket,
  528. 'Key' => $key,
  529. ) + $options);
  530. $rt = $multipartUpload->performUploading();
  531. }
  532. return $rt;
  533. }
  534. public static function simplifyPath($path) {
  535. $names = explode("/", $path);
  536. $stack = array();
  537. foreach ($names as $name) {
  538. if ($name == "..") {
  539. if (!empty($stack)) {
  540. array_pop($stack);
  541. }
  542. } elseif ($name && $name != ".") {
  543. array_push($stack, $name);
  544. }
  545. }
  546. return "/" . implode("/", $stack);
  547. }
  548. public function download($bucket, $key, $saveAs, $options = array()) {
  549. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : RangeDownload::DEFAULT_PART_SIZE;
  550. $versionId = isset($options['VersionId']) ? $options['VersionId'] : '';
  551. if ($this->cosConfig['isCheckRequestPath'] && "/" == self::simplifyPath($key)) {
  552. $e = new Exception\CosException('Getobject Key is illegal');
  553. $e->setExceptionCode('404');
  554. throw $e;
  555. }
  556. $rt = $this->headObject(array(
  557. 'Bucket'=>$bucket,
  558. 'Key'=>$key,
  559. 'VersionId'=>$versionId,
  560. )
  561. );
  562. $contentLength = $rt['ContentLength'];
  563. $resumableJson = [
  564. 'LastModified' => $rt['LastModified'],
  565. 'ContentLength' => $rt['ContentLength'],
  566. 'ETag' => $rt['ETag'],
  567. 'Crc64ecma' => $rt['Crc64ecma']
  568. ];
  569. $options['ResumableJson'] = $resumableJson;
  570. if ($contentLength < $options['PartSize']) {
  571. $rt = $this->getObject(array(
  572. 'Bucket' => $bucket,
  573. 'Key' => $key,
  574. 'SaveAs' => $saveAs,
  575. ) + $options);
  576. } else {
  577. $rangeDownload = new RangeDownload($this, $contentLength, $saveAs, array(
  578. 'Bucket' => $bucket,
  579. 'Key' => $key,
  580. ) + $options);
  581. $rt = $rangeDownload->performDownloading();
  582. }
  583. return $rt;
  584. }
  585. public function resumeUpload($bucket, $key, $body, $uploadId, $options = array()) {
  586. $body = Psr7\Utils::streamFor($body);
  587. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : MultipartUpload::DEFAULT_PART_SIZE;
  588. $multipartUpload = new MultipartUpload($this, $body, array(
  589. 'Bucket' => $bucket,
  590. 'Key' => $key,
  591. 'UploadId' => $uploadId,
  592. ) + $options);
  593. $rt = $multipartUpload->resumeUploading();
  594. return $rt;
  595. }
  596. public function copy($bucket, $key, $copySource, $options = array()) {
  597. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : Copy::DEFAULT_PART_SIZE;
  598. // set copysource client
  599. $sourceConfig = $this->rawCosConfig;
  600. $sourceConfig['region'] = $copySource['Region'];
  601. $cosSourceClient = new Client($sourceConfig);
  602. $copySource['VersionId'] = isset($copySource['VersionId']) ? $copySource['VersionId'] : '';
  603. $rt = $cosSourceClient->headObject(
  604. array('Bucket'=>$copySource['Bucket'],
  605. 'Key'=>$copySource['Key'],
  606. 'VersionId'=>$copySource['VersionId'],
  607. )
  608. );
  609. $contentLength = $rt['ContentLength'];
  610. // sample copy
  611. if ($contentLength < $options['PartSize']) {
  612. $rt = $this->copyObject(array(
  613. 'Bucket' => $bucket,
  614. 'Key' => $key,
  615. 'CopySource' => "{$copySource['Bucket']}.cos.{$copySource['Region']}.myqcloud.com/". urlencode("{$copySource['Key']}")."?versionId={$copySource['VersionId']}",
  616. ) + $options
  617. );
  618. return $rt;
  619. }
  620. // multi part copy
  621. $copySource['ContentLength'] = $contentLength;
  622. $copy = new Copy($this, $copySource, array(
  623. 'Bucket' => $bucket,
  624. 'Key' => $key
  625. ) + $options
  626. );
  627. return $copy->copy();
  628. }
  629. public function doesBucketExist($bucket, array $options = array())
  630. {
  631. try {
  632. $this->HeadBucket(array(
  633. 'Bucket' => $bucket));
  634. return true;
  635. } catch (\Exception $e){
  636. return false;
  637. }
  638. }
  639. public function doesObjectExist($bucket, $key, array $options = array())
  640. {
  641. try {
  642. $this->HeadObject(array(
  643. 'Bucket' => $bucket,
  644. 'Key' => $key));
  645. return true;
  646. } catch (\Exception $e){
  647. return false;
  648. }
  649. }
  650. public static function explodeKey($key) {
  651. global $globalCosConfig;
  652. if ($globalCosConfig['isCheckRequestPath'] && "/" == self::simplifyPath($key)) {
  653. $e = new Exception\CosException('Getobject Key is illegal');
  654. $e->setExceptionCode('404');
  655. throw $e;
  656. }
  657. // Remove a leading slash if one is found
  658. $split_key = explode('/', $key && $key[0] == '/' ? substr($key, 1) : $key);
  659. // Remove empty element
  660. $split_key = array_filter($split_key, function($var) {
  661. return !($var == '' || $var == null);
  662. });
  663. $final_key = implode("/", $split_key);
  664. if (substr($key, -1) == '/') {
  665. $final_key = $final_key . '/';
  666. }
  667. return $final_key;
  668. }
  669. public static function handleSignature($secretId, $secretKey, $options) {
  670. return function (callable $handler) use ($secretId, $secretKey, $options) {
  671. return new SignatureMiddleware($handler, $secretId, $secretKey, $options);
  672. };
  673. }
  674. public static function handleErrors() {
  675. return function (callable $handler) {
  676. return new ExceptionMiddleware($handler);
  677. };
  678. }
  679. }