SystemStorageServices.php 18 KB

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