SystemStorageServices.php 16 KB

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