SystemStorageServices.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. $upload->deleteBucket($storageInfo->name, $storageInfo->region);
  175. } catch (\Throwable $e) {
  176. throw new AdminException($e->getMessage());
  177. }
  178. $storageInfo->is_delete = 1;
  179. $storageInfo->save();
  180. $this->cacheDriver()->clear();
  181. return true;
  182. }
  183. public function saveConfig(int $type, array $data)
  184. {
  185. //保存配置信息
  186. if (1 !== $type) {
  187. $accessKey = $secretKey = $appid = '';
  188. if (isset($data['accessKey']) && isset($data['secretKey']) && $data['accessKey'] && $data['secretKey']) {
  189. $accessKey = $data['accessKey'];
  190. $secretKey = $data['secretKey'];
  191. unset($data['accessKey'], $data['secretKey']);
  192. }
  193. if (isset($data['appid']) && $data['appid']) {
  194. $appid = $data['appid'];
  195. unset($data['appid']);
  196. }
  197. if (!$accessKey || !$secretKey) {
  198. return true;
  199. }
  200. /** @var SystemConfigServices $make */
  201. $make = app()->make(SystemConfigServices::class);
  202. switch ($type) {
  203. case 2://七牛
  204. $make->update('qiniu_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  205. $make->update('qiniu_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  206. break;
  207. case 3:// oss 阿里云
  208. $make->update('accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  209. $make->update('secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  210. break;
  211. case 4:// cos 腾讯云
  212. $make->update('tengxun_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  213. $make->update('tengxun_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  214. $make->update('tengxun_appid', ['value' => json_encode($appid)], 'menu_name');
  215. break;
  216. case 5:// oss 京东云
  217. $make->update('jd_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  218. $make->update('jd_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  219. break;
  220. case 6:// oss 华为云
  221. $make->update('hw_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  222. $make->update('hw_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  223. break;
  224. case 7:// oss 天翼云
  225. $make->update('ty_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  226. $make->update('ty_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  227. break;
  228. }
  229. $make->cacheDriver()->clear();
  230. }
  231. }
  232. /**
  233. * 保存云存储
  234. * @param int $type
  235. * @param array $data
  236. * @return mixed
  237. */
  238. public function saveStorage(int $type, array $data)
  239. {
  240. //保存配置信息
  241. $this->saveConfig($type, $data);
  242. if ($this->dao->count(['name' => $data['name']])) {
  243. throw new AdminException(400610);
  244. }
  245. //保存云存储
  246. $data['type'] = $type;
  247. $upload = UploadService::init($type);
  248. $res = $upload->createBucket($data['name'], $data['region'], $data['acl']);
  249. if (false === $res) {
  250. throw new AdminException($upload->getError());
  251. }
  252. if (3 === $type) {
  253. $data['region'] = $this->getReagionHost($type, $data['region']);
  254. }
  255. $data['domain'] = $this->getDomain($type, $data['name'], $data['region'], sys_config('tengxun_appid'));
  256. if (2 === $type) {
  257. $domianList = $upload->getDomian($data['name']);
  258. $data['domain'] = $domianList[count($domianList) - 1];
  259. } else {
  260. $data['cname'] = $data['domain'];
  261. }
  262. $data['add_time'] = time();
  263. $data['update_time'] = time();
  264. $config = $this->getStorageConfig($type);
  265. $data['access_key'] = $config['accessKey'];
  266. $this->cacheDriver()->clear();
  267. return $this->dao->save($data);
  268. }
  269. /**
  270. * 同步云储存桶
  271. * @param int $type
  272. * @return bool
  273. */
  274. public function synchronization(int $type)
  275. {
  276. $data = [];
  277. switch ($type) {
  278. case 2://七牛
  279. $config = $this->getStorageConfig($type);
  280. $upload = UploadService::init($type);
  281. $list = $upload->listbuckets();
  282. foreach ($list as $item) {
  283. if (!$this->dao->count(['name' => $item['id'], 'access_key' => $config['accessKey']])) {
  284. $data[] = [
  285. 'type' => $type,
  286. 'access_key' => $config['accessKey'],
  287. 'name' => $item['id'],
  288. 'region' => $item['region'],
  289. 'acl' => $item['private'] == 0 ? 'public-read' : 'private',
  290. 'status' => 0,
  291. 'is_delete' => 0,
  292. 'add_time' => time(),
  293. 'update_time' => time()
  294. ];
  295. }
  296. }
  297. break;
  298. case 3:// oss 阿里云
  299. $upload = UploadService::init($type);
  300. $list = $upload->listbuckets();
  301. $config = $this->getStorageConfig($type);
  302. foreach ($list as $item) {
  303. if (!$this->dao->count(['name' => $item['name'], 'access_key' => $config['accessKey']])) {
  304. $region = $this->getReagionHost($type, $item['location']);
  305. $data[] = [
  306. 'type' => $type,
  307. 'access_key' => $config['accessKey'],
  308. 'name' => $item['name'],
  309. 'region' => $region,
  310. 'acl' => 'public-read',
  311. 'domain' => $this->getDomain($type, $item['name'], $region),
  312. 'status' => 0,
  313. 'is_delete' => 0,
  314. 'add_time' => strtotime($item['createTime']),
  315. 'update_time' => time()
  316. ];
  317. }
  318. }
  319. break;
  320. case 4:// cos 腾讯云
  321. $upload = UploadService::init($type);
  322. $list = $upload->listbuckets();
  323. if (!empty($list['Name'])) {
  324. $newList = $list;
  325. $list = [];
  326. $list[] = $newList;
  327. }
  328. $config = $this->getStorageConfig($type);
  329. foreach ($list as $item) {
  330. if (!$this->dao->count(['name' => $item['Name'], 'access_key' => $config['accessKey']])) {
  331. $data[] = [
  332. 'type' => $type,
  333. 'access_key' => $config['accessKey'],
  334. 'name' => $item['Name'],
  335. 'region' => $item['Location'],
  336. 'acl' => 'public-read',
  337. 'status' => 0,
  338. 'domain' => sys_config('tengxun_appid') ? $this->getDomain($type, $item['Name'], $item['Location']) : '',
  339. 'is_delete' => 0,
  340. 'add_time' => strtotime($item['CreationDate']),
  341. 'update_time' => time()
  342. ];
  343. }
  344. }
  345. break;
  346. case 5:// cos 京东云
  347. case 6:// cos 华为云
  348. case 7:// cos 天翼云
  349. $upload = UploadService::init($type);
  350. $list = $upload->listbuckets();
  351. $config = $this->getStorageConfig($type);
  352. foreach ($list as $item) {
  353. if (!$this->dao->count(['name' => $item['Name'], 'access_key' => $config['accessKey']])) {
  354. $data[] = [
  355. 'type' => $type,
  356. 'access_key' => $config['accessKey'],
  357. 'name' => $item['Name'],
  358. 'region' => $item['Location'],
  359. 'acl' => 'public-read',
  360. 'status' => 0,
  361. 'domain' => $this->getDomain($type, $item['Name'], $item['Location']),
  362. 'is_delete' => 0,
  363. 'add_time' => strtotime($item['CreationDate']),
  364. 'update_time' => time()
  365. ];
  366. }
  367. }
  368. break;
  369. }
  370. if ($data) {
  371. $this->dao->saveAll($data);
  372. }
  373. $this->cacheDriver()->clear();
  374. return true;
  375. }
  376. /**
  377. * @param int $type
  378. * @param string $reagion
  379. * @return mixed|string
  380. */
  381. public function getReagionHost(int $type, string $reagion)
  382. {
  383. $upload = UploadService::init($type);
  384. $reagionList = $upload->getRegion();
  385. foreach ($reagionList as $item) {
  386. if (strstr($item['value'], $reagion) !== false) {
  387. return $item['value'];
  388. }
  389. }
  390. return '';
  391. }
  392. /**
  393. * 获取域名
  394. * @param int $type
  395. * @param string $name
  396. * @param string $reagion
  397. * @param string $appid
  398. * @return string
  399. */
  400. public function getDomain(int $type, string $name, string $reagion, string $appid = '')
  401. {
  402. $domainName = '';
  403. switch ($type) {
  404. case 3:// oss 阿里云
  405. $domainName = 'https://' . $name . '.' . $reagion;
  406. break;
  407. case 4:// cos 腾讯云
  408. $domainName = 'https://' . $name . ($appid ? '-' . $appid : '') . '.cos.' . $reagion . '.myqcloud.com';
  409. break;
  410. case 5:// cos 京东云
  411. $domainName = 'https://' . $name . '.s3.' . $reagion . '.jdcloud-oss.com';
  412. break;
  413. case 6:// cos 华为云
  414. $domainName = 'https://' . $name . '.obs.' . $reagion . '.myhuaweicloud.com';
  415. break;
  416. case 7:// cos 天翼云
  417. $domainName = 'https://' . $name . '.obs.' . $reagion . '.ctyun.cn';
  418. break;
  419. }
  420. return $domainName;
  421. }
  422. /**
  423. * 获取云存储配置
  424. * @param int $type
  425. * @return array|string[]
  426. */
  427. public function getConfig(int $type)
  428. {
  429. $res = ['name' => '', 'region' => '', 'domain' => '', 'cdn' => ''];
  430. try {
  431. $config = $this->dao->get(['type' => $type, 'status' => 1, 'is_delete' => 0]);
  432. if ($config) {
  433. return ['name' => $config->name, 'region' => $config->region, 'domain' => $config->domain, 'cdn' => $config->cdn];
  434. }
  435. } catch (\Throwable $e) {
  436. }
  437. return $res;
  438. }
  439. /**
  440. * 获取修改域名表单
  441. * @param int $id
  442. * @return array
  443. * @throws \FormBuilder\Exception\FormBuilderException
  444. */
  445. public function getUpdateDomainForm(int $id)
  446. {
  447. $storage = $this->dao->get(['id' => $id], ['domain', 'cdn']);
  448. $rule = [
  449. FormBuilder::input('domain', '空间域名', $storage['domain']),
  450. FormBuilder::input('cdn', 'cdn域名', $storage['cdn']),
  451. ];
  452. return create_form('修改空间域名', $rule, '/system/config/storage/domain/' . $id);
  453. }
  454. /**
  455. * 修改域名并绑定
  456. * @param int $id
  457. * @param string $domain
  458. * @return bool
  459. * @throws \think\db\exception\DataNotFoundException
  460. * @throws \think\db\exception\DbException
  461. * @throws \think\db\exception\ModelNotFoundException
  462. */
  463. public function updateDomain(int $id, string $domain, array $data = [])
  464. {
  465. $info = $this->dao->get($id);
  466. if (!$info) {
  467. throw new AdminException(100026);
  468. }
  469. if ($info->domain != $domain) {
  470. $info->domain = $domain;
  471. $upload = UploadService::init($info->type);
  472. //是否添加过域名不存在需要绑定域名
  473. $domainList = $upload->getDomian($info->name, $info->region);
  474. $domainParse = parse_url($domain);
  475. if (false === $domainParse) {
  476. throw new AdminException('域名输入有误');
  477. }
  478. if (!in_array($domainParse['host'], $domainList)) {
  479. //绑定域名到云储存桶
  480. $res = $upload->bindDomian($info->name, $domain, $info->region);
  481. if (false === $res) {
  482. throw new AdminException($upload->getError());
  483. }
  484. }
  485. //七牛云需要通过接口获取cname
  486. if (2 === ((int)$info->type)) {
  487. $resDomain = $upload->getDomianInfo($domain);
  488. $info->cname = $resDomain['cname'] ?? '';
  489. }
  490. $info->save();
  491. }
  492. if ($info->cdn != $data['cdn']) {
  493. $info->cdn = $data['cdn'];
  494. $info->save();
  495. }
  496. $this->cacheDriver()->clear();
  497. return true;
  498. }
  499. }