Jdoss.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. namespace crmeb\services\upload\storage;
  3. use Aws\Acm\Exception\AcmException;
  4. use Aws\S3\S3Client;
  5. use crmeb\exceptions\AdminException;
  6. use crmeb\exceptions\UploadException;
  7. use crmeb\services\upload\BaseUpload;
  8. use GuzzleHttp\Psr7\Stream;
  9. use think\exception\ValidateException;
  10. /**
  11. * 京东云COS文件上传
  12. * Class Jdoss
  13. * @package crmeb\services\upload\storage
  14. */
  15. class Jdoss extends BaseUpload
  16. {
  17. /**
  18. * 应用id
  19. * @var string
  20. */
  21. protected $appid;
  22. /**
  23. * accessKey
  24. * @var mixed
  25. */
  26. protected $accessKey;
  27. /**
  28. * secretKey
  29. * @var mixed
  30. */
  31. protected $secretKey;
  32. /**
  33. * 句柄
  34. * @var S3Client
  35. */
  36. protected $handle;
  37. /**
  38. * 空间域名 Domain
  39. * @var mixed
  40. */
  41. protected $uploadUrl;
  42. /**
  43. * 存储空间名称 公开空间
  44. * @var mixed
  45. */
  46. protected $storageName;
  47. /**
  48. * COS使用 所属地域
  49. * @var mixed|null
  50. */
  51. protected $storageRegion;
  52. /**
  53. * @var string
  54. */
  55. protected $cdn;
  56. /**
  57. * 水印位置
  58. * @var string[]
  59. */
  60. protected $position = [
  61. '1' => 'northwest',//:左上
  62. '2' => 'north',//:中上
  63. '3' => 'northeast',//:右上
  64. '4' => 'west',//:左中
  65. '5' => 'center',//:中部
  66. '6' => 'east',//:右中
  67. '7' => 'southwest',//:左下
  68. '8' => 'south',//:中下
  69. '9' => 'southeast',//:右下
  70. ];
  71. /**
  72. * 初始化
  73. * @param array $config
  74. * @return mixed|void
  75. */
  76. public function initialize(array $config)
  77. {
  78. parent::initialize($config);
  79. $this->accessKey = $config['accessKey'] ?? null;
  80. $this->secretKey = $config['secretKey'] ?? null;
  81. $this->uploadUrl = $this->checkUploadUrl($config['uploadUrl'] ?? '');
  82. $this->storageName = $config['storageName'] ?? null;
  83. $this->storageRegion = $config['storageRegion'] ?? null;
  84. $this->cdn = $config['cdn'] ?? null;
  85. $this->waterConfig['watermark_text_font'] = 'simfang仿宋.ttf';
  86. }
  87. /**
  88. * @return S3Client
  89. *
  90. * @date 2023/06/05
  91. * @author yyw
  92. */
  93. protected function app()
  94. {
  95. if (!$this->accessKey || !$this->secretKey) {
  96. throw new UploadException('请填写存储配置或者更换存储方式');
  97. }
  98. $this->handle = new S3Client([
  99. 'version' => 'latest',
  100. 'region' => $this->storageRegion,
  101. 'endpoint' => "http://s3.{$this->storageRegion}.jdcloud-oss.com",
  102. 'signature_version' => 'v4',
  103. 'use_path_style_endpoint' => true,
  104. 'credentials' => [
  105. 'key' => $this->accessKey,
  106. 'secret' => $this->secretKey,
  107. ],
  108. ]);
  109. return $this->handle;
  110. }
  111. public function move(string $file = 'file')
  112. {
  113. $fileHandle = app()->request->file($file);
  114. if (!$fileHandle) {
  115. return $this->setError('上传的文件不存在');
  116. }
  117. if ($this->validate) {
  118. if (!in_array($fileHandle->getOriginalExtension(), $this->validate['fileExt'])) {
  119. return $this->setError('不合法的文件后缀:'.$fileHandle->getOriginalExtension());
  120. }
  121. if (filesize($fileHandle) > $this->validate['filesize']) {
  122. return $this->setError('文件过大');
  123. }
  124. if (!in_array($fileHandle->getOriginalMime(), $this->validate['fileMime'])) {
  125. return $this->setError('不合法的文件类型:'.$fileHandle->getOriginalMime());
  126. }
  127. }
  128. $key = $this->saveFileName($fileHandle->getRealPath(), $fileHandle->getOriginalExtension());
  129. $key = $this->getUploadPath($key);
  130. try {
  131. $uploadInfo = $this->app()->putObject([
  132. 'Bucket' => $this->storageName,
  133. 'Key' => $key,
  134. 'SourceFile' => $fileHandle->getRealPath()
  135. ]);
  136. if (!isset($uploadInfo['ObjectURL'])) {
  137. return $this->setError('Upload failure');
  138. }
  139. $this->fileInfo->uploadInfo = $uploadInfo;
  140. $this->fileInfo->realName = isset($fileHandle) ? $fileHandle->getOriginalName() : $key;
  141. $this->fileInfo->filePath = ($this->cdn ?: $this->uploadUrl) . '/' . $key;
  142. $this->fileInfo->fileName = $key;
  143. // $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  144. // $this->authThumb && $this->thumb($this->fileInfo->filePath);
  145. return $this->fileInfo;
  146. } catch (\Throwable $e) {
  147. return $this->setError($e->getMessage());
  148. }
  149. }
  150. public function stream($fileContent, string $key = null)
  151. {
  152. try {
  153. if (!$key) {
  154. $key = $this->saveFileName();
  155. }
  156. $key = $this->getUploadPath($key);
  157. if (is_resource($fileContent)) {
  158. $fileContent = new Stream($fileContent);
  159. }
  160. $uploadInfo = $this->app()->putObject([
  161. 'Bucket' => $this->storageName,
  162. 'Key' => $key,
  163. 'Body' => $fileContent
  164. ]);
  165. $uploadInfo = $uploadInfo->toArray();
  166. if (isset($uploadInfo['@metadata']['statusCode']) && $uploadInfo['@metadata']['statusCode'] !== 200) {
  167. return $this->setError('Upload failure');
  168. }
  169. $this->fileInfo->uploadInfo = $uploadInfo;
  170. $this->fileInfo->realName = $key;
  171. $this->fileInfo->filePath = ($this->cdn ?: $this->uploadUrl) . '/' . $key;
  172. $this->fileInfo->fileName = $key;
  173. $this->fileInfo->filePathWater = $this->water($this->fileInfo->filePath);
  174. $this->thumb($this->fileInfo->filePath);
  175. return $this->fileInfo;
  176. } catch (\Throwable $e) {
  177. return $this->setError($e->getMessage());
  178. }
  179. }
  180. public function delete(string $key)
  181. {
  182. try {
  183. return $this->app()->deleteObject([
  184. 'Bucket' => $this->storageName,
  185. 'Key' => $key
  186. ]);
  187. } catch (\Throwable $e) {
  188. return $this->setError($e->getMessage());
  189. }
  190. }
  191. public function listbuckets(string $region = '', bool $line = false, bool $shared = false)
  192. {
  193. try {
  194. $res = $this->app()->listBuckets(systemConfig('jd_storageRegion'));
  195. return $res ?? [];
  196. } catch (\Throwable $e) {
  197. return [];
  198. }
  199. }
  200. public function createBucket(string $name, string $region = '', string $acl = 'public-read')
  201. {
  202. $regionData = $this->getRegion();
  203. $regionData = array_column($regionData, 'value');
  204. if (!in_array($region, $regionData)) {
  205. return $this->setError('COS:无效的区域!');
  206. }
  207. $this->storageRegion = $region;
  208. $app = $this->app();
  209. //检测桶
  210. try {
  211. $app->headBucket([
  212. 'Bucket' => $name
  213. ]);
  214. } catch (\Throwable $e) {
  215. //桶不存在返回404
  216. if (strstr('404', $e->getMessage())) {
  217. return $this->setError('COS:' . $e->getMessage());
  218. }
  219. }
  220. //创建桶
  221. try {
  222. $res = $app->createBucket([
  223. 'Bucket' => $name,
  224. 'ACL' => $acl,
  225. ]);
  226. } catch (\Throwable $e) {
  227. if (strstr('[curl] 6', $e->getMessage())) {
  228. return $this->setError('COS:无效的区域!!');
  229. } else if (strstr('Access Denied.', $e->getMessage())) {
  230. return $this->setError('COS:无权访问');
  231. }
  232. return $this->setError('COS:' . $e->getMessage());
  233. }
  234. return $res;
  235. }
  236. public function getRegion()
  237. {
  238. return [
  239. [
  240. 'value' => 'cn-north-1',
  241. 'label' => '华北-北京'
  242. ],
  243. [
  244. 'value' => 'cn-east-1',
  245. 'label' => '华东-宿迁'
  246. ],
  247. [
  248. 'value' => 'cn-east-2',
  249. 'label' => '华东-上海'
  250. ],
  251. [
  252. 'value' => 'cn-south-1',
  253. 'label' => '华南-广州'
  254. ]
  255. ];
  256. }
  257. public function deleteBucket(string $name, string $region = '')
  258. {
  259. try {
  260. $this->storageRegion = $region;
  261. $this->app()->deleteBucket([
  262. 'Bucket' => $name, // REQUIRED
  263. ]);
  264. return true;
  265. } catch (AcmException $e) {
  266. return $this->setError($e->getMessage());
  267. }
  268. }
  269. public function getDomian(string $name, string $region = null)
  270. {
  271. try {
  272. $this->storageRegion = $region;
  273. $res = $this->app()->getBucketPolicy([
  274. 'Bucket' => $name
  275. ]);
  276. return $res['DomainName'] ?? [];
  277. } catch (\Throwable $e) {
  278. return $this->setError($e->getMessage());
  279. }
  280. }
  281. public function bindDomian(string $name, string $domain, string $region = null)
  282. {
  283. try {
  284. $this->storageRegion = $region;
  285. $this->app()->putBucketWebsite([
  286. 'Bucket' => $name,
  287. 'WebsiteConfiguration' => [
  288. 'RedirectAllRequestsTo' => [
  289. 'HostName' => $domain,
  290. 'Protocol' => 'http'
  291. ]
  292. ]
  293. ]);
  294. return true;
  295. } catch (\Throwable $e) {
  296. return $this->setError($e->getMessage());
  297. }
  298. }
  299. public function setBucketCors(string $name, string $region)
  300. {
  301. $this->storageRegion = $region;
  302. try {
  303. $this->app()->putBucketCors([
  304. 'Bucket' => $name, // REQUIRED
  305. 'CORSConfiguration' => [ // REQUIRED
  306. 'CORSRules' => [ // REQUIRED
  307. [
  308. 'AllowedHeaders' => ['*'],
  309. 'AllowedMethods' => ['POST', 'GET', 'PUT', 'DELETE', 'HEAD'], // REQUIRED
  310. 'AllowedOrigins' => ['*'], // REQUIRED
  311. 'ExposeHeaders' => ['Etag'],
  312. 'MaxAgeSeconds' => 0
  313. ],
  314. ],
  315. ]
  316. ]);
  317. return true;
  318. } catch (\Throwable $e) {
  319. return $this->setError($e->getMessage());
  320. }
  321. }
  322. /**
  323. * 获取OSS上传密钥
  324. * @return mixed|void
  325. */
  326. public function getTempKeys($key = '', $path = '', $contentType = '', $expires = '+10 minutes')
  327. {
  328. try {
  329. $app = $this->app();
  330. $cmd = $app->getCommand(
  331. 'PutObject', [
  332. 'Bucket' => $this->storageName,
  333. 'Key' => $key,
  334. // 'SourceFile' => $path,
  335. 'ContentType' => $contentType
  336. ]
  337. );
  338. $request = $app->createPresignedRequest($cmd, $expires, ['Scheme' => 'https']);
  339. return [
  340. 'upload_url' => (string)$request->getUri(),
  341. 'type' => 'JDOSS',
  342. 'url' => $this->uploadUrl . '/' . $key
  343. ];
  344. } catch (\Throwable $e) {
  345. return $this->setError($e->getMessage());
  346. }
  347. }
  348. /**
  349. * 缩略图
  350. * @param string $filePath
  351. * @param string $fileName
  352. * @param string $type
  353. * @return array|mixed
  354. */
  355. public function thumb(string $filePath = '', string $fileName = '', string $type = 'all')
  356. {
  357. $filePath = $this->getFilePath($filePath);
  358. $data = ['big' => $filePath, 'mid' => $filePath, 'small' => $filePath];
  359. $this->fileInfo->filePathBig = $this->fileInfo->filePathMid = $this->fileInfo->filePathSmall = $this->fileInfo->filePathWater = $filePath;
  360. if ($filePath) {
  361. $config = $this->thumbConfig;
  362. foreach ($this->thumb as $v) {
  363. if ($type == 'all' || $type == $v) {
  364. $height = 'thumb_' . $v . '_height';
  365. $width = 'thumb_' . $v . '_width';
  366. $key = 'filePath' . ucfirst($v);
  367. // if (systemConfig('image_thumbnail_status') && isset($config[$height]) && isset($config[$width])) {
  368. if (isset($config[$height]) && isset($config[$width])) {
  369. if (!strpos($filePath, '?x-oss-process')) {
  370. $this->fileInfo->$key = $filePath . '?x-oss-process=img/s/'.$config[$width].'/'
  371. .$config[$height];
  372. }
  373. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  374. $data[$v] = $this->fileInfo->$key;
  375. } else {
  376. $this->fileInfo->$key = $this->water($this->fileInfo->$key);
  377. $data[$v] = $this->fileInfo->$key;
  378. }
  379. }
  380. }
  381. }
  382. return $data;
  383. }
  384. /**
  385. * 水印
  386. * @param string $filePath
  387. * @return mixed|string
  388. */
  389. public function water(string $filePath = '')
  390. {
  391. $filePath = $this->getFilePath($filePath);
  392. $waterConfig = $this->waterConfig;
  393. $waterPath = $filePath;
  394. if ($waterConfig['image_watermark_status'] && $filePath) {
  395. if (strpos($filePath, '?x-oss-process') === false) {
  396. $filePath .= '&x-oss-process=img';
  397. }
  398. switch ($waterConfig['watermark_type']) {
  399. case 1://图片
  400. if (!$waterConfig['watermark_image']) {
  401. throw new AdminException(400722);
  402. }
  403. //京东入参格式:桶名:filename.jpg
  404. $waterFileName = substr(parse_url($waterConfig['watermark_image'],PHP_URL_PATH), 1);
  405. $waterImage = $this->storageName.':'.$waterFileName;
  406. $waterPath = $filePath .= '/wmi/wk/' . base64_encode($waterImage) . '/wd/' . $waterConfig['watermark_opacity'] . '/wp/' . ($waterConfig['watermark_position'] ?? '5') . '/wdx/' . $waterConfig['watermark_x'] . '/wdy/' . $waterConfig['watermark_y'];
  407. break;
  408. case 2://文字
  409. if (!$waterConfig['watermark_text']) {
  410. throw new AdminException(400723);
  411. }
  412. $waterConfig['watermark_text_color'] = str_replace('#', '', $waterConfig['watermark_text_color']);
  413. $waterPath = $filePath .= '/wmt/wt/' . base64_encode($waterConfig['watermark_text']) . '/wc/_' . $waterConfig['watermark_text_color'] . '/ws/' . $waterConfig['watermark_text_size'] . '/wp/' . ($waterConfig['watermark_position'] ?? 1) . '/wdx/' . $waterConfig['watermark_x'] . '/wdy/' . $waterConfig['watermark_y'];
  414. break;
  415. }
  416. }
  417. return $waterPath;
  418. }
  419. }