Client.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. <?php
  2. namespace Qcloud\Cos;
  3. include("Common.php");
  4. use GuzzleHttp\Client as HttpClient;
  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. /**
  16. * @method object AbortMultipartUpload(array $args) 舍弃一个分块上传且删除已上传的分片块
  17. * @method object CreateBucket(array $args) 创建存储桶(Bucket)
  18. * @method object CompleteMultipartUpload(array $args) 完成整个分块上传
  19. * @method object CreateMultipartUpload(array $args) 初始化分块上传
  20. * @method object CopyObject(array $args) 复制对象
  21. * @method object DeleteBucket(array $args) 删除存储桶 (Bucket)
  22. * @method object DeleteBucketCors(array $args) 删除跨域访问配置信息
  23. * @method object DeleteBucketTagging(array $args) 删除存储桶标签信息
  24. * @method object DeleteBucketInventory(array $args) 删除存储桶标清单任务
  25. * @method object DeleteObject(array $args) 删除 COS 上单个对象
  26. * @method object DeleteObjects(array $args) 批量删除 COS 对象
  27. * @method object DeleteBucketWebsite(array $args) 删除存储桶(Bucket)的website
  28. * @method object DeleteBucketLifecycle(array $args) 删除存储桶(Bucket)的生命周期配置
  29. * @method object DeleteBucketReplication(array $args) 删除跨区域复制配置
  30. * @method object PutObjectTagging(array $args) 配置对象标签
  31. * @method object GetObjectTagging(array $args) 获取对象标签信息
  32. * @method object DeleteObjectTagging(array $args) 删除对象标签
  33. * @method object GetObject(array $args) 下载对象
  34. * @method object GetObjectAcl(array $args) 获取 COS 对象的访问权限信息(Access Control List, ACL)
  35. * @method object GetBucketAcl(array $args) 获取存储桶(Bucket)的访问权限信息(Access Control List, ACL)
  36. * @method object GetBucketCors(array $args) 查询存储桶(Bucket)跨域访问配置信息
  37. * @method object GetBucketDomain(array $args) 查询存储桶(Bucket)Domain配置信息
  38. * @method object GetBucketAccelerate(array $args) 查询存储桶(Bucket)Accelerate配置信息
  39. * @method object GetBucketWebsite(array $args) 查询存储桶(Bucket)Website配置信息
  40. * @method object GetBucketLifecycle(array $args) 查询存储桶(Bucket)的生命周期配置
  41. * @method object GetBucketVersioning(array $args) 获取存储桶(Bucket)版本控制信息
  42. * @method object GetBucketReplication(array $args) 获取存储桶(Bucket)跨区域复制配置信息
  43. * @method object GetBucketLocation(array $args) 获取存储桶(Bucket)所在的地域信息
  44. * @method object GetBucketNotification(array $args) 获取存储桶(Bucket)Notification信息
  45. * @method object GetBucketLogging(array $args) 获取存储桶(Bucket)日志信息
  46. * @method object GetBucketInventory(array $args) 获取存储桶(Bucket)清单信息
  47. * @method object GetBucketTagging(array $args) 获取存储桶(Bucket)标签信息
  48. * @method object UploadPart(array $args) 分块上传
  49. * @method object PutObject(array $args) 上传对象
  50. * @method object AppendObject(array $args) 追加对象
  51. * @method object PutObjectAcl(array $args) 设置 COS 对象的访问权限信息(Access Control List, ACL)
  52. * @method object PutBucketAcl(array $args) 设置存储桶(Bucket)的访问权限(Access Control List, ACL)
  53. * @method object PutBucketCors(array $args) 设置存储桶(Bucket)的跨域配置信息
  54. * @method object PutBucketDomain(array $args) 设置存储桶(Bucket)的Domain信息
  55. * @method object PutBucketLifecycle(array $args) 设置存储桶(Bucket)生命周期配置
  56. * @method object PutBucketVersioning(array $args) 存储桶(Bucket)版本控制
  57. * @method object PutBucketAccelerate(array $args) 配置存储桶(Bucket)Accelerate
  58. * @method object PutBucketWebsite(array $args) 配置存储桶(Bucket)website
  59. * @method object PutBucketReplication(array $args) 配置存储桶(Bucket)跨区域复制
  60. * @method object PutBucketNotification(array $args) 设置存储桶(Bucket)的回调设置
  61. * @method object PutBucketTagging(array $args) 配置存储桶(Bucket)标签
  62. * @method object PutBucketLogging(array $args) 开启存储桶(Bucket)日志服务
  63. * @method object PutBucketInventory(array $args) 配置存储桶(Bucket)清单
  64. * @method object RestoreObject(array $args) 回热归档对象
  65. * @method object ListParts(array $args) 查询存储桶(Bucket)中正在进行中的分块上传对象
  66. * @method object ListObjects(array $args) 查询存储桶(Bucket)下的部分或者全部对象
  67. * @method object ListBuckets 获取所属账户的所有存储空间列表
  68. * @method object ListObjectVersions(array $args) 获取多版本对象
  69. * @method object ListMultipartUploads(array $args) 获取已上传分块列表
  70. * @method object ListBucketInventoryConfigurations(array $args) 获取清单列表
  71. * @method object HeadObject(array $args) 获取对象的meta信息
  72. * @method object HeadBucket(array $args) 存储桶(Bucket)是否存在
  73. * @method object UploadPartCopy(array $args) 分块copy
  74. * @method object SelectObjectContent(array $args) 检索对象内容
  75. * @method object PutBucketIntelligentTiering(array $args) 存储桶(Bucket)开启智能分层
  76. * @method object GetBucketIntelligentTiering(array $args) 查询存储桶(Bucket)智能分层
  77. * @method object ImageInfo(array $args) 万象-获取图片基本信息
  78. * @method object ImageExif(array $args) 万象-获取图片EXIF信息
  79. * @method object ImageAve(array $args) 万象-获取图片主色调信息
  80. * @method object ImageProcess(array $args) 万象-云上数据处理
  81. * @method object Qrcode(array $args) 万象-二维码下载时识别
  82. * @method object QrcodeGenerate(array $args) 万象-二维码生成
  83. * @method object DetectLabel(array $args) 万象-图片标签
  84. * @method object PutBucketImageStyle(array $args) 万象-增加样式
  85. * @method object GetBucketImageStyle(array $args) 万象-查询样式
  86. * @method object DeleteBucketImageStyle(array $args) 万象-删除样式
  87. * @method object PutBucketGuetzli(array $args) 万象-开通Guetzli压缩
  88. * @method object GetBucketGuetzli(array $args) 万象-查询Guetzli状态
  89. * @method object DeleteBucketGuetzli(array $args) 万象-关闭Guetzli压缩
  90. * @method object GetObjectSensitiveContentRecognition(array $args) 图片审核
  91. * @method object DetectText(array $args) 文本审核
  92. * @method object GetSnapshot(array $args) 媒体截图
  93. * @method object PutBucketReferer(array $args) 添加防盗链
  94. * @method object GetBucketReferer(array $args) 获取防盗链规则
  95. * @method object GetMediaInfo(array $args) 获取媒体信息
  96. * @method object CreateMediaTranscodeJobs(array $args) 媒体转码
  97. * @method object CreateMediaJobs(array $args) 媒体任务
  98. * @method object DescribeMediaJob(array $args) 查询指定的媒体任务
  99. * @method object DescribeMediaJobs(array $args) 拉取拉取符合条件的媒体任务
  100. * @method object CreateMediaSnapshotJobs(array $args) 媒体截图
  101. * @method object CreateMediaConcatJobs(array $args) 媒体拼接
  102. * @method object DetectAudio(array $args) 音频审核
  103. * @method object GetDetectAudioResult(array $args) 主动获取音频审核结果
  104. * @method object GetDetectTextResult(array $args) 主动获取文本文件审核结果
  105. * @method object DetectVideo(array $args) 视频审核
  106. * @method object GetDetectVideoResult(array $args) 主动获取视频审核结果
  107. * @method object DetectDocument(array $args) 文档审核
  108. * @method object GetDetectDocumentResult(array $args) 主动获取文档审核结果
  109. * @method object CreateDocProcessJobs(array $args) 提交文档转码任务
  110. * @method object DescribeDocProcessQueues(array $args) 查询文档转码队列
  111. * @method object DescribeDocProcessJob(array $args) 查询文档转码任务
  112. * @method object GetDescribeDocProcessJobs(array $args) 拉取符合条件的文档转码任务
  113. * @method object DetectImage(array $args) 图片审核
  114. * @method object DetectImages(array $args) 图片审核-批量
  115. * @method object DetectVirus(array $args) 云查毒
  116. * @method object GetDetectVirusResult(array $args) 查询病毒检测任务结果
  117. * @method object GetDetectImageResult(array $args) 主动获取图片审核结果
  118. * @method object CreateMediaVoiceSeparateJobs(array $args) 提交人声分离任务
  119. * @method object DescribeMediaVoiceSeparateJob(array $args) 查询指定的人声分离任务
  120. * @method object DetectWebpage(array $args) 提交网页审核任务
  121. * @method object GetDetectWebpageResult(array $args) 查询网页审核任务结果
  122. * @method object DescribeMediaBuckets(array $args) 查询媒体处理开通状态
  123. * @method object GetPrivateM3U8(array $args) 获取私有 M3U8 ts 资源的下载授权
  124. * @method object DescribeMediaQueues(array $args) 搜索媒体处理队列
  125. * @method object UpdateMediaQueue(array $args) 更新媒体处理队列
  126. * @method object CreateMediaSmartCoverJobs(array $args) 提交智能封面任务
  127. * @method object CreateMediaVideoProcessJobs(array $args) 提交视频增强任务
  128. * @method object CreateMediaVideoMontageJobs(array $args) 提交精彩集锦任务
  129. * @method object CreateMediaAnimationJobs(array $args) 提交动图任务
  130. * @method object CreateMediaPicProcessJobs(array $args) 提交图片处理任务
  131. * @method object CreateMediaSegmentJobs(array $args) 提交转封装任务
  132. * @method object CreateMediaVideoTagJobs(array $args) 提交视频标签任务
  133. * @method object CreateMediaSuperResolutionJobs(array $args) 提交超分辨率任务
  134. * @method object CreateMediaSDRtoHDRJobs(array $args) 提交 SDR to HDR 任务
  135. * @method object CreateMediaDigitalWatermarkJobs(array $args) 嵌入数字水印任务(添加水印)
  136. * @method object CreateMediaExtractDigitalWatermarkJobs(array $args) 提取数字水印任务(提取水印)
  137. * @method object DetectLiveVideo(array $args) 直播流审核
  138. * @method object CancelLiveVideoAuditing(array $args) 取消直播流审核
  139. * @method object OpticalOcrRecognition(array $args) 通用文字识别
  140. * @method object TriggerWorkflow(array $args) 手动触发工作流
  141. * @method object GetWorkflowInstances(array $args) 获取工作流实例列表
  142. * @method object GetWorkflowInstance(array $args) 获取工作流实例详情
  143. * @method object CreateMediaSnapshotTemplate(array $args) 新增截图模板
  144. * @method object UpdateMediaSnapshotTemplate(array $args) 更新截图模板
  145. * @method object CreateMediaTranscodeTemplate(array $args) 新增转码模板
  146. * @method object UpdateMediaTranscodeTemplate(array $args) 更新转码模板
  147. * @method object CreateMediaHighSpeedHdTemplate(array $args) 新增极速高清转码模板
  148. * @method object UpdateMediaHighSpeedHdTemplate(array $args) 更新极速高清转码模板
  149. * @method object CreateMediaAnimationTemplate(array $args) 新增动图模板
  150. * @method object UpdateMediaAnimationTemplate(array $args) 更新动图模板
  151. * @method object CreateMediaConcatTemplate(array $args) 新增拼接模板
  152. * @method object UpdateMediaConcatTemplate(array $args) 更新拼接模板
  153. * @method object CreateMediaVideoProcessTemplate(array $args) 新增视频增强模板
  154. * @method object UpdateMediaVideoProcessTemplate(array $args) 更新视频增强模板
  155. * @method object CreateMediaVideoMontageTemplate(array $args) 新增精彩集锦模板
  156. * @method object UpdateMediaVideoMontageTemplate(array $args) 更新精彩集锦模板
  157. * @method object CreateMediaVoiceSeparateTemplate(array $args) 新增人声分离模板
  158. * @method object UpdateMediaVoiceSeparateTemplate(array $args) 更新人声分离模板
  159. * @method object CreateMediaSuperResolutionTemplate(array $args) 新增超分辨率模板
  160. * @method object UpdateMediaSuperResolutionTemplate(array $args) 更新超分辨率模板
  161. * @method object CreateMediaPicProcessTemplate(array $args) 新增图片处理模板
  162. * @method object UpdateMediaPicProcessTemplate(array $args) 更新图片处理模板
  163. * @method object CreateMediaWatermarkTemplate(array $args) 新增水印模板
  164. * @method object UpdateMediaWatermarkTemplate(array $args) 更新水印模板
  165. * @method object DescribeMediaTemplates(array $args) 查询模板列表
  166. * @method object DescribeWorkflow(array $args) 搜索工作流
  167. * @method object DeleteWorkflow(array $args) 删除工作流
  168. * @method object CreateInventoryTriggerJob(array $args) 触发批量存量任务
  169. * @method object DescribeInventoryTriggerJobs(array $args) 批量拉取存量任务
  170. * @method object DescribeInventoryTriggerJob(array $args) 查询存量任务
  171. * @method object CancelInventoryTriggerJob(array $args) 取消存量任务
  172. * @method object CreateMediaNoiseReductionJobs(array $args) 提交音频降噪任务
  173. * @method object ImageRepairProcess(array $args) 图片水印修复
  174. * @method object ImageDetectCarProcess(array $args) 车辆车牌检测
  175. * @method object ImageAssessQualityProcess(array $args) 图片质量评估
  176. * @method object ImageSearchOpen(array $args) 开通以图搜图
  177. * @method object ImageSearchAdd(array $args) 添加图库图片
  178. * @method object ImageSearch(array $args) 图片搜索接口
  179. * @method object ImageSearchDelete(array $args) 图片搜索接口
  180. * @method object BindCiService(array $args) 绑定数据万象服务
  181. * @method object GetCiService(array $args) 查询数据万象服务
  182. * @method object UnBindCiService(array $args) 解绑数据万象服务
  183. * @method object GetHotLink(array $args) 查询防盗链
  184. * @method object AddHotLink(array $args) 查询防盗链
  185. * @method object OpenOriginProtect(array $args) 开通原图保护
  186. * @method object GetOriginProtect(array $args) 查询原图保护状态
  187. * @method object CloseOriginProtect(array $args) 关闭原图保护
  188. * @method object ImageDetectFace(array $args) 人脸检测
  189. * @method object ImageFaceEffect(array $args) 人脸特效
  190. * @method object IDCardOCR(array $args) 身份证识别
  191. * @method object IDCardOCRByUpload(array $args) 身份证识别-上传时处理
  192. * @method object GetLiveCode(array $args) 获取数字验证码
  193. * @method object GetActionSequence(array $args) 获取动作顺序
  194. * @method object DescribeDocProcessBuckets(array $args) 查询文档预览开通状态
  195. * @method object UpdateDocProcessQueue(array $args) 更新文档转码队列
  196. * @method object CreateMediaQualityEstimateJobs(array $args) 提交视频质量评分任务
  197. * @method object CreateMediaStreamExtractJobs(array $args) 提交音视频流分离任务
  198. * @see \Qcloud\Cos\Service::getService()
  199. */
  200. class Client extends GuzzleClient {
  201. const VERSION = '2.6.0';
  202. public $httpClient;
  203. private $api;
  204. private $desc;
  205. private $action;
  206. private $operation;
  207. private $cosConfig;
  208. private $signature;
  209. private $rawCosConfig;
  210. public function __construct(array $cosConfig) {
  211. $this->rawCosConfig = $cosConfig;
  212. $this->cosConfig['schema'] = isset($cosConfig['schema']) ? $cosConfig['schema'] : 'http';
  213. $this->cosConfig['region'] = isset($cosConfig['region']) ? region_map($cosConfig['region']) : null;
  214. $this->cosConfig['appId'] = isset($cosConfig['credentials']['appId']) ? $cosConfig['credentials']['appId'] : null;
  215. $this->cosConfig['secretId'] = isset($cosConfig['credentials']['secretId']) ? trim($cosConfig['credentials']['secretId']) : '';
  216. $this->cosConfig['secretKey'] = isset($cosConfig['credentials']['secretKey']) ? trim($cosConfig['credentials']['secretKey']) : '';
  217. $this->cosConfig['anonymous'] = isset($cosConfig['credentials']['anonymous']) ? $cosConfig['credentials']['anonymous'] : false;
  218. $this->cosConfig['token'] = isset($cosConfig['credentials']['token']) ? trim($cosConfig['credentials']['token']) : null;
  219. $this->cosConfig['timeout'] = isset($cosConfig['timeout']) ? $cosConfig['timeout'] : 3600;
  220. $this->cosConfig['connect_timeout'] = isset($cosConfig['connect_timeout']) ? $cosConfig['connect_timeout'] : 3600;
  221. $this->cosConfig['ip'] = isset($cosConfig['ip']) ? $cosConfig['ip'] : null;
  222. $this->cosConfig['port'] = isset($cosConfig['port']) ? $cosConfig['port'] : null;
  223. $this->cosConfig['endpoint'] = isset($cosConfig['endpoint']) ? $cosConfig['endpoint'] : null;
  224. $this->cosConfig['domain'] = isset($cosConfig['domain']) ? $cosConfig['domain'] : null;
  225. $this->cosConfig['proxy'] = isset($cosConfig['proxy']) ? $cosConfig['proxy'] : null;
  226. $this->cosConfig['retry'] = isset($cosConfig['retry']) ? $cosConfig['retry'] : 1;
  227. $this->cosConfig['userAgent'] = isset($cosConfig['userAgent']) ? $cosConfig['userAgent'] : 'cos-php-sdk-v5.'. Client::VERSION;
  228. $this->cosConfig['pathStyle'] = isset($cosConfig['pathStyle']) ? $cosConfig['pathStyle'] : false;
  229. $this->cosConfig['signHost'] = isset($cosConfig['signHost']) ? $cosConfig['signHost'] : true;
  230. $this->cosConfig['allow_redirects'] = isset($cosConfig['allow_redirects']) ? $cosConfig['allow_redirects'] : false;
  231. $this->cosConfig['allow_accelerate'] = isset($cosConfig['allow_accelerate']) ? $cosConfig['allow_accelerate'] : false;
  232. // check config
  233. $this->inputCheck();
  234. $service = Service::getService();
  235. $handler = HandlerStack::create();
  236. $handler->push(Middleware::retry($this->retryDecide(), $this->retryDelay()));
  237. $handler->push(Middleware::mapRequest(function (RequestInterface $request) {
  238. return $request->withHeader('User-Agent', $this->cosConfig['userAgent']);
  239. }));
  240. if ($this->cosConfig['anonymous'] != true) {
  241. $handler->push($this::handleSignature($this->cosConfig['secretId'], $this->cosConfig['secretKey'], $this->cosConfig));
  242. }
  243. if ($this->cosConfig['token'] != null) {
  244. $handler->push(Middleware::mapRequest(function (RequestInterface $request) {
  245. return $request->withHeader('x-cos-security-token', $this->cosConfig['token']);
  246. }));
  247. }
  248. $handler->push($this::handleErrors());
  249. $this->signature = new Signature($this->cosConfig['secretId'], $this->cosConfig['secretKey'], $this->cosConfig, $this->cosConfig['token']);
  250. $area = $this->cosConfig['allow_accelerate'] ? 'accelerate' : $this->cosConfig['region'];
  251. $this->httpClient = new HttpClient([
  252. 'base_uri' => "{$this->cosConfig['schema']}://cos.{$area}.myqcloud.com/",
  253. 'timeout' => $this->cosConfig['timeout'],
  254. 'handler' => $handler,
  255. 'proxy' => $this->cosConfig['proxy'],
  256. 'allow_redirects' => $this->cosConfig['allow_redirects']
  257. ]);
  258. $this->desc = new Description($service);
  259. $this->api = (array) $this->desc->getOperations();
  260. parent::__construct($this->httpClient, $this->desc, [$this,
  261. 'commandToRequestTransformer'], [$this, 'responseToResultTransformer'],
  262. null);
  263. }
  264. public function inputCheck() {
  265. $message = null;
  266. //检查Region
  267. if (empty($this->cosConfig['region']) &&
  268. empty($this->cosConfig['domain']) &&
  269. empty($this->cosConfig['endpoint']) &&
  270. empty($this->cosConfig['ip']) &&
  271. !$this->cosConfig['allow_accelerate']) {
  272. $message = 'Region is empty';
  273. }
  274. //检查Secret
  275. if (empty($this->cosConfig['secretId']) || empty($this->cosConfig['secretKey'])) {
  276. $message = 'Secret is empty';
  277. }
  278. if ($message !== null) {
  279. $e = new Exception\CosException($message);
  280. $e->setExceptionCode('Invalid Argument');
  281. throw $e;
  282. }
  283. }
  284. public function retryDecide() {
  285. return function (
  286. $retries,
  287. RequestInterface $request,
  288. ResponseInterface $response = null,
  289. \Exception $exception = null
  290. ) {
  291. if ($retries >= $this->cosConfig['retry']) {
  292. return false;
  293. }
  294. if ($response != null && $response->getStatusCode() >= 400 ) {
  295. return true;
  296. }
  297. if ($exception instanceof Exception\ServiceResponseException) {
  298. if ($exception->getStatusCode() >= 400) {
  299. return true;
  300. }
  301. }
  302. if ($exception instanceof ConnectException) {
  303. return true;
  304. }
  305. return false;
  306. };
  307. }
  308. public function retryDelay() {
  309. return function ($numberOfRetries) {
  310. return 1000 * $numberOfRetries;
  311. };
  312. }
  313. public function commandToRequestTransformer(CommandInterface $command)
  314. {
  315. $this->action = $command->GetName();
  316. $this->operation = $this->api[$this->action];
  317. $transformer = new CommandToRequestTransformer($this->cosConfig, $this->operation);
  318. $seri = new Serializer($this->desc);
  319. $request = $seri($command);
  320. $request = $transformer->bucketStyleTransformer($command, $request);
  321. $request = $transformer->uploadBodyTransformer($command, $request);
  322. $request = $transformer->metadataTransformer($command, $request);
  323. $request = $transformer->queryStringTransformer($command, $request);
  324. $request = $transformer->headerTransformer($command, $request);
  325. $request = $transformer->md5Transformer($command, $request);
  326. $request = $transformer->specialParamTransformer($command, $request);
  327. $request = $transformer->ciParamTransformer($command, $request);
  328. $request = $transformer->cosDomain2CiTransformer($command, $request);
  329. return $request;
  330. }
  331. public function responseToResultTransformer(ResponseInterface $response, RequestInterface $request, CommandInterface $command)
  332. {
  333. $transformer = new ResultTransformer($this->cosConfig, $this->operation);
  334. $transformer->writeDataToLocal($command, $request, $response);
  335. $deseri = new Deserializer($this->desc, true);
  336. $result = $deseri($response, $request, $command);
  337. $result = $transformer->metaDataTransformer($command, $response, $result);
  338. $result = $transformer->extraHeadersTransformer($command, $request, $result);
  339. $result = $transformer->selectContentTransformer($command, $result);
  340. $result = $transformer->ciContentInfoTransformer($command, $result);
  341. return $result;
  342. }
  343. public function __destruct() {
  344. }
  345. public function __call($method, array $args) {
  346. try {
  347. $rt = parent::__call(ucfirst($method), $args);
  348. return $rt;
  349. } catch (\Exception $e) {
  350. $previous = $e->getPrevious();
  351. if ($previous !== null) {
  352. throw $previous;
  353. } else {
  354. throw $e;
  355. }
  356. }
  357. }
  358. public function getApi() {
  359. return $this->api;
  360. }
  361. private function getCosConfig() {
  362. return $this->cosConfig;
  363. }
  364. private function createPresignedUrl(RequestInterface $request, $expires) {
  365. return $this->signature->createPresignedUrl($request, $expires);
  366. }
  367. public function getPresignedUrl($method, $args, $expires = "+30 minutes") {
  368. $command = $this->getCommand($method, $args);
  369. $request = $this->commandToRequestTransformer($command);
  370. return $this->createPresignedUrl($request, $expires);
  371. }
  372. public function getObjectUrl($bucket, $key, $expires = "+30 minutes", array $args = array()) {
  373. $command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key));
  374. $request = $this->commandToRequestTransformer($command);
  375. return $this->createPresignedUrl($request, $expires)->__toString();
  376. }
  377. public function getObjectUrlWithoutSign($bucket, $key, array $args = array()) {
  378. $command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key));
  379. $request = $this->commandToRequestTransformer($command);
  380. return $request->getUri()-> __toString();
  381. }
  382. public function upload($bucket, $key, $body, $options = array()) {
  383. $body = Psr7\Utils::streamFor($body);
  384. $options['Retry'] = $this->cosConfig['retry'];
  385. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : MultipartUpload::DEFAULT_PART_SIZE;
  386. if ($body->getSize() < $options['PartSize']) {
  387. $rt = $this->putObject(array(
  388. 'Bucket' => $bucket,
  389. 'Key' => $key,
  390. 'Body' => $body,
  391. ) + $options);
  392. }
  393. else {
  394. $multipartUpload = new MultipartUpload($this, $body, array(
  395. 'Bucket' => $bucket,
  396. 'Key' => $key,
  397. ) + $options);
  398. $rt = $multipartUpload->performUploading();
  399. }
  400. return $rt;
  401. }
  402. public function download($bucket, $key, $saveAs, $options = array()) {
  403. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : RangeDownload::DEFAULT_PART_SIZE;
  404. $contentLength = 0;
  405. $versionId = isset($options['VersionId']) ? $options['VersionId'] : '';
  406. $rt = $this->headObject(array(
  407. 'Bucket'=>$bucket,
  408. 'Key'=>$key,
  409. 'VersionId'=>$versionId,
  410. )
  411. );
  412. $contentLength = $rt['ContentLength'];
  413. $resumableJson = [
  414. 'LastModified' => $rt['LastModified'],
  415. 'ContentLength' => $rt['ContentLength'],
  416. 'ETag' => $rt['ETag'],
  417. 'Crc64ecma' => $rt['Crc64ecma']
  418. ];
  419. $options['ResumableJson'] = $resumableJson;
  420. if ($contentLength < $options['PartSize']) {
  421. $rt = $this->getObject(array(
  422. 'Bucket' => $bucket,
  423. 'Key' => $key,
  424. 'SaveAs' => $saveAs,
  425. ) + $options);
  426. } else {
  427. $rangeDownload = new RangeDownload($this, $contentLength, $saveAs, array(
  428. 'Bucket' => $bucket,
  429. 'Key' => $key,
  430. ) + $options);
  431. $rt = $rangeDownload->performDownloading();
  432. }
  433. return $rt;
  434. }
  435. public function resumeUpload($bucket, $key, $body, $uploadId, $options = array()) {
  436. $body = Psr7\Utils::streamFor($body);
  437. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : MultipartUpload::DEFAULT_PART_SIZE;
  438. $multipartUpload = new MultipartUpload($this, $body, array(
  439. 'Bucket' => $bucket,
  440. 'Key' => $key,
  441. 'UploadId' => $uploadId,
  442. ) + $options);
  443. $rt = $multipartUpload->resumeUploading();
  444. return $rt;
  445. }
  446. public function copy($bucket, $key, $copySource, $options = array()) {
  447. $options['PartSize'] = isset($options['PartSize']) ? $options['PartSize'] : Copy::DEFAULT_PART_SIZE;
  448. // set copysource client
  449. $sourceConfig = $this->rawCosConfig;
  450. $sourceConfig['region'] = $copySource['Region'];
  451. $cosSourceClient = new Client($sourceConfig);
  452. $copySource['VersionId'] = isset($copySource['VersionId']) ? $copySource['VersionId'] : '';
  453. $rt = $cosSourceClient->headObject(
  454. array('Bucket'=>$copySource['Bucket'],
  455. 'Key'=>$copySource['Key'],
  456. 'VersionId'=>$copySource['VersionId'],
  457. )
  458. );
  459. $contentLength = $rt['ContentLength'];
  460. // sample copy
  461. if ($contentLength < $options['PartSize']) {
  462. $rt = $this->copyObject(array(
  463. 'Bucket' => $bucket,
  464. 'Key' => $key,
  465. 'CopySource' => "{$copySource['Bucket']}.cos.{$copySource['Region']}.myqcloud.com/". urlencode("{$copySource['Key']}")."?versionId={$copySource['VersionId']}",
  466. ) + $options
  467. );
  468. return $rt;
  469. }
  470. // multi part copy
  471. $copySource['ContentLength'] = $contentLength;
  472. $copy = new Copy($this, $copySource, array(
  473. 'Bucket' => $bucket,
  474. 'Key' => $key
  475. ) + $options
  476. );
  477. return $copy->copy();
  478. }
  479. public function doesBucketExist($bucket, array $options = array())
  480. {
  481. try {
  482. $this->HeadBucket(array(
  483. 'Bucket' => $bucket));
  484. return true;
  485. } catch (\Exception $e){
  486. return false;
  487. }
  488. }
  489. public function doesObjectExist($bucket, $key, array $options = array())
  490. {
  491. try {
  492. $this->HeadObject(array(
  493. 'Bucket' => $bucket,
  494. 'Key' => $key));
  495. return true;
  496. } catch (\Exception $e){
  497. return false;
  498. }
  499. }
  500. public static function explodeKey($key) {
  501. // Remove a leading slash if one is found
  502. $split_key = explode('/', $key && $key[0] == '/' ? substr($key, 1) : $key);
  503. // Remove empty element
  504. $split_key = array_filter($split_key, function($var) {
  505. return !($var == '' || $var == null);
  506. });
  507. $final_key = implode("/", $split_key);
  508. if (substr($key, -1) == '/') {
  509. $final_key = $final_key . '/';
  510. }
  511. return $final_key;
  512. }
  513. public static function handleSignature($secretId, $secretKey, $options) {
  514. return function (callable $handler) use ($secretId, $secretKey, $options) {
  515. return new SignatureMiddleware($handler, $secretId, $secretKey, $options);
  516. };
  517. }
  518. public static function handleErrors() {
  519. return function (callable $handler) {
  520. return new ExceptionMiddleware($handler);
  521. };
  522. }
  523. }