Merge pull request #42 from xuchaoa/main

format code and fix wrong spell
This commit is contained in:
link 2021-12-06 03:07:48 -06:00 committed by GitHub
commit 90b997337c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 90 additions and 100 deletions

View file

@ -1,3 +1 @@
package model

View file

@ -6,7 +6,6 @@ import (
"golang.org/x/oauth2"
)
func GetGithubClient() *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(

View file

@ -7,7 +7,7 @@ import (
"strings"
)
func GetCtrlUrl(host,device string) string {
func GetCtrlUrl(host, device string) string {
request := ctrlUrlRequest(host, device)
response, _ := http.DefaultClient.Do(request)
resultBody, _ := ioutil.ReadAll(response.Body)
@ -86,4 +86,4 @@ func resolve(resultStr string) string {
}
}
return controlURL
}
}

View file

@ -22,21 +22,21 @@ func send() (string, error) {
"ST: urn:schemas-upnp-org:service:WANIPConnection:1\r\n" +
"MAN: \"ssdp:discover\"\r\n" + "MX: 3\r\n\r\n"
var conn *net.UDPConn
remotAddr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
remoteAddr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
if err != nil {
return "", errors.New("组播地址格式不正确")
}
locaAddr, err := net.ResolveUDPAddr("udp", ip_helper2.GetLoclIp()+":")
localAddr, err := net.ResolveUDPAddr("udp", ip_helper2.GetLoclIp()+":")
if err != nil {
return "", errors.New("本地ip地址格式不正确")
}
conn, err = net.ListenUDP("udp", locaAddr)
conn, err = net.ListenUDP("udp", localAddr)
defer conn.Close()
if err != nil {
return "", errors.New("监听udp出错")
}
_, err = conn.WriteToUDP([]byte(str), remotAddr)
_, err = conn.WriteToUDP([]byte(str), remoteAddr)
if err != nil {
return "", errors.New("发送msg到组播地址出错")
}

View file

@ -5,4 +5,4 @@ import "testing"
func TestGateway(t *testing.T) {
Gateway()
}
}

View file

@ -2,40 +2,37 @@ package upnp
import (
"bytes"
"github.com/pkg/errors"
"net/http"
"strconv"
"strings"
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/pkg/errors"
)
//
////添加一个端口映射
func (n *Upnp)AddPortMapping(localPort, remotePort int, protocol string) (err error) {
defer func(err error) {
func (n *Upnp) AddPortMapping(localPort, remotePort int, protocol string) (err error) {
defer func() {
if errTemp := recover(); errTemp != nil {
//log.Println("upnp模块报错了", errTemp)
err = errTemp.(error)
loger2.NewOLoger().Error("upnp模块报错了", errTemp)
}
}(err)
if issuccess := addSend(localPort, remotePort, protocol,n.GatewayHost, n.CtrlUrl,n.LocalHost); issuccess {
}()
if isSuccess := addSend(localPort, remotePort, protocol, n.GatewayHost, n.CtrlUrl, n.LocalHost); isSuccess {
return nil
} else {
return errors.New("添加一个端口映射失败")
}
return
}
func addSend(localPort, remotePort int, protocol, host, ctrUrl,localHost string) bool {
request := addRequest(localPort, remotePort, protocol, host, ctrUrl,localHost)
func addSend(localPort, remotePort int, protocol, host, ctrUrl, localHost string) bool {
request := addRequest(localPort, remotePort, protocol, host, ctrUrl, localHost)
response, _ := http.DefaultClient.Do(request)
defer response.Body.Close()
//resultBody, _ := ioutil.ReadAll(response.Body)
//fmt.Println(string(resultBody))
if response.StatusCode == 200 {
return true
}
return false
return response.StatusCode == 200
}
type Node struct {
@ -45,7 +42,7 @@ type Node struct {
Child []Node
}
func addRequest(localPort, remotePort int, protocol string, gatewayHost, ctlUrl,localHost string) *http.Request {
func addRequest(localPort, remotePort int, protocol string, gatewayHost, ctlUrl, localHost string) *http.Request {
//请求头
header := http.Header{}
header.Set("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
@ -109,27 +106,25 @@ func (n *Node) BuildXML() string {
return buf.String()
}
func (n *Upnp)DelPortMapping(remotePort int, protocol string) bool {
issuccess := delSendSend(remotePort, protocol,n.GatewayHost,n.CtrlUrl)
if issuccess {
func (n *Upnp) DelPortMapping(remotePort int, protocol string) bool {
isSuccess := delSendSend(remotePort, protocol, n.GatewayHost, n.CtrlUrl)
if isSuccess {
//this.MappingPort.delMapping(remotePort, protocol)
//fmt.Println("删除了一个端口映射: remote:", remotePort)
}
return issuccess
return isSuccess
}
func delSendSend(remotePort int, protocol,host,ctlUrl string) bool {
delrequest := delbuildRequest(remotePort, protocol,host,ctlUrl)
func delSendSend(remotePort int, protocol, host, ctlUrl string) bool {
delrequest := delbuildRequest(remotePort, protocol, host, ctlUrl)
response, _ := http.DefaultClient.Do(delrequest)
//resultBody, _ := ioutil.ReadAll(response.Body)
defer response.Body.Close()
if response.StatusCode == 200 {
// log.Println(string(resultBody))
return true
}
return false
return response.StatusCode == 200
}
func delbuildRequest(remotePort int, protocol,host,ctlUrl string) *http.Request {
func delbuildRequest(remotePort int, protocol, host, ctlUrl string) *http.Request {
//请求头
header := http.Header{}
header.Set("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
@ -160,4 +155,4 @@ func delbuildRequest(remotePort int, protocol,host,ctlUrl string) *http.Request
request.Header = header
request.Header.Set("Content-Length", strconv.Itoa(len([]byte(bodyStr))))
return request
}
}

View file

@ -7,10 +7,10 @@ import (
type Upnp struct {
LocalHost string `json:"local_host"`
GatewayName string `json:"gateway_name"` //网关名称
GatewayHost string `json:"gateway_host"` //网关ip和端口
GatewayName string `json:"gateway_name"` //网关名称
GatewayHost string `json:"gateway_host"` //网关ip和端口
DeviceDescUrl string `json:"device_desc_url"` //设备描述url
CtrlUrl string `json:"ctrl_url"` //控制请求url
CtrlUrl string `json:"ctrl_url"` //控制请求url
}
func Testaaa() {
@ -23,4 +23,3 @@ func Testaaa() {
fmt.Println("gateway ip address: ", upnpMan.Gateway.Host)
}
}

View file

@ -6,4 +6,4 @@ import (
func TestTestaaa(t *testing.T) {
(Testaaa())
}
}

View file

@ -6,7 +6,7 @@ import (
"os"
"path/filepath"
"runtime"
"github.com/IceWhaleTech/CasaOS/pkg/config"
file2 "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
)

View file

@ -6,5 +6,5 @@ import (
)
func TestRandomString(t *testing.T) {
fmt.Println(RandomString(6,true))
}
fmt.Println(RandomString(6, true))
}

View file

@ -64,7 +64,7 @@ func DDNSAddConfig(c *gin.Context) {
})
return
}
var m model2.DDNSUpdataDBModel
var m model2.DDNSUpdateDBModel
c.Bind(&m)
if err := service.MyService.DDNS().SaveConfig(m); err != nil {
c.JSON(http.StatusOK,

View file

@ -268,11 +268,11 @@ func InstallApp(c *gin.Context) {
rely.ContainerId = mysqlContainerId
rely.CustomId = mid
rely.ContainerCustomId = id
var msqlConfig model2.MysqlConfigs
var mysqlConfig model2.MysqlConfigs
//结构体转换
copier.Copy(&msqlConfig, &mc)
rely.Config = msqlConfig
copier.Copy(&mysqlConfig, &mc)
rely.Config = mysqlConfig
service.MyService.Rely().Create(rely)
relyMap["mysql"] = mid

View file

@ -102,7 +102,7 @@ func GetSystemConfigDebug(c *gin.Context) {
array := service.MyService.System().GetSystemConfigDebug()
disk := service.MyService.ZiMa().GetDiskInfo()
array = append(array, fmt.Sprintf("disk,totle:%v,used:%v,UsedPercent:%v", disk.Total>>20, disk.Used>>20, disk.UsedPercent))
array = append(array, fmt.Sprintf("disk,total:%v,used:%v,UsedPercent:%v", disk.Total>>20, disk.Used>>20, disk.UsedPercent))
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: array})
}

View file

@ -68,8 +68,7 @@ func (a *appStruct) GetMyList(index, size int, position bool) *[]model2.MyAppLis
for _, container := range containers {
if lMap[container.ID] != nil && container.Labels["origin"] != "system" {
var m model2.AppListDBModel
m = lMap[container.ID].(model2.AppListDBModel)
m := lMap[container.ID].(model2.AppListDBModel)
if len(m.Label) == 0 {
m.Label = m.Title
}
@ -129,8 +128,7 @@ func (a *appStruct) GetSystemAppList() *[]model2.MyAppList {
for _, container := range containers {
if lMap[container.ID] != nil {
var m model2.AppListDBModel
m = lMap[container.ID].(model2.AppListDBModel)
m := lMap[container.ID].(model2.AppListDBModel)
if len(m.Label) == 0 {
m.Label = m.Title
}
@ -194,6 +192,10 @@ func (a *appStruct) GetSimpleContainerInfo(name string) (types.Container, error)
filters := filters.NewArgs()
filters.Add("name", name)
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: filters})
if err != nil {
return types.Container{}, err
}
if len(containers) > 0 {
return containers[0], nil
}

View file

@ -1,12 +1,13 @@
package service
import (
"os/exec"
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/service/ddns"
"github.com/IceWhaleTech/CasaOS/service/model"
"gorm.io/gorm"
"os/exec"
)
type ddnsStruct struct {
@ -20,17 +21,15 @@ type DDNSService interface {
GetConfigList() *[]model.DDNSList
DeleteConfig(id uint) bool
GetType(name string) (uint, string)
SaveConfig(model model.DDNSUpdataDBModel) error
SaveConfig(model model.DDNSUpdateDBModel) error
}
//判断当前添加的是否存在
func (d *ddnsStruct) IsExis(t int, domain string, host string) bool {
var count int64
d.db.Table(model.DDNSLISTTABLENAME).Where("type=? AND domain=? AND host=?", t, domain, host).Count(&count)
if count > 0 {
return true
}
return false
return count > 0
}
//前台获取已配置的ddns列表
@ -41,7 +40,7 @@ func (d *ddnsStruct) GetConfigList() *[]model.DDNSList {
}
func (d *ddnsStruct) DeleteConfig(id uint) bool {
d.db.Delete(&model.DDNSUpdataDBModel{Id: id})
d.db.Delete(&model.DDNSUpdateDBModel{Id: id})
return true
}
@ -66,12 +65,12 @@ func (d *ddnsStruct) GetType(name string) (uint, string) {
}
//保存配置到数据库
func (d *ddnsStruct) GetDockerRootDir(model model.DDNSUpdataDBModel) error {
func (d *ddnsStruct) GetDockerRootDir(model model.DDNSUpdateDBModel) error {
return d.db.Create(&model).Error
}
//保存配置到数据库
func (d *ddnsStruct) SaveConfig(model model.DDNSUpdataDBModel) error {
func (d *ddnsStruct) SaveConfig(model model.DDNSUpdateDBModel) error {
return d.db.Create(&model).Error
}
@ -87,7 +86,7 @@ func chackPing(b chan bool, url string) {
}
//更新列表
func UpdataDDNSList(db *gorm.DB) {
func UpdateDDNSList(db *gorm.DB) {
var s []model.DDNSCoreList
db.Table(model.DDNSLISTTABLENAME).Select("o_ddns_type.name as name,o_ddns_type.api_host as api_host,o_ddns.id,`host`,domain,user_name,`password`,`key`,secret,type").Joins("left join o_ddns_type on o_ddns.type=o_ddns_type.id").Scan(&s)
for _, item := range s {

View file

@ -31,4 +31,3 @@ func SetOauth(request *http.Request, value string) {
func SetXFilter(request *http.Request, value string) {
request.Header.Set("X-Filter", value)
}

View file

@ -107,7 +107,7 @@ func (ds *dockerService) GetNetWorkNameByNetWorkID(id string) (string, error) {
defer cli.Close()
filter := filters.NewArgs()
filter.Add("id", id)
d, err := cli.NetworkList(context.Background(), types.NetworkListOptions{filter})
d, err := cli.NetworkList(context.Background(), types.NetworkListOptions{Filters: filter})
if err == nil && len(d) > 0 {
return d[0].Name, nil
}
@ -158,7 +158,7 @@ func DockerEx() {
importResponse.Close()
println(string(response))
if string(response) != "response" {
fmt.Println("expected response to contain 'response', got %s", string(response))
fmt.Printf("expected response to contain 'response', got %s", string(response))
}
}
@ -187,7 +187,6 @@ func (ds *dockerService) DockerImageInfo(image string) {
if err != nil {
fmt.Print(err)
}
}
func MsqlExec(container string) error {
@ -266,6 +265,8 @@ func DockerLogs() {
if err != nil {
log.Fatal(err)
}
defer i.Close()
hdr := make([]byte, 8)
for {
_, err := i.Read(hdr)
@ -284,7 +285,6 @@ func DockerLogs() {
_, err = i.Read(dat)
fmt.Fprint(w, string(dat))
}
defer i.Close()
}
//正式内容
@ -787,7 +787,7 @@ func (ds *dockerService) DockerNetworkModelList() []types.NetworkResource {
networks, _ := cli.NetworkList(context.Background(), types.NetworkListOptions{})
return networks
}
func NewDcokerService(log loger2.OLog) DockerService {
func NewDockerService(log loger2.OLog) DockerService {
return &dockerService{rootDir: command2.ExecResultStr(`source ./shell/helper.sh ;GetDockerRootDir`), log: log}
}

View file

@ -7,5 +7,3 @@ type MysqlConfig struct {
DataBasePassword string `json:"data_base_password"`
DataBaseDB string `json:"data_base_db"`
}

View file

@ -2,11 +2,11 @@ package model
import "time"
func (p *DDNSUpdataDBModel) TableName() string {
func (p *DDNSUpdateDBModel) TableName() string {
return "o_ddns"
}
type DDNSUpdataDBModel struct {
type DDNSUpdateDBModel struct {
Id uint `gorm:"column:id;primary_key" json:"id"`
Ipv4 string `gorm:"-"`
Ipv6 string `gorm:"-"`
@ -17,8 +17,8 @@ type DDNSUpdataDBModel struct {
Secret string `json:"secret" form:"secret"`
UserName string `json:"user_name" form:"user_name"`
Password string `json:"password" form:"password"`
CreatedAt time.Time `gorm:"<-:create" json:"created_at"`
UpdatedAt time.Time `gorm:"<-:create;<-:update" json:"updated_at"`
CreatedAt time.Time `gorm:"<-:create" json:"created_at"`
UpdatedAt time.Time `gorm:"<-:create;<-:update" json:"updated_at"`
}
const DDNSLISTTABLENAME = "o_ddns"
@ -39,9 +39,9 @@ type DDNSList struct {
//定时任务使用
type DDNSCoreList struct {
Id uint `gorm:"column:id;primary_key" json:"id"`
Id uint `gorm:"column:id;primary_key" json:"id"`
Domain string `json:"domain" form:"domain"`
Name string `json:"domain" form:"name"`
Name string `json:"name" form:"name"`
Type uint `json:"type"`
Key string `json:"key"`
Message string `json:"message"`

View file

@ -35,7 +35,7 @@ func NewService(db *gorm.DB, log loger2.OLog) Repository {
app: NewAppService(db, log),
ddns: NewDDNSService(db, log),
user: NewUserService(),
docker: NewDcokerService(log),
docker: NewDockerService(log),
//redis: NewRedisService(rp),
zerotier: NewZeroTierService(),
zima: NewZiMaService(),

View file

@ -2,6 +2,8 @@ package service
import (
json2 "encoding/json"
"strconv"
"github.com/IceWhaleTech/CasaOS/pkg/config"
httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
@ -9,7 +11,6 @@ import (
"github.com/IceWhaleTech/CasaOS/types"
"github.com/tidwall/gjson"
"gorm.io/gorm"
"strconv"
)
type TaskService interface {

View file

@ -34,20 +34,20 @@ type ZeroTierService interface {
DeleteNetwork(token, id string) interface{}
GetJoinNetworks() string
}
type zerotierstruct struct {
type zerotierStruct struct {
}
var client http.Client
func (c *zerotierstruct) ZeroTierJoinNetwork(networkId string) {
func (c *zerotierStruct) ZeroTierJoinNetwork(networkId string) {
command2.OnlyExec(`zerotier-cli join ` + networkId)
}
func (c *zerotierstruct) ZeroTierLeaveNetwork(networkId string) {
func (c *zerotierStruct) ZeroTierLeaveNetwork(networkId string) {
command2.OnlyExec(`zerotier-cli leave ` + networkId)
}
//登录并获取token
func (c *zerotierstruct) GetToken(username, pwd string) string {
func (c *zerotierStruct) GetToken(username, pwd string) string {
if len(config.ZeroTierInfo.Token) > 0 {
return config.ZeroTierInfo.Token
} else {
@ -55,7 +55,7 @@ func (c *zerotierstruct) GetToken(username, pwd string) string {
}
}
func (c *zerotierstruct) ZeroTierRegister(email, lastName, firstName, password string) string {
func (c *zerotierStruct) ZeroTierRegister(email, lastName, firstName, password string) string {
url := "https://accounts.zerotier.com/auth/realms/zerotier/protocol/openid-connect/registrations?client_id=zt-central&redirect_uri=https%3A%2F%2Fmy.zerotier.com%2Fapi%2F_auth%2Foidc%2Fcallback&response_type=code&scope=openid+profile+email+offline_access&state=state"
@ -210,7 +210,7 @@ func ZeroTierGet(url string, cookies []*http.Cookie, t uint8) (action string, c
}
//模拟提交表单
func ZeroTierPost(str bytes.Buffer, action string, cookes []*http.Cookie, isLogin bool) (url, errInfo string, err error) {
func ZeroTierPost(str bytes.Buffer, action string, cookies []*http.Cookie, isLogin bool) (url, errInfo string, err error) {
req, err := http.NewRequest(http.MethodPost, action, strings.NewReader(str.String()))
if err != nil {
return "", "", errors.New("newrequest error")
@ -219,7 +219,7 @@ func ZeroTierPost(str bytes.Buffer, action string, cookes []*http.Cookie, isLogi
req.Header.Set(k, v)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
for _, cookie := range cookes {
for _, cookie := range cookies {
req.AddCookie(cookie)
}
res, err := client.Do(req)
@ -273,62 +273,62 @@ func ZeroTierPost(str bytes.Buffer, action string, cookes []*http.Cookie, isLogi
}
//获取zerotile网络列表和本地用户已加入的网络
func (c *zerotierstruct) ZeroTierNetworkList(token string) (interface{}, []string) {
func (c *zerotierStruct) ZeroTierNetworkList(token string) (interface{}, []string) {
url := "https://my.zerotier.com/api/network"
return zerotier.GetData(url, token), command2.ExecResultStrArray(`zerotier-cli listnetworks | awk 'NR>1 {print $3} {line=$0}'`)
}
// get network info
func (c *zerotierstruct) ZeroTierGetInfo(token, id string) (interface{}, []string) {
func (c *zerotierStruct) ZeroTierGetInfo(token, id string) (interface{}, []string) {
url := "https://my.zerotier.com/api/network/" + id
info := zerotier.GetData(url, token)
return info, command2.ExecResultStrArray(`zerotier-cli listnetworks | awk 'NR>1 {print $3} {line=$0}'`)
}
//get status
func (c *zerotierstruct) ZeroTierGetStatus(token string) interface{} {
func (c *zerotierStruct) ZeroTierGetStatus(token string) interface{} {
url := "https://my.zerotier.com/api/v1/status"
info := zerotier.GetData(url, token)
return info
}
func (c *zerotierstruct) EditNetwork(token string, data string, id string) interface{} {
func (c *zerotierStruct) EditNetwork(token string, data string, id string) interface{} {
url := "https://my.zerotier.com/api/v1/network/" + id
info := zerotier.PostData(url, token, data)
return info
}
func (c *zerotierstruct) EditNetworkMember(token string, data string, id, mId string) interface{} {
func (c *zerotierStruct) EditNetworkMember(token string, data string, id, mId string) interface{} {
url := "https://my.zerotier.com/api/v1/network/" + id + "/member/" + mId
info := zerotier.PostData(url, token, data)
return info
}
func (c *zerotierstruct) MemberList(token string, id string) interface{} {
func (c *zerotierStruct) MemberList(token string, id string) interface{} {
url := "https://my.zerotier.com/api/v1/network/" + id + "/member"
info := zerotier.GetData(url, token)
return info
}
func (c *zerotierstruct) DeleteMember(token string, id, mId string) interface{} {
func (c *zerotierStruct) DeleteMember(token string, id, mId string) interface{} {
url := "https://my.zerotier.com/api/v1/network/" + id + "/member/" + mId
info := zerotier.DeleteMember(url, token)
return info
}
func (c *zerotierstruct) DeleteNetwork(token, id string) interface{} {
func (c *zerotierStruct) DeleteNetwork(token, id string) interface{} {
url := "https://my.zerotier.com/api/v1/network/" + id
info := zerotier.DeleteMember(url, token)
return info
}
func (c *zerotierstruct) CreateNetwork(token string) interface{} {
func (c *zerotierStruct) CreateNetwork(token string) interface{} {
url := "https://my.zerotier.com/api/v1/network"
info := zerotier.PostData(url, token, "{}")
return info
}
func (c *zerotierstruct) GetJoinNetworks() string {
func (c *zerotierStruct) GetJoinNetworks() string {
json := command2.ExecResultStr("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetLocalJoinNetworks")
return json
}
@ -339,5 +339,5 @@ func NewZeroTierService() ZeroTierService {
return http.ErrUseLastResponse //禁止重定向
},
}
return &zerotierstruct{}
return &zerotierStruct{}
}