Skip to content

Commit

Permalink
网站同步hosts优化
Browse files Browse the repository at this point in the history
  • Loading branch information
xianyunleo committed Dec 1, 2023
1 parent 3fd93e1 commit eae044d
Show file tree
Hide file tree
Showing 4 changed files with 173 additions and 155 deletions.
19 changes: 12 additions & 7 deletions src/main/core/Nginx.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,16 +135,21 @@ export default class Nginx {
}
}



static async websiteExists(serverName, port) {
static async websiteExists(serverName, port = null) {
const vhostsPath = GetPath.getNginxVhostsDir()
const files = await DirUtil.GetFiles(vhostsPath)
const filterArr = await files.filterAsync(async (path) => {
let confText = await FileUtil.ReadAll(path)
const filterFn = async (path) => {
const confText = await FileUtil.ReadAll(path)
const serverNames = this.getAllServerName(confText)
return serverNames.includes(serverName) && this.getPortByConfPath(path) === port
})
if (serverNames.includes(serverName)) {
if (port != null) {
return this.getPortByConfPath(path) === port
}
return true
}
return false
}
const filterArr = await files.filterAsync(filterFn)
return filterArr.length > 0
}

Expand Down
6 changes: 5 additions & 1 deletion src/main/core/website/Website.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default class Website {
* @param websiteInfo {WebsiteItem}
*/
static async add(websiteInfo) {
if (await Nginx.websiteExists(websiteInfo.serverName, websiteInfo.port)) {
if (await this.exists(websiteInfo.serverName, websiteInfo.port)) {
throw new Error(`${websiteInfo.serverName}:${websiteInfo.port}\n已经存在,不能重复!`)
}

Expand All @@ -19,6 +19,10 @@ export default class Website {
await Nginx.addWebsite(websiteInfo);
}

static async exists(serverName, port = null) {
return await Nginx.websiteExists(serverName, port)
}

static async delete(confName) {
await Nginx.delWebsite(confName);
}
Expand Down
266 changes: 135 additions & 131 deletions src/renderer/components/WebSite/EditWebSite/BasicSetting.vue
Original file line number Diff line number Diff line change
@@ -1,131 +1,135 @@
<template>
<a-form
:model='formData' ref="formRef" name='basic' autocomplete='off'
:label-col='{ span: labelColSpan}' :wrapper-col='{ span: wrapperColSpan}'
>
<a-form-item :label="mt('Second','ws','DomainName')" name='extraServerName'>
<a-input v-model:value='formData.extraServerName' @change='extraServerNameChange'
:placeholder='t("defaultIsEmpty")' spellcheck='false' />
</a-form-item>

<a-form-item :label="t('Port')" name='port'
:rules="[{ required: true, type: 'number', min: 80, max: 65535 }]">
<a-input-number v-model:value='formData.port' min='80' max='65535' disabled />
</a-form-item>

<a-form-item :label="t('RootPath')" name='rootPath' :rules='rootPathRules'>
<input-open-dir-dialog v-model:value='formData.rootPath' :toForwardSlash='true'></input-open-dir-dialog>
</a-form-item>

<a-form-item :label="'PHP'+mt('ws','Version')" name='phpVersion'>
<a-select style='width: 120px' v-model:value='formData.phpVersion' :options='phpVersionList'>
</a-select>
</a-form-item>

<a-form-item :label="mt('Sync','ws')+'hosts'" name='syncHosts'>
<a-switch v-model:checked='formData.syncHosts' :disabled='true' />
</a-form-item>

<a-form-item :label="mt('Note')" name='note'>
<a-input v-model:value='formData.note' :maxlength='20'
:placeholder='t("defaultIsEmpty")' spellcheck='false' />
</a-form-item>
</a-form>

<div style='text-align: center'>
<a-button type='primary' @click='save'>{{t('Save')}}</a-button>
</div>
</template>

<script setup>
import { ref, inject, reactive } from 'vue'
import InputOpenDirDialog from '@/renderer/components/Input/InputOpenDirDialog.vue'
import Website from '@/main/core/website/Website'
import { message } from 'ant-design-vue'
import MessageBox from '@/renderer/utils/MessageBox'
import SoftwareExtend from '@/main/core/software/SoftwareExtend'
import Hosts from '@/main/utils/Hosts'
import { mt, t } from '@/shared/utils/i18n'
import { useMainStore } from '@/renderer/store'
const { confName, search } = inject('WebsiteProvide')
const store = useMainStore()
const formRef = ref();
const formData = reactive({})
const emits = defineEmits(['editAfter'])
const phpVersionList = ref([])
const labelColSpan = store.settings.Language === 'zh' ? 6 : 10;
const wrapperColSpan = store.settings.Language === 'zh' ? 18 : 14;
let websiteInfo
;(async () => {
websiteInfo = await Website.getBasicInfo(confName.value)
Object.assign(formData, websiteInfo)
const list = await SoftwareExtend.getPHPList()
phpVersionList.value = list.map(item => {
return { value: item.version, label: item.name }
})
phpVersionList.value.push({ value: '', label: t('Static') })
})()
const save = async () => {
try {
await formRef.value.validateFields()
} catch (errorInfo) {
console.log('Validate Failed:', errorInfo)
return
}
try {
await Website.saveBasicInfo(confName.value, formData)
message.info('保存成功')
search()
} catch (error) {
MessageBox.error(error.message ?? error, '保存出错!')
return
}
// 会删除所有port的ServerName,需要优化
// if (websiteInfo.syncHosts) {
// try {
// let oldExtraServerName = websiteInfo.extraServerName
// if (formData.extraServerName !== oldExtraServerName) {
// //删除旧的第二域名对应的hosts文件配置
// if (oldExtraServerName) {
// await Hosts.delete(oldExtraServerName)
// }
// //增加新的第二域名对应的hosts文件配置
// if (formData.extraServerName) {
// await Hosts.add(formData.extraServerName)
// }
// }
// } catch (error) {
// MessageBox.error(error.message ?? error, '同步Hosts出错!')
// }
// }
websiteInfo = JSON.parse(JSON.stringify(formData))
emits('editAfter', websiteInfo.phpVersion)
}
const extraServerNameChange = () => {
formData.extraServerName = formData.extraServerName?.trim()
}
const rootPathRules = [
{
required: true,
validator: async (_rule, value) => {
if (value.includes(' ')) {
return Promise.reject(t('pathCannotContainSpaces'))
}
return Promise.resolve()
}
}
]
</script>
<style scoped>
</style>
<template>
<a-form
:model='formData' ref="formRef" name='basic' autocomplete='off'
:label-col='{ span: labelColSpan}' :wrapper-col='{ span: wrapperColSpan}'
>
<a-form-item :label="mt('Second','ws','DomainName')" name='extraServerName'>
<a-input v-model:value='formData.extraServerName' @change='extraServerNameChange'
:placeholder='t("defaultIsEmpty")' spellcheck='false' />
</a-form-item>

<a-form-item :label="t('Port')" name='port'
:rules="[{ required: true, type: 'number', min: 80, max: 65535 }]">
<a-input-number v-model:value='formData.port' min='80' max='65535' disabled />
</a-form-item>

<a-form-item :label="t('RootPath')" name='rootPath' :rules='rootPathRules'>
<input-open-dir-dialog v-model:value='formData.rootPath' :toForwardSlash='true'></input-open-dir-dialog>
</a-form-item>

<a-form-item :label="'PHP'+mt('ws','Version')" name='phpVersion'>
<a-select style='width: 120px' v-model:value='formData.phpVersion' :options='phpVersionList'>
</a-select>
</a-form-item>

<a-form-item :label="mt('Sync','ws')+'hosts'" name='syncHosts'>
<a-switch v-model:checked='formData.syncHosts' :disabled='true' />
</a-form-item>

<a-form-item :label="mt('Note')" name='note'>
<a-input v-model:value='formData.note' :maxlength='20'
:placeholder='t("defaultIsEmpty")' spellcheck='false' />
</a-form-item>
</a-form>

<div style='text-align: center'>
<a-button type='primary' @click='save'>{{t('Save')}}</a-button>
</div>
</template>

<script setup>
import { ref, inject, reactive } from 'vue'
import InputOpenDirDialog from '@/renderer/components/Input/InputOpenDirDialog.vue'
import Website from '@/main/core/website/Website'
import { message } from 'ant-design-vue'
import MessageBox from '@/renderer/utils/MessageBox'
import SoftwareExtend from '@/main/core/software/SoftwareExtend'
import Hosts from '@/main/utils/Hosts'
import { mt, t } from '@/shared/utils/i18n'
import { useMainStore } from '@/renderer/store'
const { confName, search } = inject('WebsiteProvide')
const store = useMainStore()
const formRef = ref();
const formData = reactive({})
const emits = defineEmits(['editAfter'])
const phpVersionList = ref([])
const labelColSpan = store.settings.Language === 'zh' ? 6 : 10;
const wrapperColSpan = store.settings.Language === 'zh' ? 18 : 14;
let websiteInfo
;(async () => {
websiteInfo = await Website.getBasicInfo(confName.value)
Object.assign(formData, websiteInfo)
const list = await SoftwareExtend.getPHPList()
phpVersionList.value = list.map(item => {
return { value: item.version, label: item.name }
})
phpVersionList.value.push({ value: '', label: t('Static') })
})()
const save = async () => {
try {
await formRef.value.validateFields()
} catch (errorInfo) {
console.log('Validate Failed:', errorInfo)
return
}
try {
await Website.saveBasicInfo(confName.value, formData)
message.info('保存成功')
search()
} catch (error) {
MessageBox.error(error.message ?? error, '保存出错!')
return
}
if (websiteInfo.syncHosts) {
const oldExtSerName = websiteInfo.extraServerName
const newExtSerName = formData.extraServerName
syncHosts(oldExtSerName, newExtSerName)
}
websiteInfo = JSON.parse(JSON.stringify(formData))
emits('editAfter', websiteInfo.phpVersion)
}
async function syncHosts(oldExtSerName, newExtSerName) {
try {
if (newExtSerName !== oldExtSerName) {
//删除旧的第二域名对应的hosts文件配置
if (oldExtSerName && !await Website.exists(oldExtSerName)) {
await Hosts.delete(oldExtSerName)
}
//增加新的第二域名对应的hosts文件配置
if (newExtSerName) {
await Hosts.add(newExtSerName)
}
}
} catch {
/* empty */
}
}
const extraServerNameChange = () => {
formData.extraServerName = formData.extraServerName?.trim()
}
const rootPathRules = [
{
required: true,
validator: async (_rule, value) => {
if (value.includes(' ')) {
return Promise.reject(t('pathCannotContainSpaces'))
}
return Promise.resolve()
}
}
]
</script>
<style scoped>
</style>
37 changes: 21 additions & 16 deletions src/renderer/views/Website.vue
Original file line number Diff line number Diff line change
Expand Up @@ -159,34 +159,40 @@ search();
const del = async (item) => {
try {
let options = {
content:t('areYouSure'),
content:t('Delete')+` ${item.serverName}:${item.port}`,
okText:t('Confirm'),
cancelText:t('Cancel'),
};
if (await MessageBox.confirm(options)) {
await Website.delete(item.confName);
}
} catch (error) {
} catch (error) {
MessageBox.error(error.message ?? error, '删除出错!');
return;
}
//// 会删除所有port的ServerName,需要优化
// if (item.syncHosts) {
// try {
// await Hosts.delete(item.serverName);
// //删除第二域名时,删除对应的hosts文件配置
// if (item.extraServerName) {
// await Hosts.delete(item.extraServerName);
// }
// } catch (error) {
// MessageBox.error(error.message ?? error, t('errorOccurredDuring', [mt('sync', 'ws') + 'hosts']))
// }
// }
if (item.syncHosts) {
const { serverName, extraServerName } = item
syncHosts(serverName, extraServerName)
}
search();
}
async function syncHosts(serverName, extraServerName) {
try {
if (!await Website.exists(serverName)) {
await Hosts.delete(serverName);
}
if (extraServerName && !await Website.exists(extraServerName)) {
await Hosts.delete(extraServerName);
}
} catch {
/* empty */
}
}
const showAdd = () => {
addModalVisible.value = true;
};
Expand Down Expand Up @@ -222,12 +228,11 @@ const openRootPath = (item) => {
.web-header {
display: flex;
justify-content: space-between;
//padding: 15px 15px;
}
:deep(td) {
height: 57px;
}
:deep(.ant-table-pagination) {
margin: 6px 0!important;
margin: 6px 10px !important;
}
</style>

0 comments on commit eae044d

Please sign in to comment.