SystemStorageServices.php 20 KB

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