SystemStorageServices.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 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\model\system\config\SystemStorage;
  13. use qiniu\basic\BaseServices;
  14. use qiniu\services\CacheService;
  15. use qiniu\services\SystemConfigService;
  16. use qiniu\services\UploadService;
  17. use think\db\exception\DbException;
  18. use think\exception\ValidateException;
  19. /**
  20. * Class SystemStorageServices
  21. * @package app\services\system\config
  22. * @mixin SystemStorage
  23. */
  24. class SystemStorageServices extends BaseServices
  25. {
  26. /**
  27. * SystemStorageServices constructor.
  28. * @param SystemStorage $model
  29. */
  30. public function __construct(SystemStorage $model)
  31. {
  32. $this->model = $model;
  33. }
  34. /**
  35. * @param array $where
  36. * @return array
  37. * @throws DbException
  38. */
  39. public function getStorageList(array $where)
  40. {
  41. [$page, $limit] = $this->getPageValue();
  42. $config = $this->getStorageConfig((int)$where['type']);
  43. $where['access_key'] = $config['accessKey'];
  44. $list = $this->getList($where, '*', $page, $limit);
  45. foreach ($list as &$item) {
  46. $item['_add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  47. $item['_update_time'] = date('Y-m-d H:i:s', $item['update_time']);
  48. $service = UploadService::init($item['type']);
  49. $region = $service->getRegion();
  50. foreach ($region as $value) {
  51. if (strstr($item['region'], $value['value'])) {
  52. $item['_region'] = $value['label'];
  53. }
  54. }
  55. if (!$item['cname']) {
  56. $item['cname'] = str_replace(['http://', 'https://'], '', $item['domain']);
  57. }
  58. }
  59. $count = $this->getCount($where);
  60. return compact('list', 'count');
  61. }
  62. /**
  63. * @param int $type
  64. * @return array
  65. */
  66. public function getStorageConfig(int $type)
  67. {
  68. $config = [
  69. 'accessKey' => '',
  70. 'secretKey' => ''
  71. ];
  72. switch ($type) {
  73. case 2://七牛
  74. $config = [
  75. 'accessKey' => sys_config('qiniu_accessKey', ''),
  76. 'secretKey' => sys_config('qiniu_secretKey', ''),
  77. ];
  78. break;
  79. case 3:// oss 阿里云
  80. $config = [
  81. 'accessKey' => sys_config('accessKey', ''),
  82. 'secretKey' => sys_config('secretKey', ''),
  83. ];
  84. break;
  85. case 4:// cos 腾讯云
  86. $config = [
  87. 'accessKey' => sys_config('tengxun_accessKey', ''),
  88. 'secretKey' => sys_config('tengxun_secretKey', ''),
  89. 'appid' => sys_config('tengxun_appid', ''),
  90. ];
  91. break;
  92. }
  93. return $config;
  94. }
  95. /**
  96. * 删除空间
  97. * @param int $id
  98. * @return bool
  99. * @throws \think\db\exception\DataNotFoundException
  100. * @throws DbException
  101. * @throws \think\db\exception\ModelNotFoundException
  102. */
  103. public function deleteStorage(int $id)
  104. {
  105. $storageInfo = $this->get(['is_delete' => 0, 'id' => $id]);
  106. if (!$storageInfo) {
  107. throw new ValidateException('删除的云存储不存在');
  108. }
  109. if ($storageInfo->status) {
  110. throw new ValidateException('云存储正在使用中,需要启动其他空间才能删除');
  111. }
  112. try {
  113. $upload = UploadService::init($storageInfo->type);
  114. $res = $upload->deleteBucket($storageInfo->name, $storageInfo->region);
  115. if (false === $res) {
  116. throw new ValidateException($upload->getError());
  117. }
  118. } catch (\Throwable $e) {
  119. throw new ValidateException($e->getMessage());
  120. }
  121. $storageInfo->is_delete = 1;
  122. $storageInfo->save();
  123. return true;
  124. }
  125. public function saveConfig(int $type, array $data)
  126. {
  127. //保存配置信息
  128. if (1 !== $type) {
  129. $accessKey = $secretKey = $appid = $storageRegion = '';
  130. if (isset($data['accessKey']) && isset($data['secretKey']) && $data['accessKey'] && $data['secretKey']) {
  131. $accessKey = $data['accessKey'];
  132. $secretKey = $data['secretKey'];
  133. unset($data['accessKey'], $data['secretKey']);
  134. }
  135. if (isset($data['appid']) && $data['appid']) {
  136. $appid = $data['appid'];
  137. unset($data['appid']);
  138. }
  139. if (isset($data['storageRegion']) && $data['storageRegion']) {
  140. $storageRegion = $data['storageRegion'];
  141. unset($data['storageRegion']);
  142. }
  143. if (!$accessKey || !$secretKey) {
  144. return true;
  145. }
  146. /** @var SystemConfigServices $make */
  147. $make = app()->make(SystemConfigServices::class);
  148. switch ($type) {
  149. case 2://七牛
  150. $make->update('qiniu_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  151. $make->update('qiniu_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  152. break;
  153. case 3:// oss 阿里云
  154. $make->update('accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  155. $make->update('secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  156. break;
  157. case 4:// cos 腾讯云
  158. $make->update('tengxun_accessKey', ['value' => json_encode($accessKey)], 'menu_name');
  159. $make->update('tengxun_secretKey', ['value' => json_encode($secretKey)], 'menu_name');
  160. $make->update('tengxun_appid', ['value' => json_encode($appid)], 'menu_name');
  161. break;
  162. }
  163. CacheService::redisHandler(SystemConfigService::getTag())->clear();
  164. }
  165. }
  166. /**
  167. * 保存云存储
  168. * @param int $type
  169. * @param array $data
  170. * @return mixed
  171. */
  172. public function saveStorage(int $type, array $data)
  173. {
  174. //保存配置信息
  175. $this->saveConfig($type, $data);
  176. $name = $data['name'];
  177. switch ($type) {
  178. case 3://阿里云oss
  179. $data['region'] = $this->getReagionHost($type, $data['region']);
  180. break;
  181. case 4://腾讯云cos
  182. $name = $data['name'] . '-' . sys_config('tengxun_appid');
  183. break;
  184. }
  185. if ($this->getCount(['type' => $type, 'name' => $name])) {
  186. throw new ValidateException('云空间名称不能重复');
  187. }
  188. //保存云存储
  189. $data['type'] = $type;
  190. $upload = UploadService::init($type);
  191. $res = $upload->createBucket($data['name'], $data['region'], $data['acl']);
  192. if (false === $res) {
  193. throw new ValidateException($upload->getError());
  194. }
  195. $data['domain'] = $this->getDomain($type, $data['name'], $data['region'], sys_config('tengxun_appid'));
  196. if (2 === $type) {
  197. $domianList = $upload->getDomian($data['name']);
  198. $data['domain'] = $domianList[count($domianList) - 1];
  199. } else {
  200. $data['cname'] = $data['domain'];
  201. }
  202. $data['name'] = $name;
  203. $data['add_time'] = time();
  204. $data['update_time'] = time();
  205. $config = $this->getStorageConfig($type);
  206. $data['access_key'] = $config['accessKey'];
  207. return $this->save($data);
  208. }
  209. /**
  210. * 同步云储存桶
  211. * @param int $type
  212. * @return bool
  213. * @throws \OSS\Core\OssException
  214. */
  215. public function synchronization(int $type)
  216. {
  217. $data = [];
  218. switch ($type) {
  219. case 2://七牛
  220. $config = $this->getStorageConfig($type);
  221. $upload = UploadService::init($type);
  222. $list = $upload->listbuckets();
  223. if (false === $list) {
  224. throw new ValidateException('同步失败,失败原因:' . $upload->getError());
  225. }
  226. foreach ($list as $item) {
  227. if (!$this->getCount(['name' => $item['id'], 'is_delete' => 0, 'access_key' => $config['accessKey']])) {
  228. $data[] = [
  229. 'type' => $type,
  230. 'access_key' => $config['accessKey'],
  231. 'name' => $item['id'],
  232. 'region' => $item['region'],
  233. 'acl' => $item['private'] == 0 ? 'public-read' : 'private',
  234. 'status' => 0,
  235. 'is_delete' => 0,
  236. 'add_time' => time(),
  237. 'update_time' => time()
  238. ];
  239. }
  240. }
  241. break;
  242. case 3:// oss 阿里云
  243. $upload = UploadService::init($type);
  244. $list = $upload->listbuckets();
  245. $config = $this->getStorageConfig($type);
  246. foreach ($list as $item) {
  247. if (!$this->getCount(['name' => $item['name'], 'is_delete' => 0, 'access_key' => $config['accessKey']])) {
  248. $region = $this->getReagionHost($type, $item['location']);
  249. $data[] = [
  250. 'type' => $type,
  251. 'access_key' => $config['accessKey'],
  252. 'name' => $item['name'],
  253. 'region' => $region,
  254. 'acl' => 'public-read',
  255. 'domain' => $this->getDomain($type, $item['name'], $region),
  256. 'status' => 0,
  257. 'is_delete' => 0,
  258. 'add_time' => strtotime($item['createTime']),
  259. 'update_time' => time()
  260. ];
  261. }
  262. }
  263. break;
  264. case 4:// cos 腾讯云
  265. $upload = UploadService::init($type);
  266. $list = $upload->listbuckets();
  267. $config = $this->getStorageConfig($type);
  268. foreach ($list as $item) {
  269. if (($id = $this->getOneValue(['name' => $item['Name'], 'is_delete' => 0, 'access_key' => $config['accessKey']], 'id'))) {
  270. $this->update($id, [
  271. 'update_time' => time(),
  272. 'region' => $item['Location'],
  273. 'name' => $item['Name'],
  274. 'domain' => sys_config('tengxun_appid') ? $this->getDomain($type, $item['Name'], $item['Location']) : '',
  275. ]);
  276. } else {
  277. $data[] = [
  278. 'type' => $type,
  279. 'access_key' => $config['accessKey'],
  280. 'name' => $item['Name'],
  281. 'region' => $item['Location'],
  282. 'acl' => 'public-read',
  283. 'status' => 0,
  284. 'domain' => sys_config('tengxun_appid') ? $this->getDomain($type, $item['Name'], $item['Location']) : '',
  285. 'is_delete' => 0,
  286. 'add_time' => strtotime($item['CreationDate']),
  287. 'update_time' => time()
  288. ];
  289. }
  290. }
  291. break;
  292. }
  293. if ($data) {
  294. $this->saveAll($data);
  295. }
  296. return true;
  297. }
  298. /**
  299. * @param int $type
  300. * @param string $reagion
  301. * @return mixed|string
  302. */
  303. public function getReagionHost(int $type, string $reagion)
  304. {
  305. $upload = UploadService::init($type);
  306. $reagionList = $upload->getRegion();
  307. foreach ($reagionList as $item) {
  308. if (strstr($item['value'], $reagion) !== false) {
  309. return $item['value'];
  310. }
  311. }
  312. return '';
  313. }
  314. /**
  315. * 获取域名
  316. * @param int $type
  317. * @param string $name
  318. * @param string $reagion
  319. * @param string $appid
  320. * @return string
  321. */
  322. public function getDomain(int $type, string $name, string $reagion, string $appid = '')
  323. {
  324. $domainName = '';
  325. switch ($type) {
  326. case 3:// oss 阿里云
  327. $domainName = 'https://' . $name . '.' . $reagion;
  328. break;
  329. case 4:// cos 腾讯云
  330. $domainName = 'https://' . $name . ($appid ? '-' . $appid : '') . '.cos.' . $reagion . '.myqcloud.com';
  331. break;
  332. }
  333. return $domainName;
  334. }
  335. /**
  336. * 获取云存储配置
  337. * @param int $type
  338. * @return array|string[]
  339. */
  340. public function getConfig(int $type)
  341. {
  342. $res = ['name' => '', 'region' => '', 'domain' => ''];
  343. try {
  344. $config = $this->get(['type' => $type, 'status' => 1, 'is_delete' => 0]);
  345. if ($config) {
  346. return ['name' => $config->name, 'region' => $config->region, 'domain' => $config->domain];
  347. }
  348. } catch (\Throwable $e) {
  349. }
  350. return $res;
  351. }
  352. /**
  353. * 修改域名并绑定
  354. * @param int $id
  355. * @param string $domain
  356. * @return bool
  357. * @throws \think\db\exception\DataNotFoundException
  358. * @throws DbException
  359. * @throws \think\db\exception\ModelNotFoundException
  360. */
  361. public function updateDomain(int $id, string $domain, array $data = [])
  362. {
  363. $info = $this->get($id);
  364. if (!$info) {
  365. throw new ValidateException('没有查询到数据');
  366. }
  367. if ($info->domain != $domain) {
  368. $info->domain = $domain;
  369. $upload = UploadService::init($info->type);
  370. //是否添加过域名不存在需要绑定域名
  371. $domainList = $upload->getDomian($info->name, $info->region);
  372. $domainParse = parse_url($domain);
  373. if (!in_array($domainParse['host'], $domainList)) {
  374. //绑定域名到云储存桶
  375. $res = $upload->bindDomian($info->name, $domain, $info->region);
  376. if (false === $res) {
  377. throw new ValidateException($upload->getError());
  378. }
  379. }
  380. //七牛云需要通过接口获取cname
  381. if (2 === ((int)$info->type)) {
  382. $resDomain = $upload->getDomianInfo($domain);
  383. $info->cname = $resDomain['cname'] ?? '';
  384. }
  385. return $info->save();
  386. }
  387. if ($info->cdn != $data['cdn']) {
  388. $info->cdn = $data['cdn'];
  389. $info->save();
  390. }
  391. return true;
  392. }
  393. }