SystemStorageServices.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. use crmeb\traits\ServicesTrait;
  18. /**
  19. * Class SystemStorageServices
  20. * @package app\services\system\config
  21. */
  22. class SystemStorageServices extends BaseServices
  23. {
  24. use ServicesTrait;
  25. /**
  26. * SystemStorageServices constructor.
  27. * @param SystemStorageDao $dao
  28. */
  29. public function __construct(SystemStorageDao $dao)
  30. {
  31. $this->dao = $dao;
  32. }
  33. /**
  34. * @param array $where
  35. * @return array
  36. */
  37. public function getList(array $where)
  38. {
  39. [$page, $limit] = $this->getPageValue();
  40. $config = $this->getStorageConfig((int)$where['type']);
  41. $where['access_key'] = $config['accessKey'];
  42. $list = $this->dao->getList($where, ['*'], $page, $limit, 'add_time');
  43. foreach ($list as &$item) {
  44. $item['_add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  45. $item['_update_time'] = date('Y-m-d H:i:s', $item['update_time']);
  46. $service = UploadService::init($item['type']);
  47. $region = $service->getRegion();
  48. foreach ($region as $value) {
  49. if (strstr($item['region'], $value['value'])) {
  50. $item['_region'] = $value['label'];
  51. }
  52. }
  53. }
  54. $count = $this->dao->count($where);
  55. return compact('list', 'count');
  56. }
  57. /**
  58. * @param int $type
  59. * @return array
  60. * @throws \FormBuilder\Exception\FormBuilderException
  61. */
  62. public function getFormStorage(int $type)
  63. {
  64. $upload = UploadService::init($type);
  65. $config = $this->getStorageConfig($type);
  66. $ruleConfig = [];
  67. if (!$config['accessKey']) {
  68. $ruleConfig = [
  69. FormBuilder::input('accessKey', 'AccessKeyId:', $config['accessKey'] ?? '')->required(),
  70. FormBuilder::input('secretKey', 'AccessKeySecret::', $config['secretKey'] ?? '')->required(),
  71. ];
  72. }
  73. if ($type === 4 && isset($config['appid']) && !$config['appid']) {
  74. $ruleConfig[] = FormBuilder::input('appid', 'APPID', $config['appid'] ?? '')->required();
  75. }
  76. $rule = [
  77. FormBuilder::input('name', '空间名称')->required(),
  78. FormBuilder::select('region', '空间区域')->options($upload->getRegion())->required(),
  79. FormBuilder::radio('acl', '读写权限','public-read')->options([
  80. ['label' => '公共读(推荐)', 'value' => 'public-read'],
  81. ['label' => '公共读写', 'value' => 'public-read-write'],
  82. ])->required(),
  83. ];
  84. $rule = array_merge($ruleConfig, $rule);
  85. return create_form('添加云空间', $rule, '/system/config/storage/' . $type);
  86. }
  87. /**
  88. * @param int $type
  89. * @return array
  90. */
  91. public function getStorageConfig(int $type)
  92. {
  93. $config = [
  94. 'accessKey' => '',
  95. 'secretKey' => ''
  96. ];
  97. switch ($type) {
  98. case 2://七牛
  99. $config = [
  100. 'accessKey' => sys_config('qiniu_accessKey', ''),
  101. 'secretKey' => sys_config('qiniu_secretKey', ''),
  102. ];
  103. break;
  104. case 3:// oss 阿里云
  105. $config = [
  106. 'accessKey' => sys_config('accessKey', ''),
  107. 'secretKey' => sys_config('secretKey', ''),
  108. ];
  109. break;
  110. case 4:// cos 腾讯云
  111. $config = [
  112. 'accessKey' => sys_config('tengxun_accessKey', ''),
  113. 'secretKey' => sys_config('tengxun_secretKey', ''),
  114. 'appid' => sys_config('tengxun_appid', ''),
  115. ];
  116. break;
  117. }
  118. return $config;
  119. }
  120. /**
  121. * @param int $type
  122. * @return array
  123. * @throws \FormBuilder\Exception\FormBuilderException
  124. */
  125. public function getFormStorageConfig(int $type)
  126. {
  127. $config = $this->getStorageConfig($type);
  128. $rule = [
  129. FormBuilder::hidden('type', $type),
  130. FormBuilder::input('accessKey', 'AccessKeyId:', $config['accessKey'] ?? '')->required(),
  131. FormBuilder::input('secretKey', 'AccessKeySecret:', $config['secretKey'] ?? '')->required(),
  132. ];
  133. if ($type === 4) {
  134. $rule[] = FormBuilder::input('appid', 'APPID', $config['appid'] ?? '')->required();
  135. }
  136. return create_form('配置信息', $rule, '/system/config/storage/config');
  137. }
  138. /**
  139. * 删除空间
  140. * @param int $id
  141. * @return bool
  142. * @throws \think\db\exception\DataNotFoundException
  143. * @throws \think\db\exception\DbException
  144. * @throws \think\db\exception\ModelNotFoundException
  145. */
  146. public function deleteStorage(int $id)
  147. {
  148. $storageInfo = $this->dao->get(['is_delete' => 0, 'id' => $id]);
  149. if (!$storageInfo) {
  150. throw new AdminException(400608);
  151. }
  152. if ($storageInfo->status) {
  153. throw new AdminException(400609);
  154. }
  155. try {
  156. $upload = UploadService::init($storageInfo->type);
  157. $upload->deleteBucket($storageInfo->name, $storageInfo->region);
  158. } catch (\Throwable $e) {
  159. throw new AdminException($e->getMessage());
  160. }
  161. $storageInfo->is_delete = 1;
  162. $storageInfo->save();
  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. 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. return true;
  320. }
  321. /**
  322. * @param int $type
  323. * @param string $reagion
  324. * @return mixed|string
  325. */
  326. public function getReagionHost(int $type, string $reagion)
  327. {
  328. $upload = UploadService::init($type);
  329. $reagionList = $upload->getRegion();
  330. foreach ($reagionList as $item) {
  331. if (strstr($item['value'], $reagion) !== false) {
  332. return $item['value'];
  333. }
  334. }
  335. return '';
  336. }
  337. /**
  338. * 获取域名
  339. * @param int $type
  340. * @param string $name
  341. * @param string $reagion
  342. * @param string $appid
  343. * @return string
  344. */
  345. public function getDomain(int $type, string $name, string $reagion, string $appid = '')
  346. {
  347. $domainName = '';
  348. switch ($type) {
  349. case 3:// oss 阿里云
  350. $domainName = 'https://' . $name . '.' . $reagion;
  351. break;
  352. case 4:// cos 腾讯云
  353. $domainName = 'https://' . $name . ($appid ? '-' . $appid : '') . '.cos.' . $reagion . '.myqcloud.com';
  354. break;
  355. }
  356. return $domainName;
  357. }
  358. /**
  359. * 获取云存储配置
  360. * @param int $type
  361. * @return array|string[]
  362. */
  363. public function getConfig(int $type)
  364. {
  365. $res = ['name' => '', 'region' => '', 'domain' => ''];
  366. try {
  367. $config = $this->dao->get(['type' => $type, 'status' => 1, 'is_delete' => 0]);
  368. if ($config) {
  369. return ['name' => $config->name, 'region' => $config->region, 'domain' => $config->domain];
  370. }
  371. } catch (\Throwable $e) {
  372. }
  373. return $res;
  374. }
  375. /**
  376. * 获取修改域名表单
  377. * @param int $id
  378. * @return array
  379. * @throws \FormBuilder\Exception\FormBuilderException
  380. */
  381. public function getUpdateDomainForm(int $id)
  382. {
  383. $domain = $this->dao->value(['id' => $id], 'domain');
  384. $rule = [
  385. FormBuilder::input('domain', '空间域名', $domain),
  386. ];
  387. return create_form('修改空间域名', $rule, '/system/config/storage/domain/' . $id);
  388. }
  389. /**
  390. * 修改域名并绑定
  391. * @param int $id
  392. * @param string $domain
  393. * @return bool
  394. * @throws \think\db\exception\DataNotFoundException
  395. * @throws \think\db\exception\DbException
  396. * @throws \think\db\exception\ModelNotFoundException
  397. */
  398. public function updateDomain(int $id, string $domain, array $data = [])
  399. {
  400. $info = $this->dao->get($id);
  401. if (!$info) {
  402. throw new AdminException(100026);
  403. }
  404. if ($info->domain != $domain) {
  405. $info->domain = $domain;
  406. $upload = UploadService::init($info->type);
  407. //是否添加过域名不存在需要绑定域名
  408. $domainList = $upload->getDomian($info->name, $info->region);
  409. $domainParse = parse_url($domain);
  410. if (!in_array($domainParse['host'], $domainList)) {
  411. //绑定域名到云储存桶
  412. $res = $upload->bindDomian($info->name, $domain, $info->region);
  413. if (false === $res) {
  414. throw new AdminException($upload->getError());
  415. }
  416. }
  417. //七牛云需要通过接口获取cname
  418. if (2 === ((int)$info->type)) {
  419. $resDomain = $upload->getDomianInfo($domain);
  420. $info->cname = $resDomain['cname'] ?? '';
  421. }
  422. return $info->save();
  423. }
  424. return true;
  425. }
  426. }