Tyoss.php 16 KB

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