SystemStorageServices.php 16 KB

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