add convert json to toml by toml.js

This commit is contained in:
2023-12-29 19:31:55 +08:00
parent 91c15936ee
commit 83ad03eca3
7 changed files with 8590 additions and 171 deletions

View File

@@ -16,6 +16,21 @@ var loadClientInfo = (function ($) {
type: 'none' type: 'none'
}).done(function (result) { }).done(function (result) {
if (result.success) { if (result.success) {
var proxies = [];
result.data.proxies.forEach(function (proxy){
var items = flatJSON(proxy.ProxyConfigurer);
proxies.push(expandJSON(items))
})
var visitors = [];
result.data.visitors.forEach(function (visitor){
var items = flatJSON(visitor.VisitorConfigurer);
visitors.push(expandJSON(items))
})
var newD = $.extend({},result.data,true);
newD.proxies = proxies;
newD.visitors = visitors;
console.log(TOML.stringify(newD))
renderClientInfo(result.data); renderClientInfo(result.data);
} else { } else {
layui.layer.msg(result.message); layui.layer.msg(result.message);

View File

@@ -1,120 +1,5 @@
var loadProxyInfo = (function ($) { var loadProxyInfo = (function ($) {
var i18n = {}, currentProxyType, currentTitle; var i18n = {}, currentProxyType, currentTitle;
//param names in Basic tab
var basicParams = [
{
name: 'name',
defaultValue: '-'
}, {
name: 'type',
defaultValue: '-'
}, {
name: 'localIP',
defaultValue: '-'
}, {
name: 'localPort',
defaultValue: '-'
}, {
name: 'customDomains',
defaultValue: '-'
}, {
name: 'subdomain',
defaultValue: '-'
}, {
name: 'remotePort',
defaultValue: '-'
}, {
name: 'transport.useEncryption',
defaultValue: 'true',
}, {
name: 'transport.useCompression',
defaultValue: 'true',
}
];
/**
* a.b.c = 1
* a.b.d = [2,3]
* to
* {a: {
* b: {
* c: 1
* d: "[2,3]"
* }
* }
* }
*
* @param obj json object
* @param names all names split from name string like 'a.b.c'
* @param value default value
*/
function expandJSON(obj, names, value) {
var currentIndex = this.index || 0;
var childrenIndex = (currentIndex + 1) > names.length ? null : (currentIndex + 1);
var currentName = names[currentIndex], currentValue = {};
var childrenName = childrenIndex == null ? null : names[childrenIndex];
if (obj.hasOwnProperty(currentName)) {
currentValue = obj[currentName];
} else {
obj[currentName] = currentValue;
}
if (childrenName !== null) {
this.index = childrenIndex;
expandJSON(currentValue, names, value);
} else {
if (value != null) {
if (Array.isArray(value)) {
obj[currentName] = JSON.stringify(value);
} else {
obj[currentName] = value;
}
}
this.index = 0;
}
}
/**
* {a: {
* b: {
* c: 1
* d: [2,3]
* }
* }
* }
* to
* {
* 'a.b.c': 1,
* 'a.b.d': '[2,3]'
* }
*
* @param obj json object
* @returns {*} flatted json key array
*/
function flatJSON(obj) {
var flat = function (obj, prentKey, flattedJSON) {
flattedJSON = flattedJSON || {};
prentKey = prentKey || '';
if (prentKey !== '')
prentKey = prentKey + '.';
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]') {
flat(value, prentKey + key, flattedJSON);
} else {
if (prentKey === 'plugin.ClientPluginOptions.')
prentKey = 'plugin.';
if (Array.isArray(value)) {
flattedJSON[prentKey + key] = JSON.stringify(value);
} else {
flattedJSON[prentKey + key] = value;
}
}
}
return flattedJSON;
}
return flat(obj);
}
/** /**
* get proxy info * get proxy info
@@ -282,9 +167,9 @@ var loadProxyInfo = (function ($) {
basicParams.forEach(function (basicName) { basicParams.forEach(function (basicName) {
var name = basicName.name; var name = basicName.name;
if (name.indexOf('.') !== -1) { if (name.indexOf('.') !== -1) {
var names = name.split('.'); var keys = name.split('.');
expandJSON(tempData, names, 0, basicName.defaultValue); expandJSONKeys(tempData, keys, basicName.defaultValue);
expandJSON(basicData, names, 0, null); expandJSONKeys(basicData, keys, null);
} }
eval('basicData.' + name + ' = ' + 'tempData.' + name); eval('basicData.' + name + ' = ' + 'tempData.' + name);
@@ -325,6 +210,7 @@ var loadProxyInfo = (function ($) {
var value = $(this).find('input').last().val(); var value = $(this).find('input').last().val();
formData[name] = value; formData[name] = value;
}); });
addOrUpdate(formData, index, update); addOrUpdate(formData, index, update);
} }
}, },
@@ -375,15 +261,20 @@ var loadProxyInfo = (function ($) {
var loading = layui.layer.load(); var loading = layui.layer.load();
var url = ''; var url = '';
if (update) { if (update) {
url = '/update'; url = '/update?type=' + currentProxyType;
} else { } else {
url = '/add?type=' + currentProxyType; url = '/add?type=' + currentProxyType;
} }
var tomlStr = TOML.stringify(expandJSON(data));
//todo get all proxy and replace or add a new proxy in it
$.ajax({ $.ajax({
url: url, url: url,
type: 'post', type: 'post',
contentType: 'application/json', contentType: 'application/json',
data: JSON.stringify(data), data: JSON.stringify(expandJSON(data)),
success: function (result) { success: function (result) {
if (result.success) { if (result.success) {
layui.layer.close(index); layui.layer.close(index);

View File

@@ -0,0 +1,183 @@
(function (){
//param names in Basic tab
var basicParams = [
{
name: 'name',
defaultValue: '-'
}, {
name: 'type',
defaultValue: '-'
}, {
name: 'localIP',
defaultValue: '-'
}, {
name: 'localPort',
defaultValue: '-'
}, {
name: 'customDomains',
defaultValue: '-'
}, {
name: 'subdomain',
defaultValue: '-'
}, {
name: 'remotePort',
defaultValue: '-'
}, {
name: 'transport.useEncryption',
defaultValue: 'true',
}, {
name: 'transport.useCompression',
defaultValue: 'true',
}
];
var mapParams = [{
name: 'plugin.ClientPluginOptions',
map: 'plugin'
}];
var paramTypes = {
number: [
'healthCheck.timeoutSeconds',
'healthCheck.maxFailed',
'healthCheck.intervalSeconds',
'localPort',
],
boolean: [
'transport.useEncryption',
'transport.useCompression'
],
array: [
'customDomains',
'locations',
'allowUsers'
],
map: [
'metadatas',
'requestHeaders.set',
'plugin.ClientPluginOptions.requestHeaders.set'
]
}
/**
* a.b.c = 1
* a.b.d = [2,3]
* to
* {a: {
* b: {
* c: 1
* d: "[2,3]"
* }
* }
* }
*
* @param obj json object
* @param keys all keys split from key string like 'a.b.c'
* @param value default value
* @param stringifyArray if true, when value is an array, it will stringify by JSON.stringify(value)
*/
function expandJSONKeys(obj, keys, value, stringifyArray) {
stringifyArray = stringifyArray == null ? true : stringifyArray;
var currentIndex = this.index || 0;
var childrenIndex = (currentIndex + 1) > keys.length ? null : (currentIndex + 1);
var currentKey = keys[currentIndex], currentValue = {};
var childrenKey = childrenIndex == null ? null : keys[childrenIndex];
if (obj.hasOwnProperty(currentKey)) {
currentValue = obj[currentKey];
} else {
obj[currentKey] = currentValue;
}
if (childrenKey != null) {
this.index = childrenIndex;
expandJSONKeys(currentValue, keys, value, stringifyArray);
} else {
if (value != null) {
if (Array.isArray(value) && stringifyArray) {
obj[currentKey] = JSON.stringify(value);
} else {
obj[currentKey] = value;
}
}
this.index = 0;
}
}
function expandJSON(obj) {
var newObj = {};
for (var name in obj) {
var value = obj[name];
if (value === '') {
continue;
}
if (paramTypes.number.indexOf(name) !== -1) {
value = parseInt(value) || 0;
} else if (paramTypes.boolean.indexOf(name) !== -1) {
value = Boolean(value) || false;
} else if (paramTypes.array.indexOf(name) !== -1) {
value = eval('(' + value + ')') || [];
} else {
for (var i = 0; i < paramTypes.map.length; i++) {
var key = paramTypes.map[i];
if (name.startsWith(key)) {
var json = {};
json[name.substring(key.length + 1, name.length)] = value;
value = json;
name = name.substring(0, key.length)
break;
}
}
}
expandJSONKeys(newObj, name.split("."), value, false);
}
return newObj;
}
/**
* {a: {
* b: {
* c: 1
* d: [2,3]
* }
* }
* }
* to
* {
* 'a.b.c': 1,
* 'a.b.d': '[2,3]'
* }
*
* @param obj json object
* @returns {*} flatted json key array
*/
function flatJSON(obj) {
var flat = function (obj, prentKey, flattedJSON) {
flattedJSON = flattedJSON || {};
prentKey = prentKey || '';
if (prentKey !== '')
prentKey = prentKey + '.';
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object' && Object.prototype.toString.call(value) === '[object Object]') {
flat(value, prentKey + key, flattedJSON);
} else {
for (var mapParam of mapParams) {
if (prentKey.startsWith(mapParam.name)) {
prentKey = mapParam.map + '.';
break;
}
}
if (Array.isArray(value)) {
flattedJSON[prentKey + key] = JSON.stringify(value);
} else {
flattedJSON[prentKey + key] = value;
}
}
}
return flattedJSON;
}
return flat(obj);
}
window.expandJSONKeys = expandJSONKeys;
window.expandJSON = expandJSON;
window.flatJSON = flatJSON;
})();

8319
assets/static/js/toml.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -6,6 +6,8 @@
<link rel="stylesheet" href="./static/css/layui-theme-dark.css?v=${ .version }"> <link rel="stylesheet" href="./static/css/layui-theme-dark.css?v=${ .version }">
<link rel="stylesheet" href="./static/css/index.css?v=${ .version }"> <link rel="stylesheet" href="./static/css/index.css?v=${ .version }">
<link rel="stylesheet" href="./static/css/color.css?v=${ .version }"> <link rel="stylesheet" href="./static/css/color.css?v=${ .version }">
<script src="./static/js/json-process.js?v=${ .version }"></script>
<script src="./static/js/toml.js?v=${ .version }"></script>
<script src="./static/lib/layui/layui.js?v=${ .version }"></script> <script src="./static/lib/layui/layui.js?v=${ .version }"></script>
<script src="./static/js/index-client-info.js?v=${ .version }"></script> <script src="./static/js/index-client-info.js?v=${ .version }"></script>
<script src="./static/js/index-proxy-overview.js?v=${ .version }"></script> <script src="./static/js/index-proxy-overview.js?v=${ .version }"></script>

View File

@@ -3,8 +3,10 @@ package controller
import ( import (
"bytes" "bytes"
"fmt" "fmt"
v1 "github.com/fatedier/frp/pkg/config/v1"
ginI18n "github.com/gin-contrib/i18n" ginI18n "github.com/gin-contrib/i18n"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/pelletier/go-toml/v2"
"github.com/vaughan0/go-ini" "github.com/vaughan0/go-ini"
"log" "log"
"net/http" "net/http"
@@ -199,7 +201,8 @@ func (c *HandleController) MakeAddProxyFunc() func(context *gin.Context) {
func (c *HandleController) MakeUpdateProxyFunc() func(context *gin.Context) { func (c *HandleController) MakeUpdateProxyFunc() func(context *gin.Context) {
return func(context *gin.Context) { return func(context *gin.Context) {
proxy := ini.Section{} proxyType := context.Query("type")
proxy := v1.NewProxyConfigurerByType(v1.ProxyType(proxyType))
response := OperationResponse{ response := OperationResponse{
Success: true, Success: true,
@@ -207,6 +210,12 @@ func (c *HandleController) MakeUpdateProxyFunc() func(context *gin.Context) {
Message: "proxy update success", Message: "proxy update success",
} }
var b = make([]byte, context.Request.ContentLength)
context.Request.Body.Read(b)
var s = string(b)
log.Print(s)
toml.Unmarshal(b, &proxy)
err := context.BindJSON(&proxy) err := context.BindJSON(&proxy)
if err != nil { if err != nil {
response.Success = false response.Success = false
@@ -217,52 +226,56 @@ func (c *HandleController) MakeUpdateProxyFunc() func(context *gin.Context) {
return return
} }
oldName := proxy[OldNameKey] context.JSON(200, &response)
name := proxy[NameKey]
if trimString(oldName) == "" || trimString(name) == "" { //proxy.GetBaseConfig()
response.Success = false //
response.Code = ParamError //oldName := proxy[OldNameKey]
response.Message = fmt.Sprintf("proxy add failed, proxy name invalid") //name := proxy[NameKey]
log.Printf(response.Message) //
context.JSON(http.StatusOK, &response) //if trimString(oldName) == "" || trimString(name) == "" {
return // response.Success = false
} // response.Code = ParamError
// response.Message = fmt.Sprintf("proxy add failed, proxy name invalid")
if _, exist := clientProxies[oldName]; !exist { // log.Printf(response.Message)
response.Success = false // context.JSON(http.StatusOK, &response)
response.Code = ProxyNotExist // return
response.Message = fmt.Sprintf("proxy update failed, proxy not exist") //}
log.Printf(response.Message) //
context.JSON(http.StatusOK, &response) //if _, exist := clientProxies[oldName]; !exist {
return // response.Success = false
} // response.Code = ProxyNotExist
// response.Message = fmt.Sprintf("proxy update failed, proxy not exist")
if oldName != name { // log.Printf(response.Message)
if _, exist := clientProxies[name]; exist { // context.JSON(http.StatusOK, &response)
response.Success = false // return
response.Code = ProxyExist //}
response.Message = fmt.Sprintf("proxy update failed, proxy exist") //
log.Printf(response.Message) //if oldName != name {
context.JSON(http.StatusOK, &response) // if _, exist := clientProxies[name]; exist {
return // response.Success = false
} // response.Code = ProxyExist
} // response.Message = fmt.Sprintf("proxy update failed, proxy exist")
// log.Printf(response.Message)
delete(clientProxies, oldName) // context.JSON(http.StatusOK, &response)
clientProxies[name] = proxy // return
// }
res := c.UpdateFrpcConfig() //}
if !res.Success { //
response.Success = false //delete(clientProxies, oldName)
response.Code = res.Code //clientProxies[name] = proxy
response.Message = fmt.Sprintf("user update failed, error : %v", res.Message) //
log.Printf(response.Message) //res := c.UpdateFrpcConfig()
context.JSON(http.StatusOK, &response) //if !res.Success {
return // response.Success = false
} // response.Code = res.Code
// response.Message = fmt.Sprintf("user update failed, error : %v", res.Message)
context.JSON(http.StatusOK, &response) // log.Printf(response.Message)
// context.JSON(http.StatusOK, &response)
// return
//}
//
//context.JSON(http.StatusOK, &response)
} }
} }

View File

@@ -137,11 +137,6 @@ func (c *HandleController) parseResponse(res *ProxyResponse, response *http.Resp
log.Printf(res.Message) log.Printf(res.Message)
} }
type MyProxy struct {
Toml string `json:"toml"`
*v1.ProxyBaseConfig
}
func (c *HandleController) parseConfigure(content, proxyType string) (interface{}, error) { func (c *HandleController) parseConfigure(content, proxyType string) (interface{}, error) {
clientConfig := v1.ClientConfig{} clientConfig := v1.ClientConfig{}
err := config.LoadConfigure([]byte(content), &clientConfig) err := config.LoadConfigure([]byte(content), &clientConfig)
@@ -160,5 +155,6 @@ func (c *HandleController) parseConfigure(content, proxyType string) (interface{
filterProxies = append(filterProxies, allProxies[i]) filterProxies = append(filterProxies, allProxies[i])
} }
} }
return filterProxies, nil return filterProxies, nil
} }