SystemStorageServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\system\config;
  12. use app\dao\system\config\SystemStorageDao;
  13. use app\services\BaseServices;
  14. use crmeb\services\FormBuilder;
  15. use crmeb\services\SystemConfigService;
  16. use crmeb\services\UploadService;
  17. use crmeb\traits\ServicesTrait;
  18. use think\exception\ValidateException;
  19. /**
  20. * Class SystemStorageServices
  21. * @package app\services\system\config
  22. * @mixin SystemStorageDao
  23. */
  24. class SystemStorageServices extends BaseServices
  25. {
  26. use ServicesTrait;
  27. /**
  28. * SystemStorageServices constructor.
  29. * @param SystemStorageDao $dao
  30. */
  31. public function __construct(SystemStorageDao $dao)
  32. {
  33. $this->dao = $dao;
  34. }
  35. /**
  36. * @param array $where
  37. * @return array
  38. */
  39. public function getList(array $where)
  40. {
  41. [$page, $limit] = $this->getPageValue();
  42. $config = $this->getStorageConfig((int)$where['type']);
  43. $where['access_key'] = $config['accessKey'];
  44. $list = $this->dao->getStorageList($where, ['*'], $page, $limit);
  45. foreach ($list as &$item) {
  46. $item['_add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  47. $item['_update_time'] = date('Y-m-d H:i:s', $item['update_time']);
  48. $service = UploadService::init($item['type']);
  49. $region = $service->getRegion();
  50. foreach ($region as $value) {
  51. if (strstr($item['region'], $value['value'])) {
  52. $item['_region'] = $value['label'];
  53. }
  54. }
  55. if (!$item['cname']) {
  56. $item['cname'] = str_replace(['http://', 'https://'], '', $item['domain']);
  57. }
  58. }
  59. $count = $this->dao->getCount($where);
  60. return compact('list', 'count');
  61. }
  62. /**
  63. * @param int $type
  64. * @return array
  65. * @throws \FormBuilder\Exception\FormBuilderException
  66. */
  67. public function getFormStorage(int $type)
  68. {
  69. $upload = UploadService::init($type);
  70. $config = $this->getStorageConfig($type);
  71. $ruleConfig = [];
  72. if (!$config['accessKey']) {
  73. $ruleConfig = [
  74. FormBuilder::input('accessKey', 'AccessKeyId:', $config['accessKey'] ?? '')->required(),
  75. FormBuilder::input('secretKey', 'AccessKeySecret:', $config['secretKey'] ?? '')->required(),
  76. ];
  77. }
  78. if ($type === 4 && isset($config['appid']) && !$config['appid']) {
  79. $ruleConfig[] = FormBuilder::input('appid', 'APPID', $config['appid'] ?? '')->required();
  80. }
  81. $rule = [
  82. FormBuilder::input('name', '空间名称')->required(),
  83. FormBuilder::select('region', '空间区域')->options($upload->getRegion())->required(),
  84. FormBuilder::radio('acl', '读写权限', 'public-read')->options([
  85. ['label' => '公共读(推荐)', 'value' => 'public-read'],
  86. ['label' => '公共读写', 'value' => 'public-read-write'],
  87. ])->required(),
  88. ];
  89. $rule = array_merge($ruleConfig, $rule);
  90. return create_form('添加云空间', $rule, '/setting/config/storage/' . $type);
  91. }
  92. /**
  93. * @param int $type
  94. * @return array
  95. */
  96. public function getStorageConfig(int $type)
  97. {
  98. $config = [
  99. 'accessKey' => '',
  100. 'secretKey' => ''
  101. ];
  102. switch ($type) {
  103. case 2://七牛
  104. $config = [
  105. 'accessKey' => sys_config('qiniu_accessKey', ''),
  106. 'secretKey' => sys_config('qiniu_secretKey', ''),
  107. ];
  108. break;
  109. case 3:// oss 阿里云
  110. $config = [
  111. 'accessKey' => sys_config('accessKey', ''),
  112. 'secretKey' => sys_config('secretKey', ''),
  113. ];
  114. break;
  115. case 4:// cos 腾讯云
  116. $config = [
  117. 'accessKey' => sys_config('tengxun_accessKey', ''),
  118. 'secretKey' => sys_config('tengxun_secretKey', ''),
  119. 'appid' => sys_config('tengxun_appid', ''),
  120. ];
  121. break;
  122. case 5:// cos 京东云
  123. $config = [
  124. 'accessKey' => sys_config('jd_accessKey', ''),
  125. 'secretKey' => sys_config('jd_secretKey', ''),
  126. 'storageRegion' => sys_config('jd_storage_region'),
  127. ];
  128. break;
  129. case 6:// cos 华为云
  130. $config = [
  131. 'accessKey' => sys_config('hw_accessKey', ''),
  132. 'secretKey' => sys_config('hw_secretKey', ''),
  133. ];
  134. break;
  135. case 7:// cos 天翼云
  136. $config = [
  137. 'accessKey' => sys_config('ty_accessKey', ''),
  138. 'secretKey' => sys_config('ty_secretKey', ''),
  139. ];
  140. break;
  141. }
  142. return $config;
  143. }
  144. /**
  145. * @param int $type
  146. * @return array
  147. * @throws \FormBuilder\Exception\FormBuilderException
  148. */
  149. public function getFormStorageConfig(int $type)
  150. {
  151. $config = $this->getStorageConfig($type);
  152. $rule = [
  153. FormBuilder::hidden('type', $type),
  154. FormBuilder::input('accessKey', 'AccessKeyId:', $config['accessKey'] ?? '')->required(),
  155. FormBuilder::input('secretKey', 'AccessKeySecret:', $config['secretKey'] ?? '')->required(),
  156. ];
  157. if ($type === 4) {
  158. $rule[] = FormBuilder::input('appid', 'APPID', $config['appid'] ?? '')->required();
  159. }
  160. if ($type === 5) {
  161. $rule[] = FormBuilder::input('storageRegion', 'Region', $config['storageRegion'] ?? '')->required();
  162. }
  163. return create_form('配置信息', $rule, '/setting/config/storage/config');
  164. }
  165. /**
  166. * 删除空间
  167. * @param int $id
  168. * @return bool
  169. * @throws \think\db\exception\DataNotFoundException
  170. * @throws \think\db\exception\DbException
  171. * @throws \think\db\exception\ModelNotFoundException
  172. */
  173. public function deleteStorage(int $id)
  174. {
  175. $storageInfo = $this->dao->get(['is_delete' => 0, 'id' => $id]);
  176. if (!$storageInfo) {
  177. throw new ValidateException('删除的云存储不存在');
  178. }
  179. if ($storageInfo->status) {
  180. throw new ValidateException('云存储正在使用中,需要启动其他空间才能删除');
  181. }
  182. try {
  183. $upload = UploadService::init($storageInfo->type);
  184. $res = $upload->deleteBucket($storageInfo->name, $storageInfo->region);
  185. if (false === $res) {
  186. throw new ValidateException($upload->getError());
  187. }
  188. } catch (\Throwable $e) {
  189. throw new ValidateException($e->getMessage());
  190. }
  191. $storageInfo->is_delete = 1;
  192. $storageInfo->save();
  193. return true;
  194. }
  195. public function saveConfig(int $type, array $data)
  196. {
  197. //保存配置信息
  198. if (1 !== $type) {
  199. $accessKey = $secretKey = $appid = $storageRegion = '';
  200. if (isset($data['accessKey']) && isset($data['secretKey']) && $data['accessKey'] && $data['secretKey']) {
  201. $accessKey = $data['accessKey'];
  202. $secretKey = $data['secretKey'];
  203. unset($data['accessKey'], $data['secretKey']);
  204. }
  205. if (isset($data['appid']) && $data['appid']) {
  206. $appid = $data['appid'];
  207. unset($data['appid']);
  208. }
  209. if (isset($data['storageRegion']) && $data['storageRegion']) {
  210. $storageRegion = $data['storageRegion'];
  211. unset($data['storageRegion']);
  212. }
  213. if (!$accessKey || !$secretKey) {
  214. return true;
  215. }
  216. /** @var SystemConfigServices $make */
  217. $make = app()->make(SystemConfigServices::class);
  218. switch ($type) {
  219. case 2://七牛
  220. $make->update('qiniu_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  221. $make->update('qiniu_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  222. break;
  223. case 3:// oss 阿里云
  224. $make->update('accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  225. $make->update('secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  226. break;
  227. case 4:// cos 腾讯云
  228. $make->update('tengxun_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  229. $make->update('tengxun_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  230. $make->update('tengxun_appid', ['value' => json_encode($appid)], 'menu_name');
  231. break;
  232. case 5:// oss 京东云
  233. $make->update('jd_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  234. $make->update('jd_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  235. $make->update('jd_storage_region', ['value' => json_encode($storageRegion)], 'menu_name');
  236. break;
  237. case 6:// oss 华为云
  238. $make->update('hw_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  239. $make->update('hw_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  240. break;
  241. case 7:// oss 天翼云
  242. $make->update('ty_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  243. $make->update('ty_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  244. break;
  245. }
  246. \crmeb\services\CacheService::redisHandler(SystemConfigService::getTag())->clear();
  247. }
  248. }
  249. /**
  250. * 保存云存储
  251. * @param int $type
  252. * @param array $data
  253. * @return mixed
  254. */
  255. public function saveStorage(int $type, array $data)
  256. {
  257. //保存配置信息
  258. $this->saveConfig($type, $data);
  259. $name = $data['name'];
  260. switch ($type) {
  261. case 3://阿里云oss
  262. $data['region'] = $this->getReagionHost($type, $data['region']);
  263. break;
  264. case 4://腾讯云cos
  265. $name = $data['name'] . '-' . sys_config('tengxun_appid');
  266. break;
  267. }
  268. if ($this->dao->count(['type' => $type, 'name' => $name])) {
  269. throw new ValidateException('云空间名称不能重复');
  270. }
  271. //保存云存储
  272. $data['type'] = $type;
  273. $upload = UploadService::init($type);
  274. $res = $upload->createBucket($data['name'], $data['region'], $data['acl']);
  275. if (false === $res) {
  276. throw new ValidateException($upload->getError());
  277. }
  278. $data['domain'] = $this->getDomain($type, $data['name'], $data['region'], sys_config('tengxun_appid'));
  279. if (2 === $type) {
  280. $domianList = $upload->getDomian($data['name']);
  281. $data['domain'] = $domianList[count($domianList) - 1];
  282. } else {
  283. $data['cname'] = $data['domain'];
  284. }
  285. $data['name'] = $name;
  286. $data['add_time'] = time();
  287. $data['update_time'] = time();
  288. $config = $this->getStorageConfig($type);
  289. $data['access_key'] = $config['accessKey'];
  290. return $this->dao->save($data);
  291. }
  292. /**
  293. * 同步云储存桶
  294. * @param int $type
  295. * @return bool
  296. */
  297. public function synchronization(int $type)
  298. {
  299. $data = [];
  300. switch ($type) {
  301. case 2://七牛
  302. $config = $this->getStorageConfig($type);
  303. $upload = UploadService::init($type);
  304. $list = $upload->listbuckets();
  305. if (false === $list) {
  306. throw new ValidateException('同步失败,失败原因:' . $upload->getError());
  307. }
  308. foreach ($list as $item) {
  309. if (!$this->dao->count(['name' => $item['id'], 'is_delete' => 0, 'access_key' => $config['accessKey']])) {
  310. $data[] = [
  311. 'type' => $type,
  312. 'access_key' => $config['accessKey'],
  313. 'name' => $item['id'],
  314. 'region' => $item['region'],
  315. 'acl' => $item['private'] == 0 ? 'public-read' : 'private',
  316. 'status' => 0,
  317. 'is_delete' => 0,
  318. 'add_time' => time(),
  319. 'update_time' => time()
  320. ];
  321. }
  322. }
  323. break;
  324. case 3:// oss 阿里云
  325. $upload = UploadService::init($type);
  326. $list = $upload->listbuckets();
  327. $config = $this->getStorageConfig($type);
  328. foreach ($list as $item) {
  329. if (!$this->dao->count(['name' => $item['name'], 'is_delete' => 0, 'access_key' => $config['accessKey']])) {
  330. $region = $this->getReagionHost($type, $item['location']);
  331. $data[] = [
  332. 'type' => $type,
  333. 'access_key' => $config['accessKey'],
  334. 'name' => $item['name'],
  335. 'region' => $region,
  336. 'acl' => 'public-read',
  337. 'domain' => $this->getDomain($type, $item['name'], $region),
  338. 'status' => 0,
  339. 'is_delete' => 0,
  340. 'add_time' => strtotime($item['createTime']),
  341. 'update_time' => time()
  342. ];
  343. }
  344. }
  345. break;
  346. case 4:// cos 腾讯云
  347. $upload = UploadService::init($type);
  348. $list = $upload->listbuckets();
  349. $config = $this->getStorageConfig($type);
  350. foreach ($list as $item) {
  351. if (($id = $this->dao->value(['name' => $item['Name'], 'is_delete' => 0, 'access_key' => $config['accessKey']], 'id'))) {
  352. $this->dao->update($id, [
  353. 'update_time' => time(),
  354. 'region' => $item['Location'],
  355. 'name' => $item['Name'],
  356. 'domain' => sys_config('tengxun_appid') ? $this->getDomain($type, $item['Name'], $item['Location']) : '',
  357. ]);
  358. } else {
  359. $data[] = [
  360. 'type' => $type,
  361. 'access_key' => $config['accessKey'],
  362. 'name' => $item['Name'],
  363. 'region' => $item['Location'],
  364. 'acl' => 'public-read',
  365. 'status' => 0,
  366. 'domain' => sys_config('tengxun_appid') ? $this->getDomain($type, $item['Name'], $item['Location']) : '',
  367. 'is_delete' => 0,
  368. 'add_time' => strtotime($item['CreationDate']),
  369. 'update_time' => time()
  370. ];
  371. }
  372. }
  373. break;
  374. case 5:// cos 京东云
  375. $upload = UploadService::init($type);
  376. $list = $upload->listbuckets();
  377. $config = $this->getStorageConfig($type);
  378. $location = $config['storageRegion'] ?? 'cn-north-1';
  379. foreach ($list as $item) {
  380. if (!$this->dao->count(['name' => $item['Name'], 'access_key' => $config['accessKey']])) {
  381. $data[] = [
  382. 'type' => $type,
  383. 'access_key' => $config['accessKey'],
  384. 'name' => $item['Name'],
  385. 'region' => $location,
  386. 'acl' => 'public-read',
  387. 'status' => 0,
  388. 'domain' => $this->getDomain($type, $item['Name'], $location),
  389. 'is_delete' => 0,
  390. 'add_time' => time(),
  391. 'update_time' => time()
  392. ];
  393. }
  394. }
  395. break;
  396. case 6:// cos 华为云
  397. case 7:// cos 天翼云
  398. $upload = UploadService::init($type);
  399. $list = $upload->listbuckets();
  400. if (!empty($list['Name'])) {
  401. $newList = $list;
  402. $list = [];
  403. $list[] = $newList;
  404. }
  405. $config = $this->getStorageConfig($type);
  406. foreach ($list as $item) {
  407. if (!$this->dao->count(['name' => $item['Name'], 'access_key' => $config['accessKey']])) {
  408. $data[] = [
  409. 'type' => $type,
  410. 'access_key' => $config['accessKey'],
  411. 'name' => $item['Name'],
  412. 'region' => $item['Location'],
  413. 'acl' => 'public-read',
  414. 'status' => 0,
  415. 'domain' => $this->getDomain($type, $item['Name'], $item['Location']),
  416. 'is_delete' => 0,
  417. 'add_time' => strtotime($item['CreationDate']),
  418. 'update_time' => time()
  419. ];
  420. }
  421. }
  422. break;
  423. }
  424. if ($data) {
  425. $this->dao->saveAll($data);
  426. }
  427. return true;
  428. }
  429. /**
  430. * @param int $type
  431. * @param string $reagion
  432. * @return mixed|string
  433. */
  434. public function getReagionHost(int $type, string $reagion)
  435. {
  436. $upload = UploadService::init($type);
  437. $reagionList = $upload->getRegion();
  438. foreach ($reagionList as $item) {
  439. if (strstr($item['value'], $reagion) !== false) {
  440. return $item['value'];
  441. }
  442. }
  443. return '';
  444. }
  445. /**
  446. * 获取域名
  447. * @param int $type
  448. * @param string $name
  449. * @param string $reagion
  450. * @param string $appid
  451. * @return string
  452. */
  453. public function getDomain(int $type, string $name, string $reagion, string $appid = '')
  454. {
  455. $domainName = '';
  456. switch ($type) {
  457. case 3:// oss 阿里云
  458. $domainName = 'https://' . $name . '.' . $reagion;
  459. break;
  460. case 4:// cos 腾讯云
  461. $domainName = 'https://' . $name . ($appid ? '-' . $appid : '') . '.cos.' . $reagion . '.myqcloud.com';
  462. break;
  463. case 5:// cos 京东云
  464. $domainName = 'https://' . $name . '.s3.' . $reagion . '.jdcloud-oss.com';
  465. break;
  466. case 6:// cos 华为云
  467. $domainName = 'https://' . $name . '.obs.' . $reagion . '.myhuaweicloud.com';
  468. break;
  469. case 7:// cos 天翼云
  470. $domainName = 'https://' . $name . '.obs.' . $reagion . '.ctyun.cn';
  471. break;
  472. }
  473. return $domainName;
  474. }
  475. /**
  476. * 获取云存储配置
  477. * @param int $type
  478. * @return array|string[]
  479. */
  480. public function getConfig(int $type)
  481. {
  482. $res = ['name' => '', 'region' => '', 'domain' => ''];
  483. try {
  484. $config = $this->dao->get(['type' => $type, 'status' => 1, 'is_delete' => 0]);
  485. if ($config) {
  486. return ['name' => $config->name, 'region' => $config->region, 'domain' => $config->domain];
  487. }
  488. } catch (\Throwable $e) {
  489. }
  490. return $res;
  491. }
  492. /**
  493. * 获取修改域名表单
  494. * @param int $id
  495. * @return array
  496. * @throws \FormBuilder\Exception\FormBuilderException
  497. */
  498. public function getUpdateDomainForm(int $id)
  499. {
  500. $domain = $this->dao->value(['id' => $id], 'domain');
  501. $rule = [
  502. FormBuilder::input('domain', '空间域名', $domain),
  503. ];
  504. return create_form('修改空间域名', $rule, '/setting/config/storage/domain/' . $id);
  505. }
  506. /**
  507. * 修改域名并绑定
  508. * @param int $id
  509. * @param string $domain
  510. * @return bool
  511. * @throws \think\db\exception\DataNotFoundException
  512. * @throws \think\db\exception\DbException
  513. * @throws \think\db\exception\ModelNotFoundException
  514. */
  515. public function updateDomain(int $id, string $domain, array $data = [])
  516. {
  517. $info = $this->dao->get($id);
  518. if (!$info) {
  519. throw new ValidateException('没有查询到数据');
  520. }
  521. if ($info->domain != $domain) {
  522. $info->domain = $domain;
  523. $upload = UploadService::init($info->type);
  524. //是否添加过域名不存在需要绑定域名
  525. $domainList = $upload->getDomian($info->name, $info->region);
  526. $domainParse = parse_url($domain);
  527. if (!in_array($domainParse['host'], $domainList)) {
  528. //绑定域名到云储存桶
  529. $res = $upload->bindDomian($info->name, $domain, $info->region);
  530. if (false === $res) {
  531. throw new ValidateException($upload->getError());
  532. }
  533. }
  534. //七牛云需要通过接口获取cname
  535. if (2 === ((int)$info->type)) {
  536. $resDomain = $upload->getDomianInfo($domain);
  537. $info->cname = $resDomain['cname'] ?? '';
  538. }
  539. return $info->save();
  540. }
  541. if ($info->cdn != $data['cdn']) {
  542. $info->cdn = $data['cdn'];
  543. $info->save();
  544. }
  545. return true;
  546. }
  547. }