feat: introducing streams management pages #166
parent
9c16b55dde
commit
2649b710bb
@ -0,0 +1,42 @@
|
||||
package streams
|
||||
|
||||
import (
|
||||
"github.com/0xJacky/Nginx-UI/api"
|
||||
"github.com/0xJacky/Nginx-UI/internal/nginx"
|
||||
"github.com/0xJacky/Nginx-UI/query"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func AdvancedEdit(c *gin.Context) {
|
||||
var json struct {
|
||||
Advanced bool `json:"advanced"`
|
||||
}
|
||||
|
||||
if !api.BindAndValid(c, &json) {
|
||||
return
|
||||
}
|
||||
|
||||
name := c.Param("name")
|
||||
path := nginx.GetConfPath("streams-available", name)
|
||||
|
||||
s := query.Site
|
||||
|
||||
_, err := s.Where(s.Path.Eq(path)).FirstOrCreate()
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = s.Where(s.Path.Eq(path)).Update(s.Advanced, json.Advanced)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
|
||||
}
|
||||
@ -0,0 +1,44 @@
|
||||
package streams
|
||||
|
||||
import (
|
||||
"github.com/0xJacky/Nginx-UI/api"
|
||||
"github.com/0xJacky/Nginx-UI/internal/helper"
|
||||
"github.com/0xJacky/Nginx-UI/internal/nginx"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Duplicate(c *gin.Context) {
|
||||
// Source name
|
||||
name := c.Param("name")
|
||||
|
||||
// Destination name
|
||||
var json struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
}
|
||||
|
||||
if !api.BindAndValid(c, &json) {
|
||||
return
|
||||
}
|
||||
|
||||
src := nginx.GetConfPath("streams-available", name)
|
||||
dst := nginx.GetConfPath("streams-available", json.Name)
|
||||
|
||||
if helper.FileExists(dst) {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "File exists",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
_, err := helper.CopyFile(src, dst)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"dst": dst,
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
package streams
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func InitRouter(r *gin.RouterGroup) {
|
||||
r.GET("streams", GetStreams)
|
||||
r.GET("stream/:name", GetStream)
|
||||
r.POST("stream/:name", SaveStream)
|
||||
r.POST("stream/:name/enable", EnableStream)
|
||||
r.POST("stream/:name/disable", DisableStream)
|
||||
r.POST("stream/:name/advance", AdvancedEdit)
|
||||
r.DELETE("stream/:name", DeleteStream)
|
||||
r.POST("stream/:name/duplicate", Duplicate)
|
||||
}
|
||||
@ -0,0 +1,343 @@
|
||||
package streams
|
||||
|
||||
import (
|
||||
"github.com/0xJacky/Nginx-UI/api"
|
||||
"github.com/0xJacky/Nginx-UI/internal/config"
|
||||
"github.com/0xJacky/Nginx-UI/internal/helper"
|
||||
"github.com/0xJacky/Nginx-UI/internal/nginx"
|
||||
"github.com/0xJacky/Nginx-UI/query"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sashabaranov/go-openai"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Stream struct {
|
||||
ModifiedAt time.Time `json:"modified_at"`
|
||||
Advanced bool `json:"advanced"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Name string `json:"name"`
|
||||
Config string `json:"config"`
|
||||
ChatGPTMessages []openai.ChatCompletionMessage `json:"chatgpt_messages,omitempty"`
|
||||
Tokenized *nginx.NgxConfig `json:"tokenized,omitempty"`
|
||||
}
|
||||
|
||||
func GetStreams(c *gin.Context) {
|
||||
name := c.Query("name")
|
||||
orderBy := c.Query("order_by")
|
||||
sort := c.DefaultQuery("sort", "desc")
|
||||
|
||||
configFiles, err := os.ReadDir(nginx.GetConfPath("streams-available"))
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
enabledConfig, err := os.ReadDir(nginx.GetConfPath("streams-enabled"))
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
enabledConfigMap := make(map[string]bool)
|
||||
for i := range enabledConfig {
|
||||
enabledConfigMap[enabledConfig[i].Name()] = true
|
||||
}
|
||||
|
||||
var configs []config.Config
|
||||
|
||||
for i := range configFiles {
|
||||
file := configFiles[i]
|
||||
fileInfo, _ := file.Info()
|
||||
if !file.IsDir() {
|
||||
if name != "" && !strings.Contains(file.Name(), name) {
|
||||
continue
|
||||
}
|
||||
configs = append(configs, config.Config{
|
||||
Name: file.Name(),
|
||||
ModifiedAt: fileInfo.ModTime(),
|
||||
Size: fileInfo.Size(),
|
||||
IsDir: fileInfo.IsDir(),
|
||||
Enabled: enabledConfigMap[file.Name()],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
configs = config.Sort(orderBy, sort, configs)
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"data": configs,
|
||||
})
|
||||
}
|
||||
|
||||
func GetStream(c *gin.Context) {
|
||||
rewriteName, ok := c.Get("rewriteConfigFileName")
|
||||
|
||||
name := c.Param("name")
|
||||
|
||||
// for modify filename
|
||||
if ok {
|
||||
name = rewriteName.(string)
|
||||
}
|
||||
|
||||
path := nginx.GetConfPath("streams-available", name)
|
||||
file, err := os.Stat(path)
|
||||
if os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"message": "file not found",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
enabled := true
|
||||
|
||||
if _, err := os.Stat(nginx.GetConfPath("streams-enabled", name)); os.IsNotExist(err) {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
s := query.Stream
|
||||
stream, err := s.Where(s.Path.Eq(path)).FirstOrInit()
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if stream.Advanced {
|
||||
origContent, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, Stream{
|
||||
ModifiedAt: file.ModTime(),
|
||||
Advanced: stream.Advanced,
|
||||
Enabled: enabled,
|
||||
Name: name,
|
||||
Config: string(origContent),
|
||||
ChatGPTMessages: stream.ChatGPTMessages,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("maybe_error", "nginx_config_syntax_error")
|
||||
nginxConfig, err := nginx.ParseNgxConfig(path)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("maybe_error", "nginx_config_syntax_error")
|
||||
|
||||
c.JSON(http.StatusOK, Stream{
|
||||
ModifiedAt: file.ModTime(),
|
||||
Advanced: stream.Advanced,
|
||||
Enabled: enabled,
|
||||
Name: name,
|
||||
Config: nginxConfig.FmtCode(),
|
||||
Tokenized: nginxConfig,
|
||||
ChatGPTMessages: stream.ChatGPTMessages,
|
||||
})
|
||||
}
|
||||
|
||||
func SaveStream(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
|
||||
if name == "" {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "param name is empty",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var json struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Content string `json:"content" binding:"required"`
|
||||
Overwrite bool `json:"overwrite"`
|
||||
}
|
||||
|
||||
if !api.BindAndValid(c, &json) {
|
||||
return
|
||||
}
|
||||
|
||||
path := nginx.GetConfPath("streams-available", name)
|
||||
|
||||
if !json.Overwrite && helper.FileExists(path) {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "File exists",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
err := os.WriteFile(path, []byte(json.Content), 0644)
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
enabledConfigFilePath := nginx.GetConfPath("streams-enabled", name)
|
||||
// rename the config file if needed
|
||||
if name != json.Name {
|
||||
newPath := nginx.GetConfPath("streams-available", json.Name)
|
||||
s := query.Stream
|
||||
_, err = s.Where(s.Path.Eq(path)).Update(s.Path, newPath)
|
||||
|
||||
// check if dst file exists, do not rename
|
||||
if helper.FileExists(newPath) {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "File exists",
|
||||
})
|
||||
return
|
||||
}
|
||||
// recreate a soft link
|
||||
if helper.FileExists(enabledConfigFilePath) {
|
||||
_ = os.Remove(enabledConfigFilePath)
|
||||
enabledConfigFilePath = nginx.GetConfPath("streams-enabled", json.Name)
|
||||
err = os.Symlink(newPath, enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
err = os.Rename(path, newPath)
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
name = json.Name
|
||||
c.Set("rewriteConfigFileName", name)
|
||||
}
|
||||
|
||||
enabledConfigFilePath = nginx.GetConfPath("streams-enabled", name)
|
||||
if helper.FileExists(enabledConfigFilePath) {
|
||||
// Test nginx configuration
|
||||
output := nginx.TestConf()
|
||||
|
||||
if nginx.GetLogLevel(output) > nginx.Warn {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
"error": "nginx_config_syntax_error",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
output = nginx.Reload()
|
||||
|
||||
if nginx.GetLogLevel(output) > nginx.Warn {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
GetStream(c)
|
||||
}
|
||||
|
||||
func EnableStream(c *gin.Context) {
|
||||
configFilePath := nginx.GetConfPath("streams-available", c.Param("name"))
|
||||
enabledConfigFilePath := nginx.GetConfPath("streams-enabled", c.Param("name"))
|
||||
|
||||
_, err := os.Stat(configFilePath)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = os.Stat(enabledConfigFilePath); os.IsNotExist(err) {
|
||||
err = os.Symlink(configFilePath, enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Test nginx config, if not pass, then disable the stream.
|
||||
output := nginx.TestConf()
|
||||
|
||||
if nginx.GetLogLevel(output) > nginx.Warn {
|
||||
_ = os.Remove(enabledConfigFilePath)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
output = nginx.Reload()
|
||||
|
||||
if nginx.GetLogLevel(output) > nginx.Warn {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
func DisableStream(c *gin.Context) {
|
||||
enabledConfigFilePath := nginx.GetConfPath("streams-enabled", c.Param("name"))
|
||||
|
||||
_, err := os.Stat(enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
err = os.Remove(enabledConfigFilePath)
|
||||
|
||||
if err != nil {
|
||||
api.ErrHandler(c, err)
|
||||
return
|
||||
}
|
||||
output := nginx.Reload()
|
||||
|
||||
if nginx.GetLogLevel(output) > nginx.Warn {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"message": output,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
func DeleteStream(c *gin.Context) {
|
||||
var err error
|
||||
name := c.Param("name")
|
||||
availablePath := nginx.GetConfPath("streams-available", name)
|
||||
enabledPath := nginx.GetConfPath("streams-enabled", name)
|
||||
|
||||
if _, err = os.Stat(availablePath); os.IsNotExist(err) {
|
||||
c.JSON(http.StatusNotFound, gin.H{
|
||||
"message": "stream not found",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if _, err = os.Stat(enabledPath); err == nil {
|
||||
c.JSON(http.StatusNotAcceptable, gin.H{
|
||||
"message": "stream is enabled",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "ok",
|
||||
})
|
||||
}
|
||||
@ -0,0 +1,37 @@
|
||||
import Curd from '@/api/curd'
|
||||
import http from '@/lib/http'
|
||||
import type { ChatComplicationMessage } from '@/api/openai'
|
||||
import type { NgxConfig } from '@/api/ngx'
|
||||
|
||||
export interface Stream {
|
||||
modified_at: string
|
||||
advanced: boolean
|
||||
enabled: boolean
|
||||
name: string
|
||||
config: string
|
||||
chatgpt_messages: ChatComplicationMessage[]
|
||||
tokenized?: NgxConfig
|
||||
}
|
||||
|
||||
class StreamCurd extends Curd<Stream> {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
enable(name: string, config?: any) {
|
||||
return http.post(`${this.baseUrl}/${name}/enable`, undefined, config)
|
||||
}
|
||||
|
||||
disable(name: string) {
|
||||
return http.post(`${this.baseUrl}/${name}/disable`)
|
||||
}
|
||||
|
||||
duplicate(name: string, data: { name: string }): Promise<{ dst: string }> {
|
||||
return http.post(`${this.baseUrl}/${name}/duplicate`, data)
|
||||
}
|
||||
|
||||
advance_mode(name: string, data: { advanced: boolean }) {
|
||||
return http.post(`${this.baseUrl}/${name}/advance`, data)
|
||||
}
|
||||
}
|
||||
|
||||
const stream = new StreamCurd('/stream')
|
||||
|
||||
export default stream
|
||||
Binary file not shown.
@ -0,0 +1,319 @@
|
||||
<script setup lang="ts">
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import { message } from 'ant-design-vue'
|
||||
import type { Ref } from 'vue'
|
||||
import FooterToolBar from '@/components/FooterToolbar/FooterToolBar.vue'
|
||||
import CodeEditor from '@/components/CodeEditor/CodeEditor.vue'
|
||||
|
||||
import NgxConfigEditor from '@/views/domain/ngx_conf/NgxConfigEditor.vue'
|
||||
import type { NgxConfig } from '@/api/ngx'
|
||||
import ngx from '@/api/ngx'
|
||||
import config from '@/api/config'
|
||||
import RightSettings from '@/views/stream/components/RightSettings.vue'
|
||||
import type { ChatComplicationMessage } from '@/api/openai'
|
||||
import type { Stream } from '@/api/stream'
|
||||
import stream from '@/api/stream'
|
||||
|
||||
const { $gettext, interpolate } = useGettext()
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const name = ref(route.params.name.toString())
|
||||
|
||||
watch(route, () => {
|
||||
name.value = route.params?.name?.toString() ?? ''
|
||||
})
|
||||
|
||||
const ngx_config: NgxConfig = reactive({
|
||||
name: '',
|
||||
upstreams: [],
|
||||
servers: [],
|
||||
})
|
||||
|
||||
const enabled = ref(false)
|
||||
const configText = ref('')
|
||||
const advance_mode_ref = ref(false)
|
||||
const saving = ref(false)
|
||||
const filename = ref('')
|
||||
const parse_error_status = ref(false)
|
||||
const parse_error_message = ref('')
|
||||
const data = ref({})
|
||||
|
||||
init()
|
||||
|
||||
const advance_mode = computed({
|
||||
get() {
|
||||
return advance_mode_ref.value || parse_error_status.value
|
||||
},
|
||||
set(v: boolean) {
|
||||
advance_mode_ref.value = v
|
||||
},
|
||||
})
|
||||
|
||||
const history_chatgpt_record = ref([]) as Ref<ChatComplicationMessage[]>
|
||||
|
||||
function handle_response(r: Stream) {
|
||||
if (r.advanced)
|
||||
advance_mode.value = true
|
||||
|
||||
if (r.advanced)
|
||||
advance_mode.value = true
|
||||
|
||||
parse_error_status.value = false
|
||||
parse_error_message.value = ''
|
||||
filename.value = r.name
|
||||
configText.value = r.config
|
||||
enabled.value = r.enabled
|
||||
history_chatgpt_record.value = r.chatgpt_messages
|
||||
data.value = r
|
||||
Object.assign(ngx_config, r.tokenized)
|
||||
}
|
||||
|
||||
function init() {
|
||||
if (name.value) {
|
||||
stream.get(name.value).then(r => {
|
||||
handle_response(r)
|
||||
}).catch(handle_parse_error)
|
||||
}
|
||||
else {
|
||||
history_chatgpt_record.value = []
|
||||
}
|
||||
}
|
||||
|
||||
function handle_parse_error(e: { error?: string; message: string }) {
|
||||
console.error(e)
|
||||
if (e?.error === 'nginx_config_syntax_error') {
|
||||
parse_error_status.value = true
|
||||
parse_error_message.value = e.message
|
||||
config.get(`streams-available/${name.value}`).then(r => {
|
||||
configText.value = r.content
|
||||
})
|
||||
}
|
||||
else {
|
||||
message.error($gettext(e?.message ?? 'Server error'))
|
||||
}
|
||||
}
|
||||
|
||||
function on_mode_change(advanced: boolean) {
|
||||
stream.advance_mode(name.value, { advanced }).then(() => {
|
||||
advance_mode.value = advanced
|
||||
if (advanced) {
|
||||
build_config()
|
||||
}
|
||||
else {
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
return ngx.tokenize_config(configText.value).then(r => {
|
||||
Object.assign(ngx_config, r)
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
}).catch(handle_parse_error)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function build_config() {
|
||||
return ngx.build_config(ngx_config).then(r => {
|
||||
configText.value = r.content
|
||||
})
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
saving.value = true
|
||||
|
||||
if (!advance_mode.value) {
|
||||
try {
|
||||
await build_config()
|
||||
}
|
||||
catch (e) {
|
||||
saving.value = false
|
||||
message.error($gettext('Failed to save, syntax error(s) was detected in the configuration.'))
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return stream.save(name.value, {
|
||||
name: filename.value || name.value,
|
||||
content: configText.value,
|
||||
overwrite: true,
|
||||
}).then(r => {
|
||||
handle_response(r)
|
||||
router.push({
|
||||
path: `/stream/${filename.value}`,
|
||||
query: route.query,
|
||||
})
|
||||
message.success($gettext('Saved successfully'))
|
||||
}).catch(handle_parse_error).finally(() => {
|
||||
saving.value = false
|
||||
})
|
||||
}
|
||||
|
||||
provide('save_config', save)
|
||||
provide('configText', configText)
|
||||
provide('ngx_config', ngx_config)
|
||||
provide('history_chatgpt_record', history_chatgpt_record)
|
||||
provide('enabled', enabled)
|
||||
provide('name', name)
|
||||
provide('filename', filename)
|
||||
provide('data', data)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ARow :gutter="16">
|
||||
<ACol
|
||||
:xs="24"
|
||||
:sm="24"
|
||||
:md="18"
|
||||
>
|
||||
<ACard :bordered="false">
|
||||
<template #title>
|
||||
<span style="margin-right: 10px">{{ interpolate($gettext('Edit %{n}'), { n: name }) }}</span>
|
||||
<ATag
|
||||
v-if="enabled"
|
||||
color="blue"
|
||||
>
|
||||
{{ $gettext('Enabled') }}
|
||||
</ATag>
|
||||
<ATag
|
||||
v-else
|
||||
color="orange"
|
||||
>
|
||||
{{ $gettext('Disabled') }}
|
||||
</ATag>
|
||||
</template>
|
||||
<template #extra>
|
||||
<div class="mode-switch">
|
||||
<div class="switch">
|
||||
<ASwitch
|
||||
size="small"
|
||||
:disabled="parse_error_status"
|
||||
:checked="advance_mode"
|
||||
@change="on_mode_change"
|
||||
/>
|
||||
</div>
|
||||
<template v-if="advance_mode">
|
||||
<div>{{ $gettext('Advance Mode') }}</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div>{{ $gettext('Basic Mode') }}</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Transition name="slide-fade">
|
||||
<div
|
||||
v-if="advance_mode"
|
||||
key="advance"
|
||||
>
|
||||
<div
|
||||
v-if="parse_error_status"
|
||||
class="parse-error-alert-wrapper"
|
||||
>
|
||||
<AAlert
|
||||
:message="$gettext('Nginx Configuration Parse Error')"
|
||||
:description="parse_error_message"
|
||||
type="error"
|
||||
show-icon
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<CodeEditor v-model:content="configText" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
key="basic"
|
||||
class="domain-edit-container"
|
||||
>
|
||||
<NgxConfigEditor
|
||||
:enabled="enabled"
|
||||
context="stream"
|
||||
@callback="save"
|
||||
/>
|
||||
</div>
|
||||
</Transition>
|
||||
</ACard>
|
||||
</ACol>
|
||||
|
||||
<ACol
|
||||
class="col-right"
|
||||
:xs="24"
|
||||
:sm="24"
|
||||
:md="6"
|
||||
>
|
||||
<RightSettings />
|
||||
</ACol>
|
||||
|
||||
<FooterToolBar>
|
||||
<ASpace>
|
||||
<AButton @click="$router.push('/streams')">
|
||||
{{ $gettext('Back') }}
|
||||
</AButton>
|
||||
<AButton
|
||||
type="primary"
|
||||
:loading="saving"
|
||||
@click="save"
|
||||
>
|
||||
{{ $gettext('Save') }}
|
||||
</AButton>
|
||||
</ASpace>
|
||||
</FooterToolBar>
|
||||
</ARow>
|
||||
</template>
|
||||
|
||||
<style lang="less">
|
||||
|
||||
</style>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.col-right {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ant-card {
|
||||
margin: 10px 0;
|
||||
box-shadow: unset;
|
||||
}
|
||||
|
||||
.mode-switch {
|
||||
display: flex;
|
||||
|
||||
.switch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-right: 5px;
|
||||
}
|
||||
}
|
||||
|
||||
.parse-error-alert-wrapper {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.domain-edit-container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.slide-fade-enter-active {
|
||||
transition: all .3s ease-in-out;
|
||||
}
|
||||
|
||||
.slide-fade-leave-active {
|
||||
transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
|
||||
}
|
||||
|
||||
.slide-fade-enter-from, .slide-fade-enter-to, .slide-fade-leave-to
|
||||
/* .slide-fade-leave-active for below version 2.1.8 */ {
|
||||
transform: translateX(10px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.directive-params-wrapper {
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.tab-content {
|
||||
padding: 10px;
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,203 @@
|
||||
<script setup lang="tsx">
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import { Badge, message } from 'ant-design-vue'
|
||||
import StdTable from '@/components/StdDesign/StdDataDisplay/StdTable.vue'
|
||||
import type { customRender } from '@/components/StdDesign/StdDataDisplay/StdTableTransformer'
|
||||
import { datetime } from '@/components/StdDesign/StdDataDisplay/StdTableTransformer'
|
||||
import stream from '@/api/stream'
|
||||
import { input } from '@/components/StdDesign/StdDataEntry'
|
||||
import InspectConfig from '@/views/config/InspectConfig.vue'
|
||||
import type { Column } from '@/components/StdDesign/types'
|
||||
import StreamDuplicate from '@/views/stream/components/StreamDuplicate.vue'
|
||||
|
||||
const { $gettext } = useGettext()
|
||||
|
||||
const columns: Column[] = [{
|
||||
title: () => $gettext('Name'),
|
||||
dataIndex: 'name',
|
||||
sortable: true,
|
||||
pithy: true,
|
||||
edit: {
|
||||
type: input,
|
||||
},
|
||||
search: true,
|
||||
}, {
|
||||
title: () => $gettext('Status'),
|
||||
dataIndex: 'enabled',
|
||||
customRender: (args: customRender) => {
|
||||
const template = []
|
||||
const { text } = args
|
||||
if (text === true || text > 0) {
|
||||
template.push(<Badge status="success"/>)
|
||||
template.push($gettext('Enabled'))
|
||||
}
|
||||
else {
|
||||
template.push(<Badge status="warning"/>)
|
||||
template.push($gettext('Disabled'))
|
||||
}
|
||||
|
||||
return h('div', template)
|
||||
},
|
||||
sortable: true,
|
||||
pithy: true,
|
||||
}, {
|
||||
title: () => $gettext('Updated at'),
|
||||
dataIndex: 'modified_at',
|
||||
customRender: datetime,
|
||||
sortable: true,
|
||||
pithy: true,
|
||||
}, {
|
||||
title: () => $gettext('Action'),
|
||||
dataIndex: 'action',
|
||||
}]
|
||||
|
||||
const table = ref()
|
||||
|
||||
const inspect_config = ref()
|
||||
|
||||
function enable(name: string) {
|
||||
stream.enable(name).then(() => {
|
||||
message.success($gettext('Enabled successfully'))
|
||||
table.value?.get_list()
|
||||
inspect_config.value?.test()
|
||||
}).catch(r => {
|
||||
message.error($gettext('Failed to enable %{msg}', { msg: r.message ?? '' }), 10)
|
||||
})
|
||||
}
|
||||
|
||||
function disable(name: string) {
|
||||
stream.disable(name).then(() => {
|
||||
message.success($gettext('Disabled successfully'))
|
||||
table.value?.get_list()
|
||||
inspect_config.value?.test()
|
||||
}).catch(r => {
|
||||
message.error($gettext('Failed to disable %{msg}', { msg: r.message ?? '' }))
|
||||
})
|
||||
}
|
||||
|
||||
function destroy(stream_name: string) {
|
||||
stream.destroy(stream_name).then(() => {
|
||||
table.value.get_list()
|
||||
message.success($gettext('Delete stream: %{stream_name}', { stream_name }))
|
||||
inspect_config.value?.test()
|
||||
}).catch(e => {
|
||||
message.error(e?.message ?? $gettext('Server error'))
|
||||
})
|
||||
}
|
||||
|
||||
const showDuplicator = ref(false)
|
||||
|
||||
const target = ref('')
|
||||
|
||||
function handle_click_duplicate(name: string) {
|
||||
showDuplicator.value = true
|
||||
target.value = name
|
||||
}
|
||||
|
||||
const route = useRoute()
|
||||
|
||||
watch(route, () => {
|
||||
inspect_config.value?.test()
|
||||
})
|
||||
|
||||
const showAddStream = ref(false)
|
||||
const name = ref('')
|
||||
function add() {
|
||||
showAddStream.value = true
|
||||
name.value = ''
|
||||
}
|
||||
|
||||
function handleAddStream() {
|
||||
stream.save(name.value, { name: name.value, content: 'server\t{\n\n}' }).then(() => {
|
||||
showAddStream.value = false
|
||||
table.value?.get_list()
|
||||
message.success($gettext('Added successfully'))
|
||||
}).catch(e => {
|
||||
message.error(e?.message ?? $gettext('Server error'))
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ACard :title="$gettext('Manage Streams')">
|
||||
<template #extra>
|
||||
<a @click="add">{{ $gettext('Add') }}</a>
|
||||
</template>
|
||||
|
||||
<InspectConfig ref="inspect_config" />
|
||||
|
||||
<StdTable
|
||||
ref="table"
|
||||
:api="stream"
|
||||
:columns="columns"
|
||||
row-key="name"
|
||||
disable-delete
|
||||
@click-edit="r => $router.push({
|
||||
path: `/stream/${r}`,
|
||||
})"
|
||||
>
|
||||
<template #actions="{ record }">
|
||||
<AButton
|
||||
v-if="record.enabled"
|
||||
type="link"
|
||||
size="small"
|
||||
@click="disable(record.name)"
|
||||
>
|
||||
{{ $gettext('Disable') }}
|
||||
</AButton>
|
||||
<AButton
|
||||
v-else
|
||||
type="link"
|
||||
size="small"
|
||||
@click="enable(record.name)"
|
||||
>
|
||||
{{ $gettext('Enable') }}
|
||||
</AButton>
|
||||
<ADivider type="vertical" />
|
||||
<AButton
|
||||
type="link"
|
||||
size="small"
|
||||
@click="handle_click_duplicate(record.name)"
|
||||
>
|
||||
{{ $gettext('Duplicate') }}
|
||||
</AButton>
|
||||
<ADivider type="vertical" />
|
||||
<APopconfirm
|
||||
:cancel-text="$gettext('No')"
|
||||
:ok-text="$gettext('OK')"
|
||||
:title="$gettext('Are you sure you want to delete?')"
|
||||
:disabled="record.enabled"
|
||||
@confirm="destroy(record.name)"
|
||||
>
|
||||
<AButton
|
||||
type="link"
|
||||
size="small"
|
||||
:disabled="record.enabled"
|
||||
>
|
||||
{{ $gettext('Delete') }}
|
||||
</AButton>
|
||||
</APopconfirm>
|
||||
</template>
|
||||
</StdTable>
|
||||
<AModal
|
||||
v-model:open="showAddStream"
|
||||
:title="$gettext('Add Stream')"
|
||||
@ok="handleAddStream"
|
||||
>
|
||||
<AForm layout="vertical">
|
||||
<AFormItem :label="$gettext('Name')">
|
||||
<AInput v-model:value="name" />
|
||||
</AFormItem>
|
||||
</AForm>
|
||||
</AModal>
|
||||
<StreamDuplicate
|
||||
v-model:visible="showDuplicator"
|
||||
:name="target"
|
||||
@duplicated="() => table.get_list()"
|
||||
/>
|
||||
</ACard>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
|
||||
</style>
|
||||
@ -0,0 +1,129 @@
|
||||
<script setup lang="ts">
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import { InfoCircleOutlined } from '@ant-design/icons-vue'
|
||||
import { Modal, notification } from 'ant-design-vue'
|
||||
import type { Ref } from 'vue'
|
||||
import stream from '@/api/stream'
|
||||
import NodeSelector from '@/components/NodeSelector/NodeSelector.vue'
|
||||
|
||||
const { $gettext, $ngettext } = useGettext()
|
||||
|
||||
const node_map = reactive({})
|
||||
const target = ref([])
|
||||
const overwrite = ref(false)
|
||||
const enabled = ref(false)
|
||||
const name = inject('name') as Ref<string>
|
||||
const [modal, ContextHolder] = Modal.useModal()
|
||||
function deploy() {
|
||||
modal.confirm({
|
||||
title: () => $ngettext('Do you want to deploy this file to remote server?',
|
||||
'Do you want to deploy this file to remote servers?', target.value.length),
|
||||
mask: false,
|
||||
centered: true,
|
||||
okText: $gettext('OK'),
|
||||
cancelText: $gettext('Cancel'),
|
||||
onOk() {
|
||||
target.value.forEach(id => {
|
||||
const node_name = node_map[id]
|
||||
|
||||
// get source content
|
||||
stream.get(name.value).then(r => {
|
||||
stream.save(name.value, {
|
||||
name: name.value,
|
||||
content: r.config,
|
||||
overwrite: overwrite.value,
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
}, { headers: { 'X-Node-ID': id } }).then(async () => {
|
||||
notification.success({
|
||||
message: $gettext('Deploy successfully'),
|
||||
description:
|
||||
$gettext('Deploy %{conf_name} to %{node_name} successfully',
|
||||
{ conf_name: name.value, node_name }),
|
||||
})
|
||||
if (enabled.value) {
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
stream.enable(name.value).then(() => {
|
||||
notification.success({
|
||||
message: $gettext('Enable successfully'),
|
||||
description:
|
||||
$gettext('Enable %{conf_name} in %{node_name} successfully',
|
||||
{ conf_name: name.value, node_name }),
|
||||
})
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
}).catch(e => {
|
||||
notification.error({
|
||||
message: $gettext('Enable %{conf_name} in %{node_name} failed', {
|
||||
conf_name: name.value,
|
||||
node_name,
|
||||
}),
|
||||
description: $gettext(e?.message ?? 'Server error'),
|
||||
})
|
||||
})
|
||||
}
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
}).catch(e => {
|
||||
notification.error({
|
||||
message: $gettext('Deploy %{conf_name} to %{node_name} failed', {
|
||||
conf_name: name.value,
|
||||
node_name,
|
||||
}),
|
||||
description: $gettext(e?.message ?? 'Server error'),
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ContextHolder />
|
||||
<NodeSelector
|
||||
v-model:target="target"
|
||||
hidden-local
|
||||
:map="node_map"
|
||||
/>
|
||||
<div class="node-deploy-control">
|
||||
<ACheckbox v-model:checked="enabled">
|
||||
{{ $gettext('Enable') }}
|
||||
</ACheckbox>
|
||||
<div class="overwrite">
|
||||
<ACheckbox v-model:checked="overwrite">
|
||||
{{ $gettext('Overwrite') }}
|
||||
</ACheckbox>
|
||||
<ATooltip placement="bottom">
|
||||
<template #title>
|
||||
{{ $gettext('Overwrite exist file') }}
|
||||
</template>
|
||||
<InfoCircleOutlined />
|
||||
</ATooltip>
|
||||
</div>
|
||||
|
||||
<AButton
|
||||
:disabled="target.length === 0"
|
||||
type="primary"
|
||||
ghost
|
||||
@click="deploy"
|
||||
>
|
||||
{{ $gettext('Deploy') }}
|
||||
</AButton>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.overwrite {
|
||||
margin-right: 15px;
|
||||
|
||||
span {
|
||||
color: #9b9b9b;
|
||||
}
|
||||
}
|
||||
|
||||
.node-deploy-control {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 10px;
|
||||
align-items: center;
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,130 @@
|
||||
<script setup lang="ts">
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import { Modal, message } from 'ant-design-vue'
|
||||
import type { Ref } from 'vue'
|
||||
import type { Stream } from '@/api/stream'
|
||||
import stream from '@/api/stream'
|
||||
import ChatGPT from '@/components/ChatGPT/ChatGPT.vue'
|
||||
import { formatDateTime } from '@/lib/helper'
|
||||
import Deploy from '@/views/stream/components/Deploy.vue'
|
||||
import { useSettingsStore } from '@/pinia'
|
||||
import type { ChatComplicationMessage } from '@/api/openai'
|
||||
import type { NgxConfig } from '@/api/ngx'
|
||||
|
||||
const settings = useSettingsStore()
|
||||
const { $gettext } = useGettext()
|
||||
const configText = inject('configText') as Ref<string>
|
||||
const ngx_config = inject('ngx_config') as Ref<NgxConfig>
|
||||
const enabled = inject('enabled') as Ref<boolean>
|
||||
const name = inject('name') as Ref<string>
|
||||
const history_chatgpt_record = inject('history_chatgpt_record') as Ref<ChatComplicationMessage[]>
|
||||
const filename = inject('filename')
|
||||
const data = inject('data') as Ref<Stream>
|
||||
|
||||
const [modal, ContextHolder] = Modal.useModal()
|
||||
|
||||
const active_key = ref(['1', '2', '3'])
|
||||
|
||||
function enable() {
|
||||
stream.enable(name.value).then(() => {
|
||||
message.success($gettext('Enabled successfully'))
|
||||
enabled.value = true
|
||||
}).catch(r => {
|
||||
message.error($gettext('Failed to enable %{msg}', { msg: r.message ?? '' }), 10)
|
||||
})
|
||||
}
|
||||
|
||||
function disable() {
|
||||
stream.disable(name.value).then(() => {
|
||||
message.success($gettext('Disabled successfully'))
|
||||
enabled.value = false
|
||||
}).catch(r => {
|
||||
message.error($gettext('Failed to disable %{msg}', { msg: r.message ?? '' }))
|
||||
})
|
||||
}
|
||||
|
||||
function on_change_enabled(checked: boolean) {
|
||||
modal.confirm({
|
||||
title: checked ? $gettext('Do you want to enable this stream?') : $gettext('Do you want to disable this stream?'),
|
||||
mask: false,
|
||||
centered: true,
|
||||
okText: $gettext('OK'),
|
||||
cancelText: $gettext('Cancel'),
|
||||
async onOk() {
|
||||
if (checked)
|
||||
enable()
|
||||
else
|
||||
disable()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ACard
|
||||
class="right-settings"
|
||||
:bordered="false"
|
||||
>
|
||||
<ContextHolder />
|
||||
<ACollapse
|
||||
v-model:activeKey="active_key"
|
||||
ghost
|
||||
>
|
||||
<ACollapsePanel
|
||||
key="1"
|
||||
:header="$gettext('Basic')"
|
||||
>
|
||||
<AFormItem :label="$gettext('Enabled')">
|
||||
<ASwitch
|
||||
:checked="enabled"
|
||||
@change="on_change_enabled"
|
||||
/>
|
||||
</AFormItem>
|
||||
<AFormItem :label="$gettext('Name')">
|
||||
<AInput v-model:value="filename" />
|
||||
</AFormItem>
|
||||
<AFormItem :label="$gettext('Updated at')">
|
||||
{{ formatDateTime(data.modified_at) }}
|
||||
</AFormItem>
|
||||
</ACollapsePanel>
|
||||
<ACollapsePanel
|
||||
v-if="!settings.is_remote"
|
||||
key="2"
|
||||
:header="$gettext('Deploy')"
|
||||
>
|
||||
<Deploy />
|
||||
</ACollapsePanel>
|
||||
<ACollapsePanel
|
||||
key="3"
|
||||
header="ChatGPT"
|
||||
>
|
||||
<ChatGPT
|
||||
v-model:history-messages="history_chatgpt_record"
|
||||
:content="configText"
|
||||
:path="ngx_config.file_name"
|
||||
/>
|
||||
</ACollapsePanel>
|
||||
</ACollapse>
|
||||
</ACard>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.right-settings {
|
||||
position: sticky;
|
||||
top: 78px;
|
||||
|
||||
:deep(.ant-card-body) {
|
||||
max-height: 100vh;
|
||||
overflow-y: scroll;
|
||||
}
|
||||
}
|
||||
|
||||
:deep(.ant-collapse-ghost > .ant-collapse-item > .ant-collapse-content > .ant-collapse-content-box) {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
:deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header) {
|
||||
padding: 0 0 10px 0;
|
||||
}
|
||||
</style>
|
||||
@ -0,0 +1,156 @@
|
||||
<script setup lang="ts">
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import { Form, message, notification } from 'ant-design-vue'
|
||||
import gettext from '@/gettext'
|
||||
import stream from '@/api/stream'
|
||||
import NodeSelector from '@/components/NodeSelector/NodeSelector.vue'
|
||||
import { useSettingsStore } from '@/pinia'
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean
|
||||
name: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits(['update:visible', 'duplicated'])
|
||||
|
||||
const { $gettext } = useGettext()
|
||||
|
||||
const settings = useSettingsStore()
|
||||
|
||||
const show = computed({
|
||||
get() {
|
||||
return props.visible
|
||||
},
|
||||
set(v) {
|
||||
emit('update:visible', v)
|
||||
},
|
||||
})
|
||||
|
||||
interface Model {
|
||||
name: string // site name
|
||||
target: number[] // ids of deploy targets
|
||||
}
|
||||
|
||||
const modelRef: Model = reactive({ name: '', target: [] })
|
||||
|
||||
const rulesRef = reactive({
|
||||
name: [
|
||||
{
|
||||
required: true,
|
||||
message: () => $gettext('Please input name, '
|
||||
+ 'this will be used as the filename of the new configuration!'),
|
||||
},
|
||||
],
|
||||
target: [
|
||||
{
|
||||
required: true,
|
||||
message: () => $gettext('Please select at least one node!'),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const { validate, validateInfos, clearValidate } = Form.useForm(modelRef, rulesRef)
|
||||
|
||||
const loading = ref(false)
|
||||
|
||||
const node_map: Record<number, string> = reactive({})
|
||||
|
||||
function onSubmit() {
|
||||
validate().then(async () => {
|
||||
loading.value = true
|
||||
|
||||
modelRef.target.forEach(id => {
|
||||
if (id === 0) {
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
stream.duplicate(props.name, { name: modelRef.name }).then(() => {
|
||||
message.success($gettext('Duplicate to local successfully'))
|
||||
show.value = false
|
||||
emit('duplicated')
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
}).catch(e => {
|
||||
message.error($gettext(e?.message ?? 'Server error'))
|
||||
})
|
||||
}
|
||||
else {
|
||||
// get source content
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
stream.get(props.name).then(r => {
|
||||
stream.save(modelRef.name, {
|
||||
name: modelRef.name,
|
||||
content: r.config,
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
}, { headers: { 'X-Node-ID': id } }).then(() => {
|
||||
notification.success({
|
||||
message: $gettext('Duplicate successfully'),
|
||||
description:
|
||||
$gettext('Duplicate %{conf_name} to %{node_name} successfully',
|
||||
{ conf_name: props.name, node_name: node_map[id] }),
|
||||
})
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
}).catch(e => {
|
||||
notification.error({
|
||||
message: $gettext('Duplicate failed'),
|
||||
description: $gettext(e?.message ?? 'Server error'),
|
||||
})
|
||||
})
|
||||
if (r.enabled) {
|
||||
// eslint-disable-next-line promise/no-nesting
|
||||
stream.enable(modelRef.name, { headers: { 'X-Node-ID': id } }).then(() => {
|
||||
notification.success({
|
||||
message: $gettext('Enabled successfully'),
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
loading.value = false
|
||||
})
|
||||
}
|
||||
|
||||
watch(() => props.visible, v => {
|
||||
if (v) {
|
||||
modelRef.name = props.name // default with source name
|
||||
modelRef.target = [0]
|
||||
nextTick(() => clearValidate())
|
||||
}
|
||||
})
|
||||
|
||||
watch(() => gettext.current, () => {
|
||||
clearValidate()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<AModal
|
||||
v-model:open="show"
|
||||
:title="$gettext('Duplicate')"
|
||||
:confirm-loading="loading"
|
||||
:mask="null"
|
||||
@ok="onSubmit"
|
||||
>
|
||||
<AForm layout="vertical">
|
||||
<AFormItem
|
||||
:label="$gettext('Name')"
|
||||
v-bind="validateInfos.name"
|
||||
>
|
||||
<AInput v-model:value="modelRef.name" />
|
||||
</AFormItem>
|
||||
<AFormItem
|
||||
v-if="!settings.is_remote"
|
||||
:label="$gettext('Target')"
|
||||
v-bind="validateInfos.target"
|
||||
>
|
||||
<NodeSelector
|
||||
v-model:target="modelRef.target"
|
||||
:map="node_map"
|
||||
/>
|
||||
</AFormItem>
|
||||
</AForm>
|
||||
</AModal>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped>
|
||||
|
||||
</style>
|
||||
@ -1,35 +1,35 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/sashabaranov/go-openai"
|
||||
"database/sql/driver"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
type JSON []openai.ChatCompletionMessage
|
||||
type ChatGPTCompletionMessages []openai.ChatCompletionMessage
|
||||
|
||||
// Scan scan value into Jsonb, implements sql.Scanner interface
|
||||
func (j *JSON) Scan(value interface{}) error {
|
||||
bytes, ok := value.([]byte)
|
||||
if !ok {
|
||||
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
|
||||
}
|
||||
// Scan value into Jsonb, implements sql.Scanner interface
|
||||
func (j *ChatGPTCompletionMessages) Scan(value interface{}) error {
|
||||
bytes, ok := value.([]byte)
|
||||
if !ok {
|
||||
return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
|
||||
}
|
||||
|
||||
result := make([]openai.ChatCompletionMessage, 0)
|
||||
err := json.Unmarshal(bytes, &result)
|
||||
*j = result
|
||||
result := make([]openai.ChatCompletionMessage, 0)
|
||||
err := json.Unmarshal(bytes, &result)
|
||||
*j = result
|
||||
|
||||
return err
|
||||
return err
|
||||
}
|
||||
|
||||
// Value return json value, implement driver.Valuer interface
|
||||
func (j *JSON) Value() (driver.Value, error) {
|
||||
return json.Marshal(*j)
|
||||
func (j *ChatGPTCompletionMessages) Value() (driver.Value, error) {
|
||||
return json.Marshal(*j)
|
||||
}
|
||||
|
||||
type ChatGPTLog struct {
|
||||
Name string `json:"name"`
|
||||
Content JSON `json:"content" gorm:"serializer:json"`
|
||||
Name string `json:"name"`
|
||||
Content ChatGPTCompletionMessages `json:"content" gorm:"serializer:json"`
|
||||
}
|
||||
|
||||
@ -0,0 +1,8 @@
|
||||
package model
|
||||
|
||||
type Stream struct {
|
||||
Model
|
||||
Path string `json:"path"`
|
||||
Advanced bool `json:"advanced"`
|
||||
ChatGPTMessages ChatGPTCompletionMessages `json:"chatgpt_messages" gorm:"serializer:json"`
|
||||
}
|
||||
@ -0,0 +1,374 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"github.com/0xJacky/Nginx-UI/model"
|
||||
)
|
||||
|
||||
func newStream(db *gorm.DB, opts ...gen.DOOption) stream {
|
||||
_stream := stream{}
|
||||
|
||||
_stream.streamDo.UseDB(db, opts...)
|
||||
_stream.streamDo.UseModel(&model.Stream{})
|
||||
|
||||
tableName := _stream.streamDo.TableName()
|
||||
_stream.ALL = field.NewAsterisk(tableName)
|
||||
_stream.ID = field.NewInt(tableName, "id")
|
||||
_stream.CreatedAt = field.NewTime(tableName, "created_at")
|
||||
_stream.UpdatedAt = field.NewTime(tableName, "updated_at")
|
||||
_stream.DeletedAt = field.NewField(tableName, "deleted_at")
|
||||
_stream.Path = field.NewString(tableName, "path")
|
||||
_stream.Advanced = field.NewBool(tableName, "advanced")
|
||||
_stream.ChatGPTMessages = field.NewField(tableName, "chat_gpt_messages")
|
||||
|
||||
_stream.fillFieldMap()
|
||||
|
||||
return _stream
|
||||
}
|
||||
|
||||
type stream struct {
|
||||
streamDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ID field.Int
|
||||
CreatedAt field.Time
|
||||
UpdatedAt field.Time
|
||||
DeletedAt field.Field
|
||||
Path field.String
|
||||
Advanced field.Bool
|
||||
ChatGPTMessages field.Field
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (s stream) Table(newTableName string) *stream {
|
||||
s.streamDo.UseTable(newTableName)
|
||||
return s.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (s stream) As(alias string) *stream {
|
||||
s.streamDo.DO = *(s.streamDo.As(alias).(*gen.DO))
|
||||
return s.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (s *stream) updateTableName(table string) *stream {
|
||||
s.ALL = field.NewAsterisk(table)
|
||||
s.ID = field.NewInt(table, "id")
|
||||
s.CreatedAt = field.NewTime(table, "created_at")
|
||||
s.UpdatedAt = field.NewTime(table, "updated_at")
|
||||
s.DeletedAt = field.NewField(table, "deleted_at")
|
||||
s.Path = field.NewString(table, "path")
|
||||
s.Advanced = field.NewBool(table, "advanced")
|
||||
s.ChatGPTMessages = field.NewField(table, "chat_gpt_messages")
|
||||
|
||||
s.fillFieldMap()
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *stream) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := s.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (s *stream) fillFieldMap() {
|
||||
s.fieldMap = make(map[string]field.Expr, 7)
|
||||
s.fieldMap["id"] = s.ID
|
||||
s.fieldMap["created_at"] = s.CreatedAt
|
||||
s.fieldMap["updated_at"] = s.UpdatedAt
|
||||
s.fieldMap["deleted_at"] = s.DeletedAt
|
||||
s.fieldMap["path"] = s.Path
|
||||
s.fieldMap["advanced"] = s.Advanced
|
||||
s.fieldMap["chat_gpt_messages"] = s.ChatGPTMessages
|
||||
}
|
||||
|
||||
func (s stream) clone(db *gorm.DB) stream {
|
||||
s.streamDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s stream) replaceDB(db *gorm.DB) stream {
|
||||
s.streamDo.ReplaceDB(db)
|
||||
return s
|
||||
}
|
||||
|
||||
type streamDo struct{ gen.DO }
|
||||
|
||||
// FirstByID Where("id=@id")
|
||||
func (s streamDo) FirstByID(id int) (result *model.Stream, err error) {
|
||||
var params []interface{}
|
||||
|
||||
var generateSQL strings.Builder
|
||||
params = append(params, id)
|
||||
generateSQL.WriteString("id=? ")
|
||||
|
||||
var executeSQL *gorm.DB
|
||||
executeSQL = s.UnderlyingDB().Where(generateSQL.String(), params...).Take(&result) // ignore_security_alert
|
||||
err = executeSQL.Error
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteByID update @@table set deleted_at=strftime('%Y-%m-%d %H:%M:%S','now') where id=@id
|
||||
func (s streamDo) DeleteByID(id int) (err error) {
|
||||
var params []interface{}
|
||||
|
||||
var generateSQL strings.Builder
|
||||
params = append(params, id)
|
||||
generateSQL.WriteString("update streams set deleted_at=strftime('%Y-%m-%d %H:%M:%S','now') where id=? ")
|
||||
|
||||
var executeSQL *gorm.DB
|
||||
executeSQL = s.UnderlyingDB().Exec(generateSQL.String(), params...) // ignore_security_alert
|
||||
err = executeSQL.Error
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (s streamDo) Debug() *streamDo {
|
||||
return s.withDO(s.DO.Debug())
|
||||
}
|
||||
|
||||
func (s streamDo) WithContext(ctx context.Context) *streamDo {
|
||||
return s.withDO(s.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (s streamDo) ReadDB() *streamDo {
|
||||
return s.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (s streamDo) WriteDB() *streamDo {
|
||||
return s.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (s streamDo) Session(config *gorm.Session) *streamDo {
|
||||
return s.withDO(s.DO.Session(config))
|
||||
}
|
||||
|
||||
func (s streamDo) Clauses(conds ...clause.Expression) *streamDo {
|
||||
return s.withDO(s.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (s streamDo) Returning(value interface{}, columns ...string) *streamDo {
|
||||
return s.withDO(s.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (s streamDo) Not(conds ...gen.Condition) *streamDo {
|
||||
return s.withDO(s.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (s streamDo) Or(conds ...gen.Condition) *streamDo {
|
||||
return s.withDO(s.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (s streamDo) Select(conds ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (s streamDo) Where(conds ...gen.Condition) *streamDo {
|
||||
return s.withDO(s.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (s streamDo) Order(conds ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (s streamDo) Distinct(cols ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (s streamDo) Omit(cols ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (s streamDo) Join(table schema.Tabler, on ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (s streamDo) LeftJoin(table schema.Tabler, on ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (s streamDo) RightJoin(table schema.Tabler, on ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (s streamDo) Group(cols ...field.Expr) *streamDo {
|
||||
return s.withDO(s.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (s streamDo) Having(conds ...gen.Condition) *streamDo {
|
||||
return s.withDO(s.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (s streamDo) Limit(limit int) *streamDo {
|
||||
return s.withDO(s.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (s streamDo) Offset(offset int) *streamDo {
|
||||
return s.withDO(s.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (s streamDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *streamDo {
|
||||
return s.withDO(s.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (s streamDo) Unscoped() *streamDo {
|
||||
return s.withDO(s.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (s streamDo) Create(values ...*model.Stream) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.DO.Create(values)
|
||||
}
|
||||
|
||||
func (s streamDo) CreateInBatches(values []*model.Stream, batchSize int) error {
|
||||
return s.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (s streamDo) Save(values ...*model.Stream) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.DO.Save(values)
|
||||
}
|
||||
|
||||
func (s streamDo) First() (*model.Stream, error) {
|
||||
if result, err := s.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.Stream), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s streamDo) Take() (*model.Stream, error) {
|
||||
if result, err := s.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.Stream), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s streamDo) Last() (*model.Stream, error) {
|
||||
if result, err := s.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.Stream), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s streamDo) Find() ([]*model.Stream, error) {
|
||||
result, err := s.DO.Find()
|
||||
return result.([]*model.Stream), err
|
||||
}
|
||||
|
||||
func (s streamDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*model.Stream, err error) {
|
||||
buf := make([]*model.Stream, 0, batchSize)
|
||||
err = s.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (s streamDo) FindInBatches(result *[]*model.Stream, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return s.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (s streamDo) Attrs(attrs ...field.AssignExpr) *streamDo {
|
||||
return s.withDO(s.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (s streamDo) Assign(attrs ...field.AssignExpr) *streamDo {
|
||||
return s.withDO(s.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (s streamDo) Joins(fields ...field.RelationField) *streamDo {
|
||||
for _, _f := range fields {
|
||||
s = *s.withDO(s.DO.Joins(_f))
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
func (s streamDo) Preload(fields ...field.RelationField) *streamDo {
|
||||
for _, _f := range fields {
|
||||
s = *s.withDO(s.DO.Preload(_f))
|
||||
}
|
||||
return &s
|
||||
}
|
||||
|
||||
func (s streamDo) FirstOrInit() (*model.Stream, error) {
|
||||
if result, err := s.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.Stream), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s streamDo) FirstOrCreate() (*model.Stream, error) {
|
||||
if result, err := s.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*model.Stream), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s streamDo) FindByPage(offset int, limit int) (result []*model.Stream, count int64, err error) {
|
||||
result, err = s.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = s.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (s streamDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = s.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = s.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (s streamDo) Scan(result interface{}) (err error) {
|
||||
return s.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (s streamDo) Delete(models ...*model.Stream) (result gen.ResultInfo, err error) {
|
||||
return s.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (s *streamDo) withDO(do gen.Dao) *streamDo {
|
||||
s.DO = *do.(*gen.DO)
|
||||
return s
|
||||
}
|
||||
Loading…
Reference in New Issue