Tyoss.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. <?php
  2. namespace crmeb\services\upload\storage;
  3. use crmeb\exceptions\AdminException;
  4. use crmeb\services\upload\extend\obs\Client as TyClient;
  5. use crmeb\basic\BaseUpload;
  6. use DateTimeInterface;
  7. use GuzzleHttp\Psr7\Utils;
  8. use think\exception\ValidateException;
  9. class Tyoss extends BaseUpload
  10. {
  11. /**
  12. * accessKey
  13. * @var mixed
  14. */
  15. protected $accessKey;
  16. /**
  17. * secretKey
  18. * @var mixed
  19. */
  20. protected $secretKey;
  21. /**
  22. * 句柄
  23. * @var TyClient
  24. */
  25. protected $handle;
  26. /**
  27. * 空间域名 Domain
  28. * @var mixed
  29. */
  30. protected $uploadUrl;
  31. /**
  32. * 存储空间名称 公开空间
  33. * @var mixed
  34. */
  35. protected $storageName;
  36. /**
  37. * COS使用 所属地域
  38. * @var mixed|null
  39. */
  40. protected $storageRegion;
  41. /**
  42. * @var string
  43. */
  44. protected $cdn;
  45. /**
  46. * @param string $file
  47. * @param bool $isStream
  48. * @param string|null $fileContent
  49. * @return array|bool|mixed
  50. */
  51. public function move(string $file = 'file', bool $isStream = false, string $fileContent = null)
  52. {
  53. if (!$isStream) {
  54. $fileHandle = app()->request->file($file);
  55. if (!$fileHandle) {
  56. return $this->setError('上传的文件不存在');
  57. }
  58. if ($this->validate) {
  59. try {
  60. $error = [
  61. $file . '.filesize' => 'Upload filesize error',
  62. $file . '.fileExt' => 'Upload fileExt error',
  63. $file . '.fileMime' => 'Upload fileMine error'
  64. ];
  65. validate([$file => $this->validate], $error)->check([$file => $fileHandle]);
  66. } catch (ValidateException $e) {
  67. return $this->setError($e->getMessage());
  68. }
  69. }
  70. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  71. $body = fopen($fileHandle->getRealPath(), 'rb');
  72. $body = (string)Utils::streamFor($body);
  73. } else {
  74. $key = $file;
  75. $body = $fileContent;
  76. }
  77. $key = $this->getUploadPath($key);
  78. try {
  79. $uploadInfo = $this->app()->putObject($key, $body, 'application/octet-stream');
  80. $this->fileInfo->uploadInfo = $uploadInfo;
  81. $this->fileInfo->realName = $fileHandle->getOriginalName();
  82. $this->fileInfo->filePath = ($this->cdn ?: $this->uploadUrl) . '/' . $key;
  83. $this->fileInfo->fileName = $key;
  84. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  85. $this->authThumb && $this->thumb($this->fileInfo->filePath);
  86. return $this->fileInfo;
  87. } catch (\Throwable $e) {
  88. return $this->setError($e->getMessage());
  89. }
  90. }
  91. /**
  92. * 文件流上传
  93. * @param string $fileContent
  94. * @param string|null $key
  95. * @return bool|mixed
  96. */
  97. public function stream(string $fileContent, string $key = null)
  98. {
  99. if (!$key) {
  100. $key = $this->saveFileName();
  101. }
  102. return $this->move($key, true, $fileContent);
  103. }
  104. public function delete(string $filePath)
  105. {
  106. try {
  107. return $this->app()->deleteObject($filePath);
  108. } catch (\Exception $e) {
  109. return $this->setError($e->getMessage());
  110. }
  111. }
  112. /**
  113. * 初始化
  114. * @param array $config
  115. * @return mixed|void
  116. */
  117. public function initialize(array $config)
  118. {
  119. parent::initialize($config);
  120. $this->accessKey = $config['accessKey'] ?? null;
  121. $this->secretKey = $config['secretKey'] ?? null;
  122. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  123. $this->storageName = $config['storageName'] ?? null;
  124. $this->storageRegion = $config['storageRegion'] ?? null;
  125. $this->cdn = $config['cdn'] ?? null;
  126. $this->waterConfig['watermark_text_font'] = 'simfang仿宋.ttf';
  127. }
  128. /**
  129. * 实例化cos
  130. * @return TyClient
  131. */
  132. protected function app()
  133. {
  134. $this->handle = new TyClient([
  135. 'accessKey' => $this->accessKey,
  136. 'secretKey' => $this->secretKey,
  137. 'region' => $this->storageRegion ?: 'cn-qhxn1',
  138. 'bucket' => $this->storageName,
  139. 'uploadUrl' => $this->uploadUrl,
  140. 'type' => 'ty'
  141. ]);
  142. return $this->handle;
  143. }
  144. public function listbuckets(string $region = null, bool $line = false, bool $shared = false)
  145. {
  146. try {
  147. $res = $this->app()->listBuckets();
  148. return $res['Buckets']['Bucket'] ?? [];
  149. } catch (\Throwable $e) {
  150. return [];
  151. }
  152. }
  153. public function createBucket(string $name, string $region, string $acl = TyClient::DEFAULT_OBS_ACL)
  154. {
  155. $regionData = $this->getRegion();
  156. $regionData = array_column($regionData, 'value');
  157. if (!in_array($region, $regionData)) {
  158. return $this->setError('COS:无效的区域!');
  159. }
  160. $this->storageRegion = $region;
  161. $app = $this->app();
  162. //创建桶
  163. try {
  164. $app->createBucket($name, $region, $acl);
  165. $data = [
  166. 'Statement' => [
  167. 'Sid' => '公共读' . $name,
  168. 'Effect' => 'Allow',
  169. 'Principal' => [
  170. 'ID' => ['*']
  171. ],
  172. 'Action' => ['HeadBucket', 'GetBucketLocation', 'ListBucketVersions', 'GetObject', 'RestoreObject', 'GetObjectVersion'],
  173. 'Resource' => [$name, $name . '/*']
  174. ]
  175. ];
  176. $app->putPolicy($name, $region, $data);
  177. } catch (\Throwable $e) {
  178. return $this->setError('COS:' . $e->getMessage());
  179. }
  180. return true;
  181. }
  182. public function getRegion()
  183. {
  184. return [
  185. [
  186. 'value' => 'cn-gz1',
  187. 'label' => '贵州'
  188. ],
  189. [
  190. 'value' => 'cn-fz1',
  191. 'label' => '福州'
  192. ],
  193. [
  194. 'value' => 'cn-hz1',
  195. 'label' => '杭州'
  196. ],
  197. [
  198. 'value' => 'cn-sz1',
  199. 'label' => '深圳'
  200. ],
  201. [
  202. 'value' => 'cn-gdgz1',
  203. 'label' => '广州'
  204. ],
  205. [
  206. 'value' => 'cn-jssz1',
  207. 'label' => '苏州'
  208. ],
  209. [
  210. 'value' => 'cn-sh1',
  211. 'label' => '上海'
  212. ],
  213. [
  214. 'value' => 'cn-ahwh1',
  215. 'label' => '芜湖'
  216. ],
  217. [
  218. 'value' => 'cn-bj1',
  219. 'label' => '北京'
  220. ],
  221. [
  222. 'value' => 'cn-sccd1',
  223. 'label' => '成都'
  224. ],
  225. [
  226. 'value' => 'cn-hazz1',
  227. 'label' => '郑州'
  228. ],
  229. [
  230. 'value' => 'cn-hncs1',
  231. 'label' => '长沙'
  232. ],
  233. [
  234. 'value' => 'cn-gxnn1',
  235. 'label' => '南宁'
  236. ],
  237. [
  238. 'value' => 'cn-jxnc1',
  239. 'label' => '南昌'
  240. ],
  241. [
  242. 'value' => 'cn-sdqd1',
  243. 'label' => '青岛'
  244. ],
  245. [
  246. 'value' => 'cn-snxy1',
  247. 'label' => '咸阳'
  248. ],
  249. [
  250. 'value' => 'cn-xjcj1',
  251. 'label' => '新疆'
  252. ],
  253. [
  254. 'value' => 'cn-ynkm1',
  255. 'label' => '昆明'
  256. ],
  257. [
  258. 'value' => 'cn-hihk1',
  259. 'label' => '海口'
  260. ],
  261. [
  262. 'value' => 'cn-hbwh1',
  263. 'label' => '武汉'
  264. ],
  265. [
  266. 'value' => 'cn-cq1',
  267. 'label' => '重庆'
  268. ],
  269. [
  270. 'value' => 'cn-qhxn1',
  271. 'label' => '西宁'
  272. ],
  273. [
  274. 'value' => 'cn-gslz1',
  275. 'label' => '兰州'
  276. ],
  277. [
  278. 'value' => 'cn-nxyc1',
  279. 'label' => '银川'
  280. ],
  281. [
  282. 'value' => 'cn-sxty1',
  283. 'label' => '太原'
  284. ],
  285. [
  286. 'value' => 'cn-hesjz1',
  287. 'label' => '石家庄'
  288. ],
  289. [
  290. 'value' => 'cn-tj1',
  291. 'label' => '天津'
  292. ],
  293. [
  294. 'value' => 'cn-jlcc1',
  295. 'label' => '长春'
  296. ],
  297. [
  298. 'value' => 'cn-hlhrb1',
  299. 'label' => '哈尔滨'
  300. ],
  301. [
  302. 'value' => 'cn-nmhh1',
  303. 'label' => '内蒙古'
  304. ],
  305. [
  306. 'value' => 'cn-lnsy1',
  307. 'label' => '沈阳'
  308. ],
  309. [
  310. 'value' => 'cn-north1',
  311. 'label' => '华北'
  312. ]
  313. ];
  314. }
  315. public function deleteBucket(string $name, string $region = '')
  316. {
  317. try {
  318. $this->app()->deleteBucket($name, $region);
  319. return true;
  320. } catch (\Throwable $e) {
  321. return $this->setError($e->getMessage());
  322. }
  323. }
  324. public function getDomian($name, $region)
  325. {
  326. try {
  327. $res = $this->app()->getBucketDomain($name, $region);
  328. if ($res) {
  329. $domainRules = $res->toArray()['ListBucketCustomDomainsResult'];
  330. return array_column($domainRules, 'DomainName');
  331. } else {
  332. return [];
  333. }
  334. } catch (\Throwable $e) {
  335. }
  336. return [];
  337. }
  338. public function bindDomian(string $name, string $domain, string $region = null)
  339. {
  340. $parseDomin = parse_url($domain);
  341. try {
  342. $this->app()->putBucketDomain($name, $region, [
  343. 'domainname' => $parseDomin['host'],
  344. ]);
  345. return true;
  346. } catch (\Throwable $e) {
  347. return $this->setError($e->getMessage());
  348. }
  349. }
  350. public function setBucketCors(string $name, string $region)
  351. {
  352. try {
  353. $this->app()->putBucketCors($name, $region, [
  354. 'AllowedHeader' => ['*'],
  355. 'AllowedMethod' => ['PUT', 'GET', 'POST', 'DELETE', 'HEAD'],
  356. 'AllowedOrigin' => ['*'],
  357. 'ExposeHeader' => ['ETag'],
  358. 'MaxAgeSeconds' => 0
  359. ]);
  360. return true;
  361. } catch (\Throwable $e) {
  362. return $this->setError($e->getMessage());
  363. }
  364. }
  365. /**
  366. * @param string $callbackUrl
  367. * @param string $dir
  368. * @return array
  369. * @throws \Exception
  370. * @author 吴汐
  371. * @email 442384644@qq.com
  372. * @date 2023/06/19
  373. */
  374. public function getTempKeys($callbackUrl = '', $dir = '')
  375. {
  376. // TODO: Implement getTempKeys() method.
  377. $base64CallbackBody = base64_encode(json_encode([
  378. 'callbackUrl' => $callbackUrl,
  379. 'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
  380. 'callbackBodyType' => "application/x-www-form-urlencoded"
  381. ]));
  382. $policy = json_encode([
  383. 'expiration' => $this->gmtIso8601(time() + 300),
  384. 'conditions' =>
  385. [
  386. [0 => 'content-length-range', 1 => 0, 2 => 1048576000],
  387. ['bucket' => $this->storageName],
  388. [0 => 'starts-with', 1 => '$key', 2 => $dir],
  389. ]
  390. ]);
  391. $base64Policy = base64_encode($policy);
  392. $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->secretKey, true));
  393. return [
  394. 'accessid' => $this->accessKey,
  395. 'host' => $this->uploadUrl,
  396. 'policy' => $base64Policy,
  397. 'signature' => $signature,
  398. 'expire' => time() + 30,
  399. 'callback' => $base64CallbackBody,
  400. 'cdn' => $this->cdn,
  401. 'type' => 'OBS'
  402. ];
  403. }
  404. /**
  405. * 获取ISO时间格式
  406. * @param $time
  407. * @return string
  408. * @throws \Exception
  409. */
  410. protected function gmtIso8601($time): string
  411. {
  412. $dtStr = date("c", $time);
  413. $myDateTime = new \DateTime($dtStr);
  414. $expiration = $myDateTime->format(DateTimeInterface::ISO8601);
  415. $pos = strpos($expiration, '+');
  416. $expiration = substr($expiration, 0, $pos);
  417. return $expiration . "Z";
  418. }
  419. /**
  420. * 缩略图
  421. * @param string $filePath
  422. * @param string $fileName
  423. * @param string $type
  424. * @return array|mixed
  425. */
  426. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  427. {
  428. $filePath = $this->getFilePath($filePath);
  429. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  430. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  431. if ($filePath) {
  432. $config = $this->thumbConfig;
  433. foreach ($this->thumb as $v) {
  434. if ($type == 'all' || $type == $v) {
  435. $height = 'thumb_' . $v . '_height';
  436. $width = 'thumb_' . $v . '_width';
  437. $key = 'filePath' . ucfirst($v);
  438. if (sys_config('image_thumbnail_status', 1) && isset($config[$height]) && isset($config[$width]) && $config[$height] && $config[$width]) {
  439. $this->fileInfo->$key = $filePath . '?x-oss-process=image/resize,h_' . $config[$height] . ',w_' . $config[$width];
  440. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  441. $data[$v] = $this->fileInfo->$key;
  442. } else {
  443. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  444. $data[$v] = $this->fileInfo->$key;
  445. }
  446. }
  447. }
  448. }
  449. return $data;
  450. }
  451. /**
  452. * 水印
  453. * @param string $filePath
  454. * @return mixed|string
  455. */
  456. public function water(string $filePath = '')
  457. {
  458. $filePath = $this->getFilePath($filePath);
  459. $waterConfig = $this->waterConfig;
  460. $waterPath = $filePath;
  461. if ($waterConfig['image_watermark_status'] && $filePath) {
  462. if (strpos($filePath, '?x-oss-process') === false) {
  463. $filePath .= '?x-oss-process=image';
  464. }
  465. switch ($waterConfig['watermark_type']) {
  466. case 1://图片
  467. if (!$waterConfig['watermark_image']) {
  468. throw new AdminException('请先配置水印图片');
  469. }
  470. $waterPath = $filePath .= '/watermark,image_' . base64_encode($waterConfig['watermark_image']) . ',t_' . $waterConfig['watermark_opacity'] . ',g_' . ($this->position[$waterConfig['watermark_position']] ?? 'nw') . ',x_' . $waterConfig['watermark_x'] . ',y_' . $waterConfig['watermark_y'];
  471. break;
  472. case 2://文字
  473. if (!$waterConfig['watermark_text']) {
  474. throw new AdminException('请先配置水印文字');
  475. }
  476. $waterConfig['watermark_text_color'] = str_replace('#', '', $waterConfig['watermark_text_color']);
  477. $waterPath = $filePath .= '/watermark,text_' . base64_encode($waterConfig['watermark_text']) . ',color_' . $waterConfig['watermark_text_color'] . ',size_' . $waterConfig['watermark_text_size'] . ',g_' . ($this->position[$waterConfig['watermark_position']] ?? 'nw') . ',x_' . $waterConfig['watermark_x'] . ',y_' . $waterConfig['watermark_y'];
  478. break;
  479. }
  480. }
  481. return $waterPath;
  482. }
  483. }