diff --git a/CHANGELOG.md b/CHANGELOG.md index 43f881a..cad4793 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,17 +22,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- SSH adds port-side options and prompts for connection status. ((#286)[https://github.com/IceWhaleTech/CasaOS/issues/286]) + ### Changed +- Normalize all routes +- Application names now support spaces ((#211)[https://github.com/IceWhaleTech/CasaOS/issues/211]) + ### Removed -- Removed connect +- Removed casaos connect ### Security +- Adjustment of authentication method + ### Fixed +- Fixed storage format and remove password error issues ((#344)[https://github.com/IceWhaleTech/CasaOS/issues/344] (#357)[https://github.com/IceWhaleTech/CasaOS/issues/357]) + ## [0.3.3-alpha] - 2022-07-01(UTC) ### Added diff --git a/UI b/UI index 7af1bf5..bca2742 160000 --- a/UI +++ b/UI @@ -1 +1 @@ -Subproject commit 7af1bf549dd35c93f48b6c501204a4efe57e8d6b +Subproject commit bca27426e1f398c31fb6c5c23885482326514f6e diff --git a/conf/conf.conf.sample b/conf/conf.conf.sample index 682717f..c4f8179 100644 --- a/conf/conf.conf.sample +++ b/conf/conf.conf.sample @@ -21,11 +21,4 @@ Handshake = socket.casaos.io Token = USBAutoMount = - -[system] -WidgetList = - - -[file] -ShareDir = -DownloadDir = \ No newline at end of file +[system] \ No newline at end of file diff --git a/main.go b/main.go index c67d163..932f28d 100644 --- a/main.go +++ b/main.go @@ -63,7 +63,6 @@ func init() { func main() { service.NotifyMsg = make(chan notify.Message, 10) if *resetUser { - if user == nil || len(*user) == 0 { fmt.Println("user is empty") return diff --git a/middleware/gin.go b/middleware/gin.go index d70dfb9..3febab2 100644 --- a/middleware/gin.go +++ b/middleware/gin.go @@ -2,7 +2,7 @@ * @Author: LinkLeong link@icewhale.com * @Date: 2021-10-08 10:29:08 * @LastEditors: LinkLeong - * @LastEditTime: 2022-06-21 15:10:03 + * @LastEditTime: 2022-07-13 11:26:12 * @FilePath: /CasaOS/middleware/gin.go * @Description: * @Website: https://www.casaos.io @@ -26,14 +26,14 @@ func Cors() gin.HandlerFunc { c.Header("Access-Control-Allow-Origin", "*") c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") //允许跨域设置可以返回其他子段,可以自定义字段 - c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,Language") + c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,Language,Content-Type,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods,Connection,Host,Origin,Referer,User-Agent,X-Requested-With") // 允许浏览器(客户端)可以解析的头部 (重要) c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers") //c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, Content-Length, X-CSRF-Token, Token, session, Origin, Host, Connection, Accept-Encoding, Accept-Language, X-Requested-With") //设置缓存时间 c.Header("Access-Control-Max-Age", "172800") c.Header("Access-Control-Allow-Credentials", "true") - c.Set("content-type", "application/json") + c.Set("Content-Type", "application/json") //} //允许类型校验 diff --git a/model/category.go b/model/category.go index ed5e848..3005491 100644 --- a/model/category.go +++ b/model/category.go @@ -2,10 +2,9 @@ * @Author: link a624669980@163.com * @Date: 2022-05-16 17:37:08 * @LastEditors: LinkLeong - * @LastEditTime: 2022-06-22 17:45:53 + * @LastEditTime: 2022-07-13 10:46:38 * @FilePath: /CasaOS/model/category.go - * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE - + * @Description: */ package model diff --git a/model/disk.go b/model/disk.go index b58049b..dd48976 100644 --- a/model/disk.go +++ b/model/disk.go @@ -1,3 +1,13 @@ +/* + * @Author: LinkLeong link@icewhale.com + * @Date: 2022-07-13 10:43:45 + * @LastEditors: LinkLeong + * @LastEditTime: 2022-07-13 11:00:04 + * @FilePath: /CasaOS/model/disk.go + * @Description: + * @Website: https://www.casaos.io + * Copyright (c) 2022 by icewhale, All Rights Reserved. + */ package model type LSBLKModel struct { @@ -53,8 +63,8 @@ type DriveUSB struct { Size uint64 `json:"size"` Used uint64 `json:"use"` Model string `json:"model"` - Mount bool `json:"mount"` //是否完全挂载 - Avail uint64 `json:"avail"` //可用空间 + Mount bool `json:"mount"` + Avail uint64 `json:"avail"` } type Storage struct { diff --git a/model/docker.go b/model/docker.go index 2fb03ba..a083319 100644 --- a/model/docker.go +++ b/model/docker.go @@ -2,7 +2,7 @@ * @Author: LinkLeong link@icewhale.com * @Date: 2021-12-08 18:10:25 * @LastEditors: LinkLeong - * @LastEditTime: 2022-06-14 17:20:36 + * @LastEditTime: 2022-07-13 10:49:16 * @FilePath: /CasaOS/model/docker.go * @Description: * @Website: https://www.casaos.io @@ -11,8 +11,8 @@ package model type DockerStatsModel struct { - Icon string `json:"icon"` - Title string `json:"title"` - Data interface{} `json:"data"` - Pre interface{} `json:"pre"` // @tiger - pre 不知道什么意思,可以提高一下描述性 + Icon string `json:"icon"` + Title string `json:"title"` + Data interface{} `json:"data"` + Previous interface{} `json:"previous"` } diff --git a/model/manifest.go b/model/manifest.go index 1ee8fc4..0888fb0 100644 --- a/model/manifest.go +++ b/model/manifest.go @@ -104,17 +104,17 @@ func (p *PathArray) Scan(input interface{}) error { //} type CustomizationPostData struct { - Name string `json:"name"` - CustomId string `json:"custom_id"` - Origin string `json:"origin"` - NetworkModel string `json:"network_model"` - Index string `json:"index"` - Icon string `json:"icon"` - Image string `json:"image"` - Envs EnvArray `json:"envs"` - Ports PortArray `json:"ports"` - Volumes PathArray `json:"volumes"` - Devices PathArray `json:"devices"` + ContainerName string `json:"container_name"` + CustomId string `json:"custom_id"` + Origin string `json:"origin"` + NetworkModel string `json:"network_model"` + Index string `json:"index"` + Icon string `json:"icon"` + Image string `json:"image"` + Envs EnvArray `json:"envs"` + Ports PortArray `json:"ports"` + Volumes PathArray `json:"volumes"` + Devices PathArray `json:"devices"` //Port string `json:"port,omitempty"` PortMap string `json:"port_map"` CpuShares int64 `json:"cpu_shares"` diff --git a/model/notify/storage.go b/model/notify/storage.go new file mode 100644 index 0000000..0c62970 --- /dev/null +++ b/model/notify/storage.go @@ -0,0 +1,19 @@ +/* + * @Author: LinkLeong link@icewhale.com + * @Date: 2022-07-15 10:43:00 + * @LastEditors: LinkLeong + * @LastEditTime: 2022-07-15 10:56:17 + * @FilePath: /CasaOS/model/notify/storage.go + * @Description: + * @Website: https://www.casaos.io + * Copyright (c) 2022 by icewhale, All Rights Reserved. + */ +package notify + +type StorageMessage struct { + Type string `json:"type"` //sata,usb + Action string `json:"action"` //remove add + Path string `json:"path"` + Volume string `json:"volume"` + Size uint64 `json:"size"` +} diff --git a/model/sys_common.go b/model/sys_common.go index ce36035..162757d 100644 --- a/model/sys_common.go +++ b/model/sys_common.go @@ -2,7 +2,7 @@ * @Author: LinkLeong link@icewhale.com * @Date: 2022-05-13 18:15:46 * @LastEditors: LinkLeong - * @LastEditTime: 2022-07-04 14:39:23 + * @LastEditTime: 2022-07-14 11:02:06 * @FilePath: /CasaOS/model/sys_common.go * @Description: * @Website: https://www.casaos.io @@ -37,7 +37,6 @@ type ServerModel struct { RunMode string ServerApi string LockAccount bool - Handshake string Token string USBAutoMount string SocketPort string @@ -75,12 +74,7 @@ type RedisModel struct { } type SystemConfig struct { - ConfigStr string `json:"config_str"` - WidgetList string `json:"widget_list"` ConfigPath string `json:"config_path"` - SyncPort string `json:"sync_port"` - SyncKey string `json:"sync_key"` - Analyse string `json:"analyse"` } type CasaOSGlobalVariables struct { diff --git a/pkg/config/init.go b/pkg/config/init.go index efa495f..738ecc5 100644 --- a/pkg/config/init.go +++ b/pkg/config/init.go @@ -2,7 +2,7 @@ * @Author: LinkLeong link@icewhale.com * @Date: 2022-05-13 18:15:46 * @LastEditors: LinkLeong - * @LastEditTime: 2022-06-21 16:01:26 + * @LastEditTime: 2022-07-14 10:58:45 * @FilePath: /CasaOS/pkg/config/init.go * @Description: * @Website: https://www.casaos.io diff --git a/pkg/docker/helper.go b/pkg/docker/helper.go index f2a9886..be76b7d 100644 --- a/pkg/docker/helper.go +++ b/pkg/docker/helper.go @@ -6,7 +6,6 @@ import ( "fmt" "io" "regexp" - "strconv" "sync" "time" @@ -32,7 +31,7 @@ func NewSshClient(user, password string, port string) (*ssh.Client, error) { //} else { // config.Auth = []ssh.AuthMethod{publicKeyAuthFunc(h.Key)} //} - addr := fmt.Sprintf("%s:%d", "127.0.0.1", port) + addr := fmt.Sprintf("%s:%s", "127.0.0.1", port) c, err := ssh.Dial("tcp", addr, config) if err != nil { return nil, err @@ -396,7 +395,7 @@ func WsReaderCopy(reader *websocket.Conn, writer io.Writer) { if err = json2.Unmarshal(p, &msgObj); err != nil { writer.Write(p) } else if msgObj.Type == wsMsgResize { - writer.Write([]byte("stty rows " + strconv.Itoa(msgObj.Rows) + " && stty cols " + strconv.Itoa(msgObj.Cols) + " \r")) + //writer.Write([]byte("stty rows " + strconv.Itoa(msgObj.Rows) + " && stty cols " + strconv.Itoa(msgObj.Cols) + " \r")) } } } diff --git a/pkg/utils/common_err/e.go b/pkg/utils/common_err/e.go index cc8b65b..79ee8cd 100644 --- a/pkg/utils/common_err/e.go +++ b/pkg/utils/common_err/e.go @@ -2,10 +2,11 @@ package common_err const ( SUCCESS = 200 - ERROR = 500 - INVALID_PARAMS = 400 + SERVICE_ERROR = 500 + CLIENT_ERROR = 400 ERROR_AUTH_TOKEN = 401 + INVALID_PARAMS = 4000 //user PWD_INVALID = 10001 PWD_IS_EMPTY = 10002 @@ -53,7 +54,8 @@ const ( var MsgFlags = map[int]string{ SUCCESS: "ok", - ERROR: "fail", + SERVICE_ERROR: "Fail", + CLIENT_ERROR: "Fail", INVALID_PARAMS: "Parameters Error", ERROR_AUTH_TOKEN: "Error auth token", @@ -109,5 +111,5 @@ func GetMsg(code int) string { if ok { return msg } - return MsgFlags[ERROR] + return MsgFlags[SERVICE_ERROR] } diff --git a/pkg/utils/jwt/jwt.go b/pkg/utils/jwt/jwt.go index f48feae..ad88197 100644 --- a/pkg/utils/jwt/jwt.go +++ b/pkg/utils/jwt/jwt.go @@ -2,7 +2,7 @@ * @Author: LinkLeong link@icewhale.com * @Date: 2021-09-30 18:18:14 * @LastEditors: LinkLeong - * @LastEditTime: 2022-07-11 17:41:22 + * @LastEditTime: 2022-07-18 17:30:38 * @FilePath: /CasaOS/pkg/utils/jwt/jwt.go * @Description: * @Website: https://www.casaos.io @@ -46,13 +46,17 @@ func GenerateToken(username, password string, id int, issuer string, t time.Dura } //解析token -func ParseToken(token string) (*Claims, error) { +func ParseToken(token string, valid bool) (*Claims, error) { tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) { return jwtSecret, nil }) if tokenClaims != nil { - if clims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid { - return clims, nil + if clims, ok := tokenClaims.Claims.(*Claims); ok { + if valid && tokenClaims.Valid { + return clims, nil + } else if !valid { + return clims, nil + } } } return nil, err diff --git a/pkg/utils/jwt/jwt_helper.go b/pkg/utils/jwt/jwt_helper.go index 9c124b1..2c18e67 100644 --- a/pkg/utils/jwt/jwt_helper.go +++ b/pkg/utils/jwt/jwt_helper.go @@ -2,7 +2,7 @@ * @Author: LinkLeong link@icewhale.com * @Date: 2022-06-17 14:01:25 * @LastEditors: LinkLeong - * @LastEditTime: 2022-07-11 18:21:40 + * @LastEditTime: 2022-07-18 17:31:15 * @FilePath: /CasaOS/pkg/utils/jwt/jwt_helper.go * @Description: * @Website: https://www.casaos.io @@ -33,10 +33,13 @@ func JWT() gin.HandlerFunc { code = common_err.INVALID_PARAMS } - claims, err := ParseToken(token) + claims, err := ParseToken(token, false) + //_, err := ParseToken(token) if err != nil { code = common_err.ERROR_AUTH_TOKEN + } else if (c.Request.URL.Path == "/v1/file" || c.Request.URL.Path == "/v1/image" || c.Request.URL.Path == "/v1/file/upload" || c.Request.URL.Path == "/v1/batch") && claims.VerifyIssuer("casaos", true) { + //Special treatment } else if !claims.VerifyExpiresAt(time.Now(), true) || !claims.VerifyIssuer("casaos", true) { code = common_err.ERROR_AUTH_TOKEN } diff --git a/route/init.go b/route/init.go index 7a7ff1f..7aedb2f 100644 --- a/route/init.go +++ b/route/init.go @@ -2,7 +2,6 @@ package route import ( "os" - "runtime" "strconv" "strings" @@ -82,31 +81,11 @@ func CheckToken2_11() { config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) } - sysType := runtime.GOOS - if len(config.FileSettingInfo.DownloadDir) == 0 { - downloadPath := "/DATA/Downloads" - if sysType == "windows" { - downloadPath = "C:\\CasaOS\\DATA\\Downloads" - } - if sysType == "darwin" { - downloadPath = "./CasaOS/DATA/Downloads" - } - config.Cfg.Section("file").Key("DownloadDir").SetValue(downloadPath) - config.FileSettingInfo.DownloadDir = downloadPath - file.IsNotExistMkDir(config.FileSettingInfo.DownloadDir) - config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) - } - if len(config.UserInfo.Description) == 0 { config.Cfg.Section("user").Key("Description").SetValue("nothing") config.UserInfo.Description = "nothing" config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) } - if len(config.ServerInfo.Handshake) == 0 { - config.Cfg.Section("server").Key("Handshake").SetValue("socket.casaos.io") - config.ServerInfo.Handshake = "socket.casaos.io" - config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) - } if service.MyService.System().GetSysInfo().KernelArch == "aarch64" && config.ServerInfo.USBAutoMount != "True" && strings.Contains(service.MyService.System().GetDeviceTree(), "Raspberry Pi") { service.MyService.System().UpdateUSBAutoMount("False") diff --git a/route/route.go b/route/route.go index 69c16e7..4466662 100644 --- a/route/route.go +++ b/route/route.go @@ -1,5 +1,3 @@ -// 这是一个用来反馈 API 设计的 PR,不要 merge - package route import ( @@ -34,14 +32,14 @@ func InitRouter() *gin.Engine { // c.Redirect(http.StatusMovedPermanently, "ui/") //}) - r.POST("/v1/user/register", v1.PostUserRegister) - r.POST("/v1/user/login", v1.PostUserLogin) + r.POST("/v1/users/register", v1.PostUserRegister) + r.POST("/v1/users/login", v1.PostUserLogin) r.GET("/v1/users/name", v1.GetUserAllUsername) //all/name r.POST("/v1/user/refresh", v1.PostUserRefreshToken) // No short-term modifications - r.GET("/v1/user/image", v1.GetUserImage) + r.GET("/v1/users/image", v1.GetUserImage) - r.GET("/v1/user/status", v1.GetUserStatus) //init/check + r.GET("/v1/users/status", v1.GetUserStatus) //init/check //r.GET("/v1/guide/check", v1.GetGuideCheck) // /v1/sys/guide_check r.GET("/v1/sys/debug", v1.GetSystemConfigDebug) // //debug @@ -51,41 +49,33 @@ func InitRouter() *gin.Engine { v1Group.Use(jwt2.JWT()) { - v1UserGroup := v1Group.Group("/user") - v1UserGroup.Use() - { - - v1UserGroup.GET("/current", v1.GetUserInfo) - v1UserGroup.PUT("/current", v1.PutUserInfo) - - v1UserGroup.GET("/current/custom/:key", v1.GetUserCustomConf) - v1UserGroup.POST("/current/custom/:key", v1.PostUserCustomConf) - v1UserGroup.DELETE("/current/custom/:key", v1.DeleteUserCustomConf) - - v1UserGroup.POST("/current/image/:key", v1.PostUserUploadImage) - //v1UserGroup.POST("/file/image/:key", v1.PostUserFileImage) - v1UserGroup.DELETE("/current/image", v1.DeleteUserImage) - - //v1UserGroup.PUT("/avatar", v1.PutUserAvatar) - //v1UserGroup.GET("/avatar", v1.GetUserAvatar) - v1UserGroup.DELETE("/:id", v1.DeleteUser) - v1UserGroup.GET("/:username", v1.GetUserInfoByUsername) - - } v1UsersGroup := v1Group.Group("/users") v1UsersGroup.Use() { + v1UsersGroup.GET("/current", v1.GetUserInfo) + v1UsersGroup.PUT("/current", v1.PutUserInfo) + v1UsersGroup.PUT("/current/password", v1.PutUserPassword) + + v1UsersGroup.GET("/current/custom/:key", v1.GetUserCustomConf) + v1UsersGroup.POST("/current/custom/:key", v1.PostUserCustomConf) + v1UsersGroup.DELETE("/current/custom/:key", v1.DeleteUserCustomConf) + + v1UsersGroup.POST("/current/image/:key", v1.PostUserUploadImage) + //v1UserGroup.POST("/file/image/:key", v1.PostUserFileImage) + v1UsersGroup.DELETE("/current/image", v1.DeleteUserImage) + + //v1UserGroup.PUT("/avatar", v1.PutUserAvatar) + //v1UserGroup.GET("/avatar", v1.GetUserAvatar) + v1UsersGroup.DELETE("/:id", v1.DeleteUser) + v1UsersGroup.GET("/:username", v1.GetUserInfoByUsername) v1UsersGroup.DELETE("", v1.DeleteUserAll) } - v1AppGroup := v1Group.Group("/app") - v1AppGroup.Use() - { - v1AppGroup.GET("/:id", v1.AppInfo) - } + v1AppsGroup := v1Group.Group("/apps") v1AppsGroup.Use() { v1AppsGroup.GET("", v1.AppList) //list + v1AppsGroup.GET("/:id", v1.AppInfo) } v1ContainerGroup := v1Group.Group("/container") v1ContainerGroup.Use() @@ -127,6 +117,7 @@ func InitRouter() *gin.Engine { v1SysGroup.GET("/hardware", v1.GetSystemHardwareInfo) //hardware/info v1SysGroup.GET("/wsssh", v1.WsSsh) + v1SysGroup.POST("/ssh-login", v1.PostSshLogin) //v1SysGroup.GET("/config", v1.GetSystemConfig) //delete //v1SysGroup.POST("/config", v1.PostSetSystemConfig) v1SysGroup.GET("/logs", v1.GetCasaOSErrorLogs) //error/logs @@ -134,15 +125,19 @@ func InitRouter() *gin.Engine { //v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig)//delete v1SysGroup.POST("/stop", v1.PostKillCasaOS) - v1SysGroup.GET("/utilization", v1.GetSystemUtilization) - v1SysGroup.GET("/cpu", v1.GetSystemCupInfo) - v1SysGroup.GET("/mem", v1.GetSystemMemInfo) - v1SysGroup.GET("/disk", v1.GetSystemDiskInfo) - v1SysGroup.GET("/network", v1.GetSystemNetInfo) + v1SysGroup.GET("/utilization", v1.GetSystemUtilization) + // v1SysGroup.GET("/cpu", v1.GetSystemCupInfo) + // v1SysGroup.GET("/mem", v1.GetSystemMemInfo) + // v1SysGroup.GET("/disk", v1.GetSystemDiskInfo) + // v1SysGroup.GET("/network", v1.GetSystemNetInfo) + v1SysGroup.PUT("/usb-auto-mount", v1.PutSystemUSBAutoMount) ///sys/usb/:status v1SysGroup.GET("/usb-auto-mount", v1.GetSystemUSBAutoMount) ///sys/usb/status + v1SysGroup.GET("/server-info", nil) + v1SysGroup.PUT("/server-info", nil) + v1SysGroup.GET("/apps-state", v1.GetSystemAppsStatus) v1SysGroup.GET("/port", v1.GetCasaOSPort) v1SysGroup.PUT("/port", v1.PutCasaOSPort) } @@ -156,9 +151,9 @@ func InitRouter() *gin.Engine { v1FileGroup := v1Group.Group("/file") v1FileGroup.Use() { - v1FileGroup.GET("/", v1.GetDownloadSingleFile) //download/:path - v1FileGroup.POST("/", v1.PostCreateFile) - v1FileGroup.PUT("/", v1.PutFileContent) + v1FileGroup.GET("", v1.GetDownloadSingleFile) //download/:path + v1FileGroup.POST("", v1.PostCreateFile) + v1FileGroup.PUT("", v1.PutFileContent) v1FileGroup.PUT("/name", v1.RenamePath) //file/rename v1FileGroup.GET("/content", v1.GetFilerContent) //file/read @@ -172,32 +167,32 @@ func InitRouter() *gin.Engine { v1FolderGroup.Use() { v1FolderGroup.PUT("/name", v1.RenamePath) - v1FolderGroup.GET("/", v1.DirPath) ///file/dirpath - v1FolderGroup.POST("/", v1.MkdirAll) ///file/mkdir + v1FolderGroup.GET("", v1.DirPath) ///file/dirpath + v1FolderGroup.POST("", v1.MkdirAll) ///file/mkdir } v1BatchGroup := v1Group.Group("/batch") v1BatchGroup.Use() { - v1BatchGroup.DELETE("/", v1.DeleteFile) //file/delete + v1BatchGroup.DELETE("", v1.DeleteFile) //file/delete v1BatchGroup.DELETE("/:id/task", v1.DeleteOperateFileOrDir) v1BatchGroup.POST("/task", v1.PostOperateFileOrDir) //file/operate - v1BatchGroup.GET("/", v1.GetDownloadFile) + v1BatchGroup.GET("", v1.GetDownloadFile) } v1ImageGroup := v1Group.Group("/image") v1ImageGroup.Use() { - v1ImageGroup.GET("/", v1.GetFileImage) + v1ImageGroup.GET("", v1.GetFileImage) } - v1DiskGroup := v1Group.Group("/disk") - v1DiskGroup.Use() + v1DisksGroup := v1Group.Group("/disks") + v1DisksGroup.Use() { //v1DiskGroup.GET("/check", v1.GetDiskCheck) //delete - v1DiskGroup.GET("/", v1.GetDiskInfo) - - v1DiskGroup.POST("/", v1.PostMountDisk) + //v1DisksGroup.GET("", v1.GetDiskInfo) + //v1DisksGroup.POST("", v1.PostMountDisk) + v1DisksGroup.GET("", v1.GetDiskList) // //format storage // v1DiskGroup.POST("/format", v1.PostDiskFormat) @@ -209,24 +204,18 @@ func InitRouter() *gin.Engine { //v1DiskGroup.GET("/type", v1.FormatDiskType)//delete - v1DiskGroup.DELETE("/part", v1.RemovePartition) //disk/delpart + v1DisksGroup.DELETE("/part", v1.RemovePartition) //disk/delpart } v1StorageGroup := v1Group.Group("/storage") v1StorageGroup.Use() { - v1StorageGroup.POST("/", v1.PostDiskAddPartition) - //v1StorageGroup.GET("/", v1.GetStorageList) - } + v1StorageGroup.POST("", v1.PostDiskAddPartition) - v1DisksGroup := v1Group.Group("/disks") - v1DisksGroup.Use() - { - //v1UsbGroup.GET("/", v1.GetUSBList) - v1DisksGroup.GET("/", v1.GetDiskList) - } + v1StorageGroup.PUT("", v1.PostDiskFormat) - v1Group.GET("/sync/config", v1.GetSyncConfig) + v1StorageGroup.DELETE("", v1.PostDiskUmount) + } } return r } diff --git a/route/v1/app.go b/route/v1/app.go index 97cc327..7d6b6ed 100644 --- a/route/v1/app.go +++ b/route/v1/app.go @@ -3,7 +3,6 @@ package v1 import ( "encoding/json" "io/ioutil" - "net/http" "strconv" "github.com/IceWhaleTech/CasaOS/model" @@ -37,10 +36,14 @@ func AppList(c *gin.Context) { categoryId := c.DefaultQuery("category_id", "0") key := c.DefaultQuery("key", "") if len(index) == 0 || len(size) == 0 || len(t) == 0 || len(categoryId) == 0 { - c.JSON(http.StatusOK, &model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, &model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + return + } + collection, err := service.MyService.Casa().GetServerList(index, size, t, categoryId, key) + if err != nil { + c.JSON(common_err.SERVICE_ERROR, &model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } - collection := service.MyService.Casa().GetServerList(index, size, t, categoryId, key) // for i := 0; i < len(recommend); i++ { // ct, _ := service.MyService.Docker().DockerListByImage(recommend[i].Image, recommend[i].ImageVersion) // if ct != nil { @@ -64,7 +67,7 @@ func AppList(c *gin.Context) { data["list"] = collection.List data["community"] = collection.Community - c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } // @Summary 获取一个可用端口 @@ -84,7 +87,7 @@ func GetPort(c *gin.Context) { ok = !port2.IsPortAvailable(p, t) } // @tiger 这里最好封装成 {'port': ...} 的形式,来体现出参的上下文 - c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: p}) + c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: p}) } // @Summary 检查端口是否可用 @@ -99,7 +102,7 @@ func GetPort(c *gin.Context) { func PortCheck(c *gin.Context) { p, _ := strconv.Atoi(c.Param("port")) t := c.DefaultQuery("type", "tcp") - c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: port2.IsPortAvailable(p, t)}) + c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: port2.IsPortAvailable(p, t)}) } // @Summary 我的应用列表 @@ -118,10 +121,10 @@ func MyAppList(c *gin.Context) { position, _ := strconv.ParseBool(c.DefaultQuery("position", "true")) list, unTranslation := service.MyService.App().GetMyList(index, size, position) data := make(map[string]interface{}, 2) - data["casaos-apps"] = list - data["local-apps"] = unTranslation + data["casaos_apps"] = list + data["local_apps"] = unTranslation - c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } // @Summary my app hardware usage list @@ -133,7 +136,7 @@ func MyAppList(c *gin.Context) { // @Router /app/usage [get] func AppUsageList(c *gin.Context) { list := service.MyService.App().GetHardwareUsage() - c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list}) + c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list}) } // @Summary 应用详情 @@ -148,7 +151,11 @@ func AppInfo(c *gin.Context) { id := c.Param("id") language := c.GetHeader("Language") - info := service.MyService.Casa().GetServerAppInfo(id, "", language) + info, err := service.MyService.Casa().GetServerAppInfo(id, "", language) + if err != nil { + c.JSON(common_err.SERVICE_ERROR, &model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) + return + } if info.NetworkModel != "host" { for i := 0; i < len(info.Ports); i++ { if p, _ := strconv.Atoi(info.Ports[i].ContainerPort); port2.IsPortAvailable(p, info.Ports[i].Protocol) { @@ -215,7 +222,7 @@ func AppInfo(c *gin.Context) { info.MaxMemory = (service.MyService.System().GetMemInfo()["total"]).(uint64) >> 20 - c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: info}) + c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: info}) } // @Summary 获取远程分类列表 @@ -226,7 +233,11 @@ func AppInfo(c *gin.Context) { // @Success 200 {string} string "ok" // @Router /app/category [get] func CategoryList(c *gin.Context) { - list := service.MyService.Casa().GetServerCategoryList() + list, err := service.MyService.Casa().GetServerCategoryList() + if err != nil { + c.JSON(common_err.SERVICE_ERROR, &model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) + return + } var count uint = 0 for _, category := range list { count += category.Count @@ -235,7 +246,7 @@ func CategoryList(c *gin.Context) { rear := append([]model.CategoryList{}, list[0:]...) list = append(list[:0], model.CategoryList{Count: count, Name: "All", Font: "apps"}) list = append(list, rear...) - c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list}) + c.JSON(common_err.SUCCESS, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list}) } // @Summary 分享该应用配置 @@ -248,5 +259,5 @@ func CategoryList(c *gin.Context) { func ShareAppFile(c *gin.Context) { str, _ := ioutil.ReadAll(c.Request.Body) content := service.MyService.Casa().ShareAppFile(str) - c.JSON(http.StatusOK, json.RawMessage(content)) + c.JSON(common_err.SUCCESS, json.RawMessage(content)) } diff --git a/route/v1/disk.go b/route/v1/disk.go index 8a8db65..75eefae 100644 --- a/route/v1/disk.go +++ b/route/v1/disk.go @@ -9,6 +9,7 @@ import ( "time" "github.com/IceWhaleTech/CasaOS/model" + "github.com/IceWhaleTech/CasaOS/model/notify" "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err" "github.com/IceWhaleTech/CasaOS/pkg/utils/encryption" "github.com/IceWhaleTech/CasaOS/pkg/utils/file" @@ -28,6 +29,12 @@ var diskMap = make(map[string]string) // @Success 200 {string} string "ok" // @Router /disk/list [get] func GetDiskList(c *gin.Context) { + path := c.Query("path") + if len(path) > 0 { + m := service.MyService.Disk().GetDiskInfo(path) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m}) + return + } t := c.DefaultQuery("type", "") list := service.MyService.Disk().LSBLK(false) if t == "usb" { @@ -54,7 +61,7 @@ func GetDiskList(c *gin.Context) { data = append(data, temp) } } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) return } @@ -183,7 +190,7 @@ func GetDiskList(c *gin.Context) { data["storage"] = storage data["avail"] = avail - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } // @Summary get disk list @@ -243,16 +250,16 @@ func FormatDiskType(c *gin.Context) { // @Router /disk/delpart [delete] func RemovePartition(c *gin.Context) { js := make(map[string]string) - c.BindJSON(&js) + c.ShouldBind(&js) path := js["path"] if len(path) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) } var p = path[:len(path)-1] var n = path[len(path)-1:] service.MyService.Disk().DelPartition(p, n) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary add storage @@ -269,30 +276,30 @@ func RemovePartition(c *gin.Context) { func PostDiskAddPartition(c *gin.Context) { js := make(map[string]string) - c.BindJSON(&js) + c.ShouldBind(&js) path := js["path"] name := js["name"] format, _ := strconv.ParseBool(js["format"]) if len(name) == 0 || len(path) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } if _, ok := diskMap[path]; ok { - c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)}) return } if !file.CheckNotExist("/DATA/" + name) { // /mnt/name exist - c.JSON(http.StatusOK, model.Result{Success: common_err.NAME_NOT_AVAILABLE, Message: common_err.GetMsg(common_err.NAME_NOT_AVAILABLE)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.NAME_NOT_AVAILABLE, Message: common_err.GetMsg(common_err.NAME_NOT_AVAILABLE)}) return } diskMap[path] = "busying" currentDisk := service.MyService.Disk().GetDiskInfo(path) if !format { if len(currentDisk.Children) != 1 || !(len(currentDisk.Children) > 0 && currentDisk.Children[0].FsType == "ext4") { - c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_NEEDS_FORMAT, Message: common_err.GetMsg(common_err.DISK_NEEDS_FORMAT)}) delete(diskMap, path) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_NEEDS_FORMAT, Message: common_err.GetMsg(common_err.DISK_NEEDS_FORMAT)}) return } } else { @@ -311,7 +318,7 @@ func PostDiskAddPartition(c *gin.Context) { } currentDisk = service.MyService.Disk().GetDiskInfo(path) if len(currentDisk.Children) != 1 { - c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_NEEDS_FORMAT, Message: common_err.GetMsg(common_err.DISK_NEEDS_FORMAT)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_NEEDS_FORMAT, Message: common_err.GetMsg(common_err.DISK_NEEDS_FORMAT)}) return } @@ -330,105 +337,61 @@ func PostDiskAddPartition(c *gin.Context) { service.MyService.Disk().RemoveLSBLKCache() delete(diskMap, path) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + + //send notify to client + msg := notify.StorageMessage{} + msg.Action = "ADDED" + msg.Path = currentDisk.Children[0].Path + msg.Volume = mountPath + msg.Size = currentDisk.Children[0].Size + msg.Type = currentDisk.Children[0].Tran + service.MyService.Notify().SendStorageBySocket(msg) + + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } -// @Summary add mount point -// @Produce application/json -// @Accept multipart/form-data -// @Tags disk -// @Security ApiKeyAuth -// @Param path body string true "for example: /dev/sda1" -// @Param action body string true "mount,umount,format" -// @Param serial formData string true "disk id" +// @Param pwd formData string true "user password" +// @Param volume formData string true "mount point" // @Success 200 {string} string "ok" -// @Router /disk/mount [post] -func PostMountDisk(c *gin.Context) { - // for example: path=/dev/sda1 +// @Router /disk/format [post] +func PostDiskFormat(c *gin.Context) { id := c.GetHeader("user_id") js := make(map[string]string) - c.BindJSON(&js) - + c.ShouldBind(&js) path := js["path"] - serial := js["serial"] - action := js["action"] t := "ext4" - password := js["password"] + pwd := js["password"] volume := js["volume"] user := service.MyService.User().GetUserAllInfoById(id) - // volume := js["volume"] - if action == "mount" { - mountPath := "/DATA/volume" - var list = service.MyService.Disk().GetSerialAll() - var pathMapList = make(map[string]string, len(list)) - for _, v := range list { - pathMapList[v.MountPoint] = "1" - } - - for i := 0; i < len(list)+1; i++ { - if _, ok := pathMapList[mountPath+strconv.Itoa(i)]; !ok { - mountPath = mountPath + strconv.Itoa(i) - break - } - } - - //mount dir - service.MyService.Disk().MountDisk(path, mountPath) - - m := model2.SerialDisk{} - m.MountPoint = mountPath - m.Path = path - m.UUID = serial - m.State = 0 - service.MyService.Disk().SaveMountPoint(m) - } else if action == "umount" { - if len(path) == 0 || len(volume) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) - return - } - if encryption.GetMD5ByStr(password) != user.Password { - c.JSON(http.StatusOK, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)}) - return - } - - if _, ok := diskMap[path]; ok { - c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)}) - return - } - - service.MyService.Disk().UmountPointAndRemoveDir(path) - //delete data - service.MyService.Disk().DeleteMountPoint(path, volume) - service.MyService.Disk().RemoveLSBLKCache() - } else if action == "format" { - - if encryption.GetMD5ByStr(password) != user.Password { - c.JSON(http.StatusOK, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)}) - return - } - - if len(path) == 0 || len(t) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) - return - } - if _, ok := diskMap[path]; ok { - c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)}) - return - } - diskMap[path] = "busying" - service.MyService.Disk().UmountPointAndRemoveDir(path) - format := service.MyService.Disk().FormatDisk(path, t) - if len(format) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.FORMAT_ERROR, Message: common_err.GetMsg(common_err.FORMAT_ERROR)}) - delete(diskMap, path) - return - } - service.MyService.Disk().MountDisk(path, volume) - service.MyService.Disk().RemoveLSBLKCache() - delete(diskMap, path) + if user.Id == 0 { + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) + return + } + if encryption.GetMD5ByStr(pwd) != user.Password { + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)}) + return } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + if len(path) == 0 || len(t) == 0 { + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + return + } + if _, ok := diskMap[path]; ok { + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)}) + return + } + diskMap[path] = "busying" + service.MyService.Disk().UmountPointAndRemoveDir(path) + format := service.MyService.Disk().FormatDisk(path, t) + if len(format) == 0 { + delete(diskMap, path) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FORMAT_ERROR, Message: common_err.GetMsg(common_err.FORMAT_ERROR), Data: "22222"}) + return + } + service.MyService.Disk().MountDisk(path, volume) + service.MyService.Disk().RemoveLSBLKCache() + delete(diskMap, path) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: "1111"}) } // @Summary remove mount point @@ -442,8 +405,47 @@ func PostMountDisk(c *gin.Context) { // @Success 200 {string} string "ok" // @Router /disk/umount [post] func PostDiskUmount(c *gin.Context) { + id := c.GetHeader("user_id") + js := make(map[string]string) + c.ShouldBind(&js) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + path := js["path"] + mountPoint := js["volume"] + pwd := js["password"] + + if len(path) == 0 || len(mountPoint) == 0 { + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + return + } + user := service.MyService.User().GetUserAllInfoById(id) + if user.Id == 0 { + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) + return + } + if encryption.GetMD5ByStr(pwd) != user.Password { + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)}) + return + } + + if _, ok := diskMap[path]; ok { + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)}) + return + } + + service.MyService.Disk().UmountPointAndRemoveDir(path) + //delete data + service.MyService.Disk().DeleteMountPoint(path, mountPoint) + service.MyService.Disk().RemoveLSBLKCache() + + //send notify to client + msg := notify.StorageMessage{} + msg.Action = "REMOVED" + msg.Path = path + msg.Volume = mountPoint + msg.Size = 0 + msg.Type = "" + service.MyService.Notify().SendStorageBySocket(msg) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary confirm delete disk @@ -481,7 +483,7 @@ func GetDiskCheck(c *gin.Context) { for _, v := range dbList { if _, ok := mapList[v.UUID]; !ok { //disk undefind - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: "disk undefind"}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: "disk undefind"}) return } } diff --git a/route/v1/docker.go b/route/v1/docker.go index 98265ab..4c2cd7f 100644 --- a/route/v1/docker.go +++ b/route/v1/docker.go @@ -4,6 +4,7 @@ import ( "bytes" json2 "encoding/json" "net/http" + "os/exec" "path/filepath" "strconv" "strings" @@ -15,6 +16,7 @@ import ( "github.com/IceWhaleTech/CasaOS/pkg/docker" "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err" "github.com/IceWhaleTech/CasaOS/pkg/utils/file" + "github.com/IceWhaleTech/CasaOS/pkg/utils/loger" port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port" "github.com/IceWhaleTech/CasaOS/pkg/utils/random" "github.com/IceWhaleTech/CasaOS/service" @@ -25,6 +27,7 @@ import ( "github.com/gorilla/websocket" "github.com/jinzhu/copier" uuid "github.com/satori/go.uuid" + "go.uber.org/zap" "golang.org/x/crypto/ssh" ) @@ -41,14 +44,14 @@ func DockerTerminal(c *gin.Context) { row := c.DefaultQuery("rows", "30") conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } defer conn.Close() container := c.Param("id") hr, err := service.Exec(container, row, col) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } // 关闭I/O流 @@ -63,15 +66,38 @@ func DockerTerminal(c *gin.Context) { docker.WsReaderCopy(conn, hr.Conn) } -//打开本机的ssh接口 -func WsSsh(c *gin.Context) { +func PostSshLogin(c *gin.Context) { j := make(map[string]string) - c.BindJSON(j) - userName := j["user_name"] + c.ShouldBind(&j) + userName := j["username"] password := j["password"] port := j["port"] + if userName == "" || password == "" || port == "" { + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: "Username or password or port is empty"}) + return + } + _, err := docker.NewSshClient(userName, password, port) + if err != nil { + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.CLIENT_ERROR), Data: "Please check if the username and port are correct, and make sure that ssh server is installed."}) + loger.Error("connect ssh error", zap.Any("error", err)) + return + } + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) +} + +func WsSsh(c *gin.Context) { + _, e := exec.LookPath("ssh") + if e != nil { + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: "ssh server not found"}) + return + } + + userName := c.Query("username") + password := c.Query("password") + port := c.Query("port") wsConn, _ := upgrader.Upgrade(c.Writer, c.Request, nil) var logBuff = new(bytes.Buffer) + quitChan := make(chan bool, 3) // user := "" // password := "" @@ -82,7 +108,9 @@ func WsSsh(c *gin.Context) { for login != 0 { var err error - + if userName == "" || password == "" || port == "" { + wsConn.WriteMessage(websocket.TextMessage, []byte("username or password or port is empty")) + } // wsConn.WriteMessage(websocket.TextMessage, []byte("login:")) // user = docker.ReceiveWsMsgUser(wsConn, logBuff) // wsConn.WriteMessage(websocket.TextMessage, []byte("\r\n\x1b[0m")) @@ -129,7 +157,7 @@ func WsSsh(c *gin.Context) { func InstallApp(c *gin.Context) { var appInfo model.ServerAppList m := model.CustomizationPostData{} - c.BindJSON(&m) + c.ShouldBind(&m) const CUSTOM = "custom" var dockerImage string @@ -139,20 +167,22 @@ func InstallApp(c *gin.Context) { if len(m.Protocol) == 0 { m.Protocol = "http" } - m.Label = strings.Replace(m.Name, " ", "_", -1) + m.ContainerName = strings.Replace(m.Label, " ", "_", -1) if m.Origin != CUSTOM { - oldName := m.Label + oldName := m.ContainerName + oldLabel := m.Label for i := 0; true; i++ { if i != 0 { - m.Label = oldName + "-" + strconv.Itoa(i) + m.ContainerName = oldName + "-" + strconv.Itoa(i) + m.Label = oldLabel + "-" + strconv.Itoa(i) } - if _, err := service.MyService.Docker().DockerListByName(m.Label); err != nil { + if _, err := service.MyService.Docker().DockerListByName(m.ContainerName); err != nil { break } } } else { - if _, err := service.MyService.Docker().DockerListByName(m.Label); err == nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR_APP_NAME_EXIST, Message: common_err.GetMsg(common_err.ERROR_APP_NAME_EXIST)}) + if _, err := service.MyService.Docker().DockerListByName(m.ContainerName); err == nil { + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.ERROR_APP_NAME_EXIST, Message: common_err.GetMsg(common_err.ERROR_APP_NAME_EXIST)}) return } @@ -163,7 +193,7 @@ func InstallApp(c *gin.Context) { //c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) portMap, _ := strconv.Atoi(m.PortMap) if !port2.IsPortAvailable(portMap, "tcp") { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + m.PortMap}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + m.PortMap}) return } } @@ -185,25 +215,25 @@ func InstallApp(c *gin.Context) { if u.Protocol == "udp" { t, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(t, "udp") { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } } else if u.Protocol == "tcp" { te, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(te, "tcp") { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } } else if u.Protocol == "both" { t, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(t, "udp") { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } te, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(te, "tcp") { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } } @@ -211,7 +241,7 @@ func InstallApp(c *gin.Context) { if m.Origin == CUSTOM { for _, device := range m.Devices { if file.CheckNotExist(device.Path) { - c.JSON(http.StatusOK, model.Result{Success: common_err.DEVICE_NOT_EXIST, Message: device.Path + "," + common_err.GetMsg(common_err.DEVICE_NOT_EXIST)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.DEVICE_NOT_EXIST, Message: device.Path + "," + common_err.GetMsg(common_err.DEVICE_NOT_EXIST)}) return } @@ -335,7 +365,7 @@ func InstallApp(c *gin.Context) { // echo -e "hellow\nworld" >> //step:启动容器 - err = service.MyService.Docker().DockerContainerStart(m.Label) + err = service.MyService.Docker().DockerContainerStart(m.ContainerName) if err != nil { //service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":90}", 100) notify := notify.Application{} @@ -358,7 +388,7 @@ func InstallApp(c *gin.Context) { } //step: 启动成功 检查容器状态确认启动成功 - container, err := service.MyService.Docker().DockerContainerInfo(m.Label) + container, err := service.MyService.Docker().DockerContainerInfo(m.ContainerName) if err != nil && container.ContainerJSONBase.State.Running { notify := notify.Application{} notify.Icon = m.Icon @@ -391,7 +421,7 @@ func InstallApp(c *gin.Context) { }() - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m.Label}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m.Label}) } @@ -412,7 +442,7 @@ func InstallApp(c *gin.Context) { // // appInfo := service.MyService.App().GetServerAppInfo(appId) // // m := model.CustomizationPostData{} -// c.BindJSON(&m) +// c.ShouldBind(&m) // //检查端口 // if len(m.PortMap) == 0 || m.PortMap == "0" { // c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) @@ -589,27 +619,27 @@ func UnInstallApp(c *gin.Context) { appId := c.Param("id") if len(appId) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } //info := service.MyService.App().GetUninstallInfo(appId) info, err := service.MyService.Docker().DockerContainerInfo(appId) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } //step:停止容器 err = service.MyService.Docker().DockerContainerStop(appId) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.UNINSTALL_APP_ERROR, Message: common_err.GetMsg(common_err.UNINSTALL_APP_ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.UNINSTALL_APP_ERROR, Message: common_err.GetMsg(common_err.UNINSTALL_APP_ERROR), Data: err.Error()}) return } err = service.MyService.Docker().DockerContainerRemove(appId, false) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.UNINSTALL_APP_ERROR, Message: common_err.GetMsg(common_err.UNINSTALL_APP_ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.UNINSTALL_APP_ERROR, Message: common_err.GetMsg(common_err.UNINSTALL_APP_ERROR), Data: err.Error()}) return } @@ -674,7 +704,7 @@ func UnInstallApp(c *gin.Context) { notify.Success = true notify.Finished = true service.MyService.Notify().SendUninstallAppBySocket(notify) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } @@ -690,10 +720,10 @@ func UnInstallApp(c *gin.Context) { func ChangAppState(c *gin.Context) { appId := c.Param("id") js := make(map[string]string) - c.BindJSON(&js) + c.ShouldBind(&js) state := js["state"] if len(appId) == 0 || len(state) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } var err error @@ -707,17 +737,17 @@ func ChangAppState(c *gin.Context) { } if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } info, err := service.MyService.App().GetContainerInfo(appId) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } // @tiger - 用 {'state': ...} 来体现出参上下文 - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: info.State}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: info.State}) } // @Summary 查看容器日志 @@ -731,7 +761,7 @@ func ChangAppState(c *gin.Context) { func ContainerLog(c *gin.Context) { appId := c.Param("id") log, _ := service.MyService.Docker().DockerContainerLog(appId) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: log}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: log}) } // @Summary 获取容器状态 @@ -748,7 +778,7 @@ func GetContainerState(c *gin.Context) { //t := c.DefaultQuery("type", "0") containerInfo, e := service.MyService.App().GetSimpleContainerInfo(id) if e != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: e.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: e.Error()}) return } @@ -761,7 +791,7 @@ func GetContainerState(c *gin.Context) { // data["app"] = appInfo // } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } // @Summary 更新设置 @@ -781,10 +811,10 @@ func UpdateSetting(c *gin.Context) { id := c.Param("id") const CUSTOM = "custom" m := model.CustomizationPostData{} - c.BindJSON(&m) + c.ShouldBind(&m) if len(id) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } //var cpd model.CustomizationPostData @@ -804,7 +834,7 @@ func UpdateSetting(c *gin.Context) { portMap, _ := strconv.Atoi(m.PortMap) if !port2.IsPortAvailable(portMap, "tcp") { service.MyService.Docker().DockerContainerStart(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + m.PortMap}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + m.PortMap}) return } @@ -814,28 +844,28 @@ func UpdateSetting(c *gin.Context) { t, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(t, "udp") { service.MyService.Docker().DockerContainerStart(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } } else if u.Protocol == "tcp" { te, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(te, "tcp") { service.MyService.Docker().DockerContainerStart(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } } else if u.Protocol == "both" { t, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(t, "udp") { service.MyService.Docker().DockerContainerStart(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } te, _ := strconv.Atoi(u.CommendPort) if !port2.IsPortAvailable(te, "tcp") { service.MyService.Docker().DockerContainerStart(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort}) return } } @@ -846,9 +876,9 @@ func UpdateSetting(c *gin.Context) { containerId, err := service.MyService.Docker().DockerContainerCreate(m.Image, m) if err != nil { - service.MyService.Docker().DockerContainerUpdateName(m.Label, id) + service.MyService.Docker().DockerContainerUpdateName(m.ContainerName, id) service.MyService.Docker().DockerContainerStart(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR)}) return } // echo -e "hellow\nworld" >> @@ -857,7 +887,7 @@ func UpdateSetting(c *gin.Context) { err = service.MyService.Docker().DockerContainerStart(containerId) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR)}) return } service.MyService.Docker().DockerContainerRemove(id, true) @@ -928,7 +958,7 @@ func UpdateSetting(c *gin.Context) { //service.MyService.App().UpdateApp(appInfo) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary update app version @@ -943,20 +973,20 @@ func PutAppUpdate(c *gin.Context) { id := c.Param("id") if len(id) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } inspect, err := service.MyService.Docker().DockerContainerInfo(id) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } imageLatest := strings.Split(inspect.Config.Image, ":")[0] + ":latest" err = service.MyService.Docker().DockerPullImage(imageLatest, "", "") if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } @@ -969,7 +999,7 @@ func PutAppUpdate(c *gin.Context) { if err != nil { service.MyService.Docker().DockerContainerUpdateName(inspect.Name, id) service.MyService.Docker().DockerContainerStart(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR)}) return } @@ -977,13 +1007,13 @@ func PutAppUpdate(c *gin.Context) { err = service.MyService.Docker().DockerContainerStart(containerId) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR)}) return } service.MyService.Docker().DockerContainerRemove(id, true) delete(service.NewVersionApp, id) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary 获取容器详情 @@ -1012,7 +1042,7 @@ func ContainerInfo(c *gin.Context) { info, err := service.MyService.Docker().DockerContainerInfo(appId) if err != nil { //todo 需要自定义错误 - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } con := struct { @@ -1028,7 +1058,7 @@ func ContainerInfo(c *gin.Context) { data["memory"] = service.MyService.System().GetMemInfo()["total"] // @tiger - 改成 total_memory,方便以后增加 free_memory 之类的字段 data["container"] = json2.RawMessage(containerInfo) data["info"] = con - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } func GetDockerNetworks(c *gin.Context) { @@ -1039,7 +1069,7 @@ func GetDockerNetworks(c *gin.Context) { list = append(list, map[string]string{"name": network.Name, "driver": network.Driver, "id": network.ID}) } } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list}) } // @Summary 获取依赖数据 @@ -1069,7 +1099,7 @@ func ContainerUpdateInfo(c *gin.Context) { info, err := service.MyService.Docker().DockerContainerInfo(appId) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: err.Error()}) return } var port model.PortArray @@ -1147,7 +1177,7 @@ func ContainerUpdateInfo(c *gin.Context) { } m.NetworkModel = string(info.HostConfig.NetworkMode) m.Description = info.Config.Labels["desc"] - m.Label = strings.ReplaceAll(info.Name, "/", "") + m.ContainerName = strings.ReplaceAll(info.Name, "/", "") m.PortMap = info.Config.Labels["web"] m.Devices = driver m.Envs = envs @@ -1167,7 +1197,11 @@ func ContainerUpdateInfo(c *gin.Context) { m.Cmd = info.Config.Cmd m.HostName = info.Config.Hostname m.Privileged = info.HostConfig.Privileged - m.Name = info.Config.Labels["name"] + name := info.Config.Labels["name"] + if len(name) == 0 { + name = strings.ReplaceAll(info.Name, "/", "") + } + m.Label = name m.Protocol = info.Config.Labels["protocol"] if m.Protocol == "" { diff --git a/route/v1/file.go b/route/v1/file.go index 4754802..ae9bd68 100644 --- a/route/v1/file.go +++ b/route/v1/file.go @@ -34,14 +34,14 @@ import ( func GetFilerContent(c *gin.Context) { filePath := c.Query("path") if len(filePath) == 0 { - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.CLIENT_ERROR, model.Result{ Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS), }) return } if !file.Exists(filePath) { - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.SERVICE_ERROR, model.Result{ Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST), }) @@ -50,7 +50,7 @@ func GetFilerContent(c *gin.Context) { //文件读取任务是将文件内容读取到内存中。 info, err := ioutil.ReadFile(filePath) if err != nil { - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.SERVICE_ERROR, model.Result{ Success: common_err.FILE_READ_ERROR, Message: common_err.GetMsg(common_err.FILE_READ_ERROR), Data: err.Error(), @@ -59,8 +59,7 @@ func GetFilerContent(c *gin.Context) { } result := string(info) - //返回结果 - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: result, @@ -103,7 +102,7 @@ func GetDownloadFile(c *gin.Context) { files := c.Query("files") if len(files) == 0 { - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.CLIENT_ERROR, model.Result{ Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS), }) @@ -112,7 +111,7 @@ func GetDownloadFile(c *gin.Context) { list := strings.Split(files, ",") for _, v := range list { if !file.Exists(v) { - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.SERVICE_ERROR, model.Result{ Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST), }) @@ -150,7 +149,7 @@ func GetDownloadFile(c *gin.Context) { extension, ar, err := file.GetCompressionAlgorithm(t) if err != nil { - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.CLIENT_ERROR, model.Result{ Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS), }) @@ -159,9 +158,9 @@ func GetDownloadFile(c *gin.Context) { err = ar.Create(c.Writer) if err != nil { - c.JSON(http.StatusOK, model.Result{ - Success: common_err.ERROR, - Message: common_err.GetMsg(common_err.ERROR), + c.JSON(common_err.SERVICE_ERROR, model.Result{ + Success: common_err.SERVICE_ERROR, + Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error(), }) return @@ -186,7 +185,7 @@ func GetDownloadFile(c *gin.Context) { func GetDownloadSingleFile(c *gin.Context) { filePath := c.Query("path") if len(filePath) == 0 { - c.JSON(http.StatusOK, model.Result{ + c.JSON(service.ClientCount, model.Result{ Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS), }) @@ -194,7 +193,7 @@ func GetDownloadSingleFile(c *gin.Context) { } fileTmp, err := os.Open(filePath) if err != nil { - c.JSON(http.StatusOK, model.Result{ + c.JSON(common_err.SERVICE_ERROR, model.Result{ Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST), }) @@ -282,7 +281,7 @@ func DirPath(c *gin.Context) { } } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: pathList}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: pathList}) } // @Summary rename file or dir @@ -296,15 +295,15 @@ func DirPath(c *gin.Context) { // @Router /file/rename [put] func RenamePath(c *gin.Context) { json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) op := json["old_path"] np := json["new_path"] if len(op) == 0 || len(np) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } success, err := service.MyService.System().RenameFile(op, np) - c.JSON(http.StatusOK, model.Result{Success: success, Message: common_err.GetMsg(success), Data: err}) + c.JSON(common_err.SUCCESS, model.Result{Success: success, Message: common_err.GetMsg(success), Data: err}) } // @Summary create folder @@ -317,11 +316,11 @@ func RenamePath(c *gin.Context) { // @Router /file/mkdir [post] func MkdirAll(c *gin.Context) { json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) path := json["path"] var code int if len(path) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } // decodedPath, err := url.QueryUnescape(path) @@ -330,7 +329,7 @@ func MkdirAll(c *gin.Context) { // return // } code, _ = service.MyService.System().MkdirAll(path) - c.JSON(http.StatusOK, model.Result{Success: code, Message: common_err.GetMsg(code)}) + c.JSON(common_err.SUCCESS, model.Result{Success: code, Message: common_err.GetMsg(code)}) } // @Summary create file @@ -343,11 +342,11 @@ func MkdirAll(c *gin.Context) { // @Router /file/create [post] func PostCreateFile(c *gin.Context) { json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) path := json["path"] var code int if len(path) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } // decodedPath, err := url.QueryUnescape(path) @@ -356,7 +355,7 @@ func PostCreateFile(c *gin.Context) { // return // } code, _ = service.MyService.System().CreateFile(path) - c.JSON(http.StatusOK, model.Result{Success: code, Message: common_err.GetMsg(code)}) + c.JSON(common_err.SUCCESS, model.Result{Success: code, Message: common_err.GetMsg(code)}) } // @Summary upload file @@ -437,7 +436,7 @@ func PostFileUpload(c *gin.Context) { defer out.Close() _, err := io.Copy(out, f) if err != nil { - c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } } else { @@ -445,7 +444,7 @@ func PostFileUpload(c *gin.Context) { defer out.Close() _, err := io.Copy(out, f) if err != nil { - c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) @@ -453,7 +452,7 @@ func PostFileUpload(c *gin.Context) { } fileNum, err := ioutil.ReadDir(tempDir) if err != nil { - c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } if totalChunks == len(fileNum) { @@ -461,7 +460,7 @@ func PostFileUpload(c *gin.Context) { file.RMDir(tempDir) } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary copy or move file @@ -475,14 +474,14 @@ func PostFileUpload(c *gin.Context) { func PostOperateFileOrDir(c *gin.Context) { list := model.FileOperate{} - c.BindJSON(&list) + c.ShouldBind(&list) if len(list.Item) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } if list.To == list.Item[0].From[:strings.LastIndex(list.Item[0].From, "/")] { - c.JSON(http.StatusOK, model.Result{Success: common_err.SOURCE_DES_SAME, Message: common_err.GetMsg(common_err.SOURCE_DES_SAME)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SOURCE_DES_SAME, Message: common_err.GetMsg(common_err.SOURCE_DES_SAME)}) return } @@ -512,7 +511,7 @@ func PostOperateFileOrDir(c *gin.Context) { } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary delete file @@ -526,9 +525,9 @@ func PostOperateFileOrDir(c *gin.Context) { func DeleteFile(c *gin.Context) { paths := []string{} - c.BindJSON(&paths) + c.ShouldBind(&paths) if len(paths) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } // path := c.Query("path") @@ -538,12 +537,12 @@ func DeleteFile(c *gin.Context) { for _, v := range paths { err := os.RemoveAll(v) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.FILE_DELETE_ERROR, Message: common_err.GetMsg(common_err.FILE_DELETE_ERROR), Data: err}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FILE_DELETE_ERROR, Message: common_err.GetMsg(common_err.FILE_DELETE_ERROR), Data: err}) return } } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary update file @@ -558,26 +557,26 @@ func DeleteFile(c *gin.Context) { func PutFileContent(c *gin.Context) { fi := model.FileUpdate{} - c.BindJSON(&fi) + c.ShouldBind(&fi) // path := c.PostForm("path") // content := c.PostForm("content") if !file.Exists(fi.FilePath) { - c.JSON(http.StatusOK, model.Result{Success: common_err.FILE_ALREADY_EXISTS, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FILE_ALREADY_EXISTS, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)}) return } //err := os.Remove(path) err := os.RemoveAll(fi.FilePath) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.FILE_DELETE_ERROR, Message: common_err.GetMsg(common_err.FILE_DELETE_ERROR), Data: err}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FILE_DELETE_ERROR, Message: common_err.GetMsg(common_err.FILE_DELETE_ERROR), Data: err}) return } err = file.CreateFileAndWriteContent(fi.FilePath, fi.FileContent) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary image thumbnail/original image @@ -593,13 +592,13 @@ func GetFileImage(c *gin.Context) { t := c.Query("type") path := c.Query("path") if !file.Exists(path) { - c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.FILE_ALREADY_EXISTS, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FILE_ALREADY_EXISTS, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)}) return } if t == "thumbnail" { f, err := file.GetImage(path, 100, 0) if err != nil { - c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } c.Writer.WriteString(string(f)) @@ -607,13 +606,13 @@ func GetFileImage(c *gin.Context) { } f, err := os.Open(path) if err != nil { - c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { - c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()}) return } c.Writer.WriteString(string(data)) @@ -638,5 +637,5 @@ func DeleteOperateFileOrDir(c *gin.Context) { } go service.MyService.Notify().SendFileOperateNotify(true) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } diff --git a/route/v1/shortcuts.go b/route/v1/shortcuts.go deleted file mode 100644 index c866470..0000000 --- a/route/v1/shortcuts.go +++ /dev/null @@ -1,107 +0,0 @@ -/* - * @Author: LinkLeong link@icewhale.com - * @Date: 2021-09-30 18:18:14 - * @LastEditors: LinkLeong - * @LastEditTime: 2022-06-15 14:30:05 - * @FilePath: /CasaOS/route/v1/shortcuts.go - * @Description: - * @Website: https://www.casaos.io - * Copyright (c) 2022 by icewhale, All Rights Reserved. - */ -package v1 - -import ( - "net/http" - "net/url" - - "github.com/IceWhaleTech/CasaOS/model" - "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err" - "github.com/IceWhaleTech/CasaOS/service" - model2 "github.com/IceWhaleTech/CasaOS/service/model" - "github.com/gin-gonic/gin" -) - -// @Summary 获取短链列表 -// @Produce application/json -// @Accept application/json -// @Tags shortcuts -// @Param username formData string true "User name" -// @Param pwd formData string true "password" -// @Security ApiKeyAuth -// @Success 200 {string} string "ok" -// @Router /shortcuts/list [get] -func GetShortcutsList(c *gin.Context) { - list := service.MyService.Shortcuts().GetList() - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list}) -} - -// @Summary 添加shortcuts -// @Produce application/json -// @Accept application/json -// @Tags shortcuts -// @Param title formData string true "title" -// @Param url formData string true "url" -// @Security ApiKeyAuth -// @Success 200 {string} string "ok" -// @Router /shortcuts/add [post] -func PostShortcutsAdd(c *gin.Context) { - var m model2.ShortcutsDBModel - - c.BindJSON(&m) - if len(m.Url) == 0 || len(m.Title) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) - return - } - u, err := url.Parse(m.Url) - if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.SHORTCUTS_URL_ERROR, Message: common_err.GetMsg(common_err.SHORTCUTS_URL_ERROR), Data: err.Error()}) - return - } - m.Icon = "https://api.faviconkit.com/" + u.Host + "/57" - service.MyService.Shortcuts().AddData(m) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) - -} - -// @Summary 删除shortcuts -// @Produce application/json -// @Accept application/json -// @Tags shortcuts -// @Security ApiKeyAuth -// @Success 200 {string} string "ok" -// @Router /shortcuts/del/{id} [post] -func DeleteShortcutsDelete(c *gin.Context) { - id := c.Param("id") - service.MyService.Shortcuts().DeleteData(id) - c.JSON(http.StatusOK, model.Result{ - Success: common_err.SUCCESS, - Message: common_err.GetMsg(common_err.SUCCESS), - Data: "", - }) -} - -// @Summary 编辑shortcuts -// @Produce application/json -// @Accept application/json -// @Tags shortcuts -// @Param title formData string true "title" -// @Param url formData string true "url" -// @Security ApiKeyAuth -// @Success 200 {string} string "ok" -// @Router /shortcuts/edit [put] -func PutShortcutsEdit(c *gin.Context) { - var m model2.ShortcutsDBModel - c.BindJSON(&m) - if len(m.Url) == 0 || len(m.Title) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) - return - } - u, err := url.Parse(m.Url) - if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.SHORTCUTS_URL_ERROR, Message: common_err.GetMsg(common_err.SHORTCUTS_URL_ERROR), Data: err.Error()}) - return - } - m.Icon = "https://api.faviconkit.com/" + u.Host + "/57" - service.MyService.Shortcuts().EditData(m) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: ""}) -} diff --git a/route/v1/sync.go b/route/v1/sync.go deleted file mode 100644 index 14a7f65..0000000 --- a/route/v1/sync.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - * @Author: LinkLeong link@icewhale.com - * @Date: 2021-11-08 18:02:02 - * @LastEditors: LinkLeong - * @LastEditTime: 2022-06-21 19:13:59 - * @FilePath: /CasaOS/route/v1/sync.go - * @Description: - * @Website: https://www.casaos.io - * Copyright (c) 2022 by icewhale, All Rights Reserved. - */ -package v1 - -import ( - "net/http" - - "github.com/IceWhaleTech/CasaOS/model" - "github.com/IceWhaleTech/CasaOS/pkg/config" - "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err" - "github.com/gin-gonic/gin" -) - -func GetSyncConfig(c *gin.Context) { - data := make(map[string]string) - data["key"] = config.SystemConfigInfo.SyncKey - data["port"] = config.SystemConfigInfo.SyncPort - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) -} diff --git a/route/v1/system.go b/route/v1/system.go index 4a352b1..42d7d32 100644 --- a/route/v1/system.go +++ b/route/v1/system.go @@ -1,7 +1,6 @@ package v1 import ( - "encoding/json" "fmt" "net/http" "os" @@ -44,10 +43,10 @@ func GetSystemCheckVersion(c *gin.Context) { service.MyService.Notify().AddLog(installLog) } data := make(map[string]interface{}, 3) - data["is_need"] = need + data["need_update"] = need data["version"] = version data["current_version"] = types.CURRENTVERSION - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } // @Summary 系统信息 @@ -62,7 +61,7 @@ func SystemUpdate(c *gin.Context) { if need { service.MyService.System().UpdateSystemVersion(version.Version) } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary get logs @@ -74,86 +73,29 @@ func SystemUpdate(c *gin.Context) { // @Router /sys/error/logs [get] func GetCasaOSErrorLogs(c *gin.Context) { line, _ := strconv.Atoi(c.DefaultQuery("line", "100")) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: service.MyService.System().GetCasaOSLogs(line)}) -} - -// @Summary 修改配置文件 -// @Produce application/json -// @Accept multipart/form-data -// @Tags sys -// @Param config formData string true "config json string" -// @Security ApiKeyAuth -// @Success 200 {string} string "ok" -// @Router /sys/changhead [post] -func PostSetSystemConfig(c *gin.Context) { - buf := make([]byte, 1024) - n, _ := c.Request.Body.Read(buf) - - service.MyService.System().UpSystemConfig(string(buf[0:n]), "") - c.JSON(http.StatusOK, - model.Result{ - Success: common_err.SUCCESS, - Message: common_err.GetMsg(common_err.SUCCESS), - Data: json.RawMessage(config.SystemConfigInfo.ConfigStr), - }) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: service.MyService.System().GetCasaOSLogs(line)}) } //系统配置 func GetSystemConfigDebug(c *gin.Context) { - array := service.MyService.System().GetSystemConfigDebug() disk := service.MyService.System().GetDiskInfo() sys := service.MyService.System().GetSysInfo() - //todo 准备sync需要显示的数据(镜像,容器) - var systemAppStatus string - images := service.MyService.Docker().IsExistImage("linuxserver/syncthing") - systemAppStatus += "Sync img: " + strconv.FormatBool(images) + "\n\t" - - list := service.MyService.App().GetSystemAppList() - for _, v := range list { - systemAppStatus += v.Image + ",\n\t" - } - - systemAppStatus += "Sync Key length: " + strconv.Itoa(len(config.SystemConfigInfo.SyncKey)) - + version := service.MyService.Casa().GetCasaosVersion() var bugContent string = fmt.Sprintf(` - OS: %s - CasaOS Version: %s - Disk Total: %v - Disk Used: %v - - Sync State: %s - System Info: %s + - Remote Version: %s - Browser: $Browser$ - Version: $Version$ -`, sys.OS, types.CURRENTVERSION, disk.Total>>20, disk.Used>>20, systemAppStatus, array) +`, sys.OS, types.CURRENTVERSION, disk.Total>>20, disk.Used>>20, array, version.Version) // 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: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: bugContent}) -} - -//widget配置 -func GetWidgetConfig(c *gin.Context) { - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json.RawMessage(config.SystemConfigInfo.WidgetList)}) -} - -// @Summary 修改组件配置文件 -// @Produce application/json -// @Accept application/json -// @Tags sys -// @Security ApiKeyAuth -// @Success 200 {string} string "ok" -// @Router /sys/widget/config [post] -func PostSetWidgetConfig(c *gin.Context) { - buf := make([]byte, 1024) - n, _ := c.Request.Body.Read(buf) - service.MyService.System().UpSystemConfig("", string(buf[0:n])) - c.JSON(http.StatusOK, - model.Result{ - Success: common_err.SUCCESS, - Message: common_err.GetMsg(common_err.SUCCESS), - Data: json.RawMessage(config.SystemConfigInfo.WidgetList), - }) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: bugContent}) } // @Summary get casaos server port @@ -164,7 +106,7 @@ func PostSetWidgetConfig(c *gin.Context) { // @Success 200 {string} string "ok" // @Router /sys/port [get] func GetCasaOSPort(c *gin.Context) { - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -182,13 +124,13 @@ func GetCasaOSPort(c *gin.Context) { // @Router /sys/port [put] func PutCasaOSPort(c *gin.Context) { json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) portStr := json["port"] port, err := strconv.Atoi(portStr) if err != nil { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{ - Success: common_err.ERROR, + Success: common_err.SERVICE_ERROR, Message: err.Error(), }) return @@ -196,7 +138,7 @@ func PutCasaOSPort(c *gin.Context) { isAvailable := port2.IsPortAvailable(port, "tcp") if !isAvailable { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{ Success: common_err.PORT_IS_OCCUPIED, Message: common_err.GetMsg(common_err.PORT_IS_OCCUPIED), @@ -204,7 +146,7 @@ func PutCasaOSPort(c *gin.Context) { return } service.MyService.System().UpSystemPort(strconv.Itoa(port)) - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -230,7 +172,9 @@ func PostKillCasaOS(c *gin.Context) { // @Success 200 {string} string "ok" // @Router /sys/usb/off [put] func PutSystemUSBAutoMount(c *gin.Context) { - status := c.Query("state") + js := make(map[string]string) + c.ShouldBind(&js) + status := js["status"] if status == "on" { service.MyService.System().UpdateUSBAutoMount("True") service.MyService.System().ExecUSBAutoMountShell("True") @@ -239,7 +183,7 @@ func PutSystemUSBAutoMount(c *gin.Context) { service.MyService.System().ExecUSBAutoMountShell("False") } - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -259,7 +203,7 @@ func GetSystemUSBAutoMount(c *gin.Context) { state = "False" } - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -267,6 +211,40 @@ func GetSystemUSBAutoMount(c *gin.Context) { }) } +func GetSystemAppsStatus(c *gin.Context) { + systemAppList := service.MyService.App().GetSystemAppList() + appList := []model2.MyAppList{} + for _, v := range systemAppList { + name := strings.ReplaceAll(v.Names[0], "/", "") + if len(v.Labels["name"]) > 0 { + name = v.Labels["name"] + } + appList = append(appList, model2.MyAppList{ + Name: name, + Icon: v.Labels["icon"], + State: v.State, + CustomId: v.Labels["custom_id"], + Id: v.ID, + Port: v.Labels["web"], + Index: v.Labels["index"], + //Order: m.Labels["order"], + Image: v.Image, + Latest: false, + //Type: m.Labels["origin"], + //Slogan: m.Slogan, + //Rely: m.Rely, + Host: v.Labels["host"], + Protocol: v.Labels["protocol"], + }) + } + c.JSON(common_err.SUCCESS, + model.Result{ + Success: common_err.SUCCESS, + Message: common_err.GetMsg(common_err.SUCCESS), + Data: appList, + }) +} + // @Summary get system hardware info // @Produce application/json // @Accept application/json @@ -278,7 +256,7 @@ func GetSystemHardwareInfo(c *gin.Context) { data := make(map[string]string, 1) data["drive_model"] = service.MyService.System().GetDeviceTree() - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -421,7 +399,7 @@ func GetSystemUtilization(c *gin.Context) { data["net"] = newNet - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } // @Summary Get notification port @@ -433,7 +411,7 @@ func GetSystemUtilization(c *gin.Context) { // @Router /sys/socket/port [get] func GetSystemSocketPort(c *gin.Context) { - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), diff --git a/route/v1/user.go b/route/v1/user.go index 597680c..e18851e 100644 --- a/route/v1/user.go +++ b/route/v1/user.go @@ -31,47 +31,47 @@ import ( // @Router /user/register/ [post] func PostUserRegister(c *gin.Context) { json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) username := json["username"] pwd := json["password"] key := json["key"] if _, ok := service.UserRegisterHash[key]; !ok { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.KEY_NOT_EXIST, Message: common_err.GetMsg(common_err.KEY_NOT_EXIST)}) return } if len(username) == 0 || len(pwd) == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } if len(pwd) < 6 { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_IS_TOO_SIMPLE, Message: common_err.GetMsg(common_err.PWD_IS_TOO_SIMPLE)}) return } oldUser := service.MyService.User().GetUserInfoByUserName(username) if oldUser.Id > 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.USER_EXIST, Message: common_err.GetMsg(common_err.USER_EXIST)}) return } user := model2.UserDBModel{} user.Username = username - user.Password = encryption.GetMD5ByStr(config.UserInfo.PWD) + user.Password = encryption.GetMD5ByStr(pwd) user.Role = "admin" user = service.MyService.User().CreateUser(user) if user.Id == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR)}) return } file.MkDir(config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id)) delete(service.UserRegisterHash, key) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } @@ -85,28 +85,28 @@ func PostUserRegister(c *gin.Context) { // @Router /user/login [post] func PostUserLogin(c *gin.Context) { json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) username := json["username"] password := json["password"] //check params is empty if len(username) == 0 || len(password) == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{ - Success: common_err.ERROR, + Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), }) return } user := service.MyService.User().GetUserAllInfoByName(username) if user.Id == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } if user.Password != encryption.GetMD5ByStr(password) { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)}) return } @@ -121,7 +121,7 @@ func PostUserLogin(c *gin.Context) { // TODO:1 Database fields cannot be external data["user"] = user - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -141,14 +141,14 @@ func PutUserAvatar(c *gin.Context) { id := c.GetHeader("user_id") user := service.MyService.User().GetUserInfoById(id) if user.Id == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } f, err := c.FormFile("file") if err != nil { - c.JSON(http.StatusOK, - model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.CLIENT_ERROR, + model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.CLIENT_ERROR), Data: err.Error()}) return } if len(user.Avatar) > 0 { @@ -178,25 +178,22 @@ func PutUserAvatar(c *gin.Context) { func PutUserInfo(c *gin.Context) { id := c.GetHeader("user_id") json := model2.UserDBModel{} - c.BindJSON(&json) + c.ShouldBind(&json) user := service.MyService.User().GetUserInfoById(id) if user.Id == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } if len(json.Username) > 0 { u := service.MyService.User().GetUserInfoByUserName(json.Username) if u.Id > 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.USER_EXIST, Message: common_err.GetMsg(common_err.USER_EXIST)}) return } } - if len(json.Password) > 0 { - user.Password = encryption.GetMD5ByStr(json.Password) - service.MyService.User().UpdateUserPassword(user) - } + if len(json.Email) == 0 { json.Email = user.Email } @@ -213,7 +210,7 @@ func PutUserInfo(c *gin.Context) { json.Nickname = user.Nickname } service.MyService.User().UpdateUser(json) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json}) } // @Summary edit user password @@ -223,31 +220,30 @@ func PutUserInfo(c *gin.Context) { // @Security ApiKeyAuth // @Success 200 {string} string "ok" // @Router /user/password/:id [put] -func PutUserPwd(c *gin.Context) { - //id := c.GetHeader("user_id") +func PutUserPassword(c *gin.Context) { + id := c.GetHeader("user_id") json := make(map[string]string) - c.BindJSON(&json) - oldPwd := json["old_pwd"] - pwd := json["pwd"] - id := json["user_id"] + c.ShouldBind(&json) + oldPwd := json["old_password"] + pwd := json["password"] if len(oldPwd) == 0 || len(pwd) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } user := service.MyService.User().GetUserAllInfoById(id) if user.Id == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } if user.Password != encryption.GetMD5ByStr(oldPwd) { - c.JSON(http.StatusOK, model.Result{Success: common_err.PWD_INVALID_OLD, Message: common_err.GetMsg(common_err.PWD_INVALID_OLD)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.PWD_INVALID_OLD, Message: common_err.GetMsg(common_err.PWD_INVALID_OLD)}) return } user.Password = encryption.GetMD5ByStr(pwd) service.MyService.User().UpdateUserPassword(user) user.Password = "" - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: user}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: user}) } // @Summary edit user nick @@ -262,7 +258,7 @@ func PutUserNick(c *gin.Context) { id := c.GetHeader("user_id") json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) Nickname := json["nick_name"] if len(Nickname) == 0 { c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) @@ -290,7 +286,7 @@ func PutUserNick(c *gin.Context) { func PutUserDesc(c *gin.Context) { id := c.GetHeader("user_id") json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) desc := json["description"] if len(desc) == 0 { c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) @@ -319,7 +315,7 @@ func GetUserInfo(c *gin.Context) { id := c.GetHeader("user_id") user := service.MyService.User().GetUserInfoById(id) - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -338,17 +334,16 @@ func GetUserInfo(c *gin.Context) { func GetUserInfoByUsername(c *gin.Context) { username := c.Param("username") if len(username) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } user := service.MyService.User().GetUserInfoByUserName(username) if user.Id == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } - //** - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -367,7 +362,7 @@ func GetUserAllUsername(c *gin.Context) { for _, v := range users { names = append(names, v.Username) } - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), @@ -384,7 +379,7 @@ func GetUserAllUsername(c *gin.Context) { func GetUserCustomConf(c *gin.Context) { name := c.Param("key") if len(name) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } id := c.GetHeader("user_id") @@ -392,7 +387,7 @@ func GetUserCustomConf(c *gin.Context) { user := service.MyService.User().GetUserInfoById(id) // user := service.MyService.User().GetUserInfoByUsername(Username) if user.Id == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } @@ -400,10 +395,10 @@ func GetUserCustomConf(c *gin.Context) { data := file.ReadFullFile(filePath) if !gjson.ValidBytes(data) { - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: string(data)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: string(data)}) return } - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json2.RawMessage(string(data))}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json2.RawMessage(string(data))}) } /** @@ -413,15 +408,16 @@ func GetUserCustomConf(c *gin.Context) { * @router:/user/custom/:key */ func PostUserCustomConf(c *gin.Context) { + name := c.Param("key") if len(name) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } id := c.GetHeader("user_id") user := service.MyService.User().GetUserInfoById(id) if user.Id == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } @@ -429,7 +425,7 @@ func PostUserCustomConf(c *gin.Context) { filePath := config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id) file.WriteToPath(data, filePath, name+".json") - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json2.RawMessage(string(data))}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json2.RawMessage(string(data))}) } /** @@ -441,19 +437,23 @@ func PostUserCustomConf(c *gin.Context) { func DeleteUserCustomConf(c *gin.Context) { name := c.Param("key") if len(name) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } id := c.GetHeader("user_id") user := service.MyService.User().GetUserInfoById(id) if user.Id == 0 { - c.JSON(http.StatusOK, + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } filePath := config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id) + "/" + name + ".json" - os.Remove(filePath) // @tiger - 这里万一无法实际删除,后面仍然有可能返回成功 - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + err := os.Remove(filePath) + if err != nil { + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR)}) + return + } + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } /** @@ -465,7 +465,7 @@ func DeleteUserCustomConf(c *gin.Context) { func DeleteUser(c *gin.Context) { id := c.Param("id") service.MyService.User().DeleteUserById(id) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: id}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: id}) } /** @@ -476,7 +476,7 @@ func DeleteUser(c *gin.Context) { func PostUserFileImage(c *gin.Context) { id := c.GetHeader("user_id") json := make(map[string]string) - c.BindJSON(&json) + c.ShouldBind(&json) path := json["path"] key := c.Param("key") @@ -533,24 +533,24 @@ func PostUserUploadImage(c *gin.Context) { key := c.Param("key") t := c.PostForm("type") if len(key) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.CLIENT_ERROR), Data: err.Error()}) return } _, err = file.GetImageExtByName(f.Filename) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.NOT_IMAGE, Message: common_err.GetMsg(common_err.NOT_IMAGE)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.NOT_IMAGE, Message: common_err.GetMsg(common_err.NOT_IMAGE)}) return } ext := filepath.Ext(f.Filename) user := service.MyService.User().GetUserInfoById(id) if user.Id == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } if t == "avatar" { @@ -563,7 +563,7 @@ func PostUserUploadImage(c *gin.Context) { data["path"] = path data["file_name"] = key + ext data["online_path"] = "/v1/user/image?path=" + path - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data}) } /** @@ -599,24 +599,24 @@ func DeleteUserImage(c *gin.Context) { id := c.GetHeader("user_id") path := c.Query("path") if len(path) == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)}) return } user := service.MyService.User().GetUserInfoById(id) if user.Id == 0 { - c.JSON(http.StatusOK, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) return } if !file.Exists(path) { - c.JSON(http.StatusOK, model.Result{Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST)}) return } if !strings.Contains(path, config.AppInfo.UserDataPath+"/"+strconv.Itoa(user.Id)) { - c.JSON(http.StatusOK, model.Result{Success: common_err.INSUFFICIENT_PERMISSIONS, Message: common_err.GetMsg(common_err.INSUFFICIENT_PERMISSIONS)}) + c.JSON(common_err.SERVICE_ERROR, model.Result{Success: common_err.INSUFFICIENT_PERMISSIONS, Message: common_err.GetMsg(common_err.INSUFFICIENT_PERMISSIONS)}) return } os.Remove(path) - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } /** @@ -628,34 +628,31 @@ func DeleteUserImage(c *gin.Context) { * @router: */ func PostUserRefreshToken(c *gin.Context) { - - refresh := c.Query("refresh_token") - claims, err := jwt.ParseToken(refresh) + js := make(map[string]string) + c.ShouldBind(&js) + refresh := js["refresh_token"] + claims, err := jwt.ParseToken(refresh, true) if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.VERIFICATION_FAILURE), Data: err.Error()}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.VERIFICATION_FAILURE, Message: common_err.GetMsg(common_err.VERIFICATION_FAILURE), Data: err.Error()}) return } if !claims.VerifyExpiresAt(time.Now(), true) || !claims.VerifyIssuer("refresh", true) { - c.JSON(http.StatusOK, model.Result{Success: common_err.VERIFICATION_FAILURE, Message: common_err.GetMsg(common_err.VERIFICATION_FAILURE)}) + c.JSON(common_err.CLIENT_ERROR, model.Result{Success: common_err.VERIFICATION_FAILURE, Message: common_err.GetMsg(common_err.VERIFICATION_FAILURE)}) return } newToken := jwt.GetAccessToken(claims.Username, claims.PassWord, claims.Id) - if err != nil { - c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()}) - return - } verifyInfo := system_model.VerifyInformation{} verifyInfo.AccessToken = newToken verifyInfo.RefreshToken = jwt.GetRefreshToken(claims.Username, claims.PassWord, claims.Id) verifyInfo.ExpiresAt = time.Now().Add(3 * time.Hour * time.Duration(1)).Unix() - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: verifyInfo}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: verifyInfo}) } func DeleteUserAll(c *gin.Context) { service.MyService.User().DeleteAllUser() - c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) + c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)}) } // @Summary 检查是否进入引导状态 @@ -677,7 +674,7 @@ func GetUserStatus(c *gin.Context) { data["key"] = key data["initialized"] = false } - c.JSON(http.StatusOK, + c.JSON(common_err.SUCCESS, model.Result{ Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), diff --git a/service/app.go b/service/app.go index b45a28a..965c59c 100644 --- a/service/app.go +++ b/service/app.go @@ -156,19 +156,32 @@ func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppLi for _, m := range containers { if m.Labels["casaos"] == "casaos" { + _, newVersion := NewVersionApp[m.ID] + name := strings.ReplaceAll(m.Names[0], "/", "") + icon := m.Labels["icon"] + if len(m.Labels["name"]) > 0 { + name = m.Labels["name"] + } + if m.Labels["origin"] == "system" { + name = strings.Split(m.Image, ":")[0] + if len(strings.Split(name, "/")) > 1 { + icon = "https://icon.casaos.io/main/all/" + strings.Split(name, "/")[1] + ".png" + } + } + list = append(list, model2.MyAppList{ - Name: m.Labels["name"], - Icon: m.Labels["icon"], + Name: name, + Icon: icon, State: m.State, CustomId: m.Labels["custom_id"], Id: m.ID, Port: m.Labels["web"], Index: m.Labels["index"], //Order: m.Labels["order"], - Image: m.Image, - NewVersion: newVersion, - Type: m.Labels["origin"], + Image: m.Image, + Latest: newVersion, + //Type: m.Labels["origin"], //Slogan: m.Slogan, //Rely: m.Rely, Host: m.Labels["host"], @@ -176,16 +189,16 @@ func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppLi }) } else { unTranslation = append(unTranslation, model2.MyAppList{ - Name: strings.ReplaceAll(m.Names[0], "/", ""), - Icon: "", - State: m.State, - CustomId: m.ID, - Id: m.ID, - Port: "", - NewVersion: false, - Host: "", - Protocol: "", - Image: m.Image, + Name: strings.ReplaceAll(m.Names[0], "/", ""), + Icon: "", + State: m.State, + CustomId: m.ID, + Id: m.ID, + Port: "", + Latest: false, + Host: "", + Protocol: "", + Image: m.Image, }) } } @@ -397,20 +410,26 @@ func (a *appStruct) GetHardwareUsageStream() { fts := filters.NewArgs() fts.Add("label", "casaos=casaos") //fts.Add("status", "running") - + containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts}) + if err != nil { + loger.Error("Failed to get container_list", zap.Any("err", err)) + } for i := 0; i < 100; i++ { + if i%10 == 0 { + containers, err = cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts}) + if err != nil { + loger.Error("Failed to get container_list", zap.Any("err", err)) + continue + } + } if config.CasaOSGlobalVariables.AppChange { config.CasaOSGlobalVariables.AppChange = false - dataStats.Range(func(key, value interface{}) bool { dataStats.Delete(key) return true }) } - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts}) - if err != nil { - loger.Error("Failed to get container_list", zap.Any("err", err)) - } + var temp sync.Map var wg sync.WaitGroup for _, v := range containers { @@ -432,7 +451,7 @@ func (a *appStruct) GetHardwareUsageStream() { m, _ := dataStats.Load(v.ID) dockerStats := model.DockerStatsModel{} if m != nil { - dockerStats.Pre = m.(model.DockerStatsModel).Data + dockerStats.Previous = m.(model.DockerStatsModel).Data } dockerStats.Data = data dockerStats.Icon = v.Labels["icon"] diff --git a/service/casa.go b/service/casa.go index 6a59fcd..f628c77 100644 --- a/service/casa.go +++ b/service/casa.go @@ -14,18 +14,19 @@ import ( "github.com/IceWhaleTech/CasaOS/pkg/utils/httper" httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper" "github.com/IceWhaleTech/CasaOS/pkg/utils/loger" + "github.com/pkg/errors" "github.com/tidwall/gjson" "go.uber.org/zap" ) type CasaService interface { - GetServerList(index, size, tp, categoryId, key string) model.ServerAppListCollection - GetServerCategoryList() []model.CategoryList - GetServerAppInfo(id, t string, language string) model.ServerAppList + GetServerList(index, size, tp, categoryId, key string) (model.ServerAppListCollection, error) + GetServerCategoryList() (list []model.CategoryList, err error) + GetServerAppInfo(id, t string, language string) (model.ServerAppList, error) ShareAppFile(body []byte) string GetCasaosVersion() model.Version - AsyncGetServerList() (collection model.ServerAppListCollection) - AsyncGetServerCategoryList() []model.CategoryList + AsyncGetServerList() (collection model.ServerAppListCollection, err error) + AsyncGetServerCategoryList() ([]model.CategoryList, error) } type casaService struct { @@ -40,7 +41,7 @@ func (o *casaService) ShareAppFile(body []byte) string { return content } -func (o *casaService) GetServerList(index, size, tp, categoryId, key string) model.ServerAppListCollection { +func (o *casaService) GetServerList(index, size, tp, categoryId, key string) (model.ServerAppListCollection, error) { keyName := fmt.Sprintf("list_%s_%s_%s_%s_%s", index, size, tp, categoryId, "en") collection := model.ServerAppListCollection{} @@ -48,7 +49,7 @@ func (o *casaService) GetServerList(index, size, tp, categoryId, key string) mod res, ok := result.(string) if ok { json2.Unmarshal([]byte(res), &collection) - return collection + return collection, nil } } @@ -57,7 +58,10 @@ func (o *casaService) GetServerList(index, size, tp, categoryId, key string) mod err := json2.Unmarshal(collectionStr, &collection) if err != nil { loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(collectionStr))) - collection = o.AsyncGetServerList() + collection, err = o.AsyncGetServerList() + if err != nil { + return collection, err + } } go o.AsyncGetServerList() @@ -116,20 +120,20 @@ func (o *casaService) GetServerList(index, size, tp, categoryId, key string) mod Cache.Set(keyName, string(by), time.Minute*10) } - return collection + return collection, nil } -func (o *casaService) AsyncGetServerList() (collection model.ServerAppListCollection) { +func (o *casaService) AsyncGetServerList() (collection model.ServerAppListCollection, err error) { results := file.ReadFullFile(config.AppInfo.DBPath + "/app_list.json") - err := json2.Unmarshal(results, &collection) + err = json2.Unmarshal(results, &collection) if err != nil { loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(results))) } if collection.Version == o.GetCasaosVersion().Version { - return collection + return collection, err } head := make(map[string]string) @@ -181,33 +185,36 @@ func (o *casaService) AsyncGetServerList() (collection model.ServerAppListCollec // return list // } -func (o *casaService) GetServerCategoryList() (list []model.CategoryList) { +func (o *casaService) GetServerCategoryList() (list []model.CategoryList, err error) { category := model.ServerCategoryList{} results := file.ReadFullFile(config.AppInfo.DBPath + "/app_category.json") - err := json2.Unmarshal(results, &category) + err = json2.Unmarshal(results, &category) if err != nil { loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(results))) return o.AsyncGetServerCategoryList() } go o.AsyncGetServerCategoryList() - return category.Item + return category.Item, err } -func (o *casaService) AsyncGetServerCategoryList() []model.CategoryList { +func (o *casaService) AsyncGetServerCategoryList() ([]model.CategoryList, error) { list := model.ServerCategoryList{} results := file.ReadFullFile(config.AppInfo.DBPath + "/app_category.json") err := json2.Unmarshal(results, &list) if err != nil { loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(results))) - } - - if list.Version == o.GetCasaosVersion().Version { - return nil + } else { + if list.Version == o.GetCasaosVersion().Version { + return list.Item, nil + } } item := []model.CategoryList{} head := make(map[string]string) head["Authorization"] = GetToken() listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/category", head) + if len(listS) == 0 { + return item, errors.New("server error") + } json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &item) if len(item) > 0 { list.Version = o.GetCasaosVersion().Version @@ -218,10 +225,10 @@ func (o *casaService) AsyncGetServerCategoryList() []model.CategoryList { } file.WriteToPath(by, config.AppInfo.DBPath, "app_category.json") } - return item + return item, nil } -func (o *casaService) GetServerAppInfo(id, t string, language string) model.ServerAppList { +func (o *casaService) GetServerAppInfo(id, t string, language string) (model.ServerAppList, error) { head := make(map[string]string) @@ -229,9 +236,12 @@ func (o *casaService) GetServerAppInfo(id, t string, language string) model.Serv infoS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/info/"+id+"?t="+t+"&language="+language, head) info := model.ServerAppList{} + if infoS == "" { + return info, errors.New("server error") + } json2.Unmarshal([]byte(gjson.Get(infoS, "data").String()), &info) - return info + return info, nil } func GetToken() string { t := make(chan string) diff --git a/service/docker.go b/service/docker.go index 0cfdb8e..4501345 100644 --- a/service/docker.go +++ b/service/docker.go @@ -540,7 +540,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi config.Labels["show_env"] = strings.Join(showENV, ",") config.Labels["protocol"] = m.Protocol config.Labels["host"] = m.Host - config.Labels["name"] = m.Name + config.Labels["name"] = m.Label hostConfig := &container.HostConfig{Resources: res, Mounts: volumes, RestartPolicy: rp, NetworkMode: container.NetworkMode(m.NetworkModel), Privileged: m.Privileged, CapAdd: m.CapAdd} //if net != "host" { config.ExposedPorts = ports @@ -552,7 +552,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi hostConfig, &network.NetworkingConfig{EndpointsConfig: map[string]*network.EndpointSettings{m.NetworkModel: {NetworkID: "", Aliases: []string{}}}}, nil, - m.Label) + m.ContainerName) if err != nil { return "", err } diff --git a/service/model/o_container.go b/service/model/o_container.go index 4c2f6ac..69c32f7 100644 --- a/service/model/o_container.go +++ b/service/model/o_container.go @@ -2,7 +2,7 @@ * @Author: LinkLeong link@icewhale.com * @Date: 2022-05-13 18:15:46 * @LastEditors: LinkLeong - * @LastEditTime: 2022-05-30 17:33:21 + * @LastEditTime: 2022-07-13 10:56:34 * @FilePath: /CasaOS/service/model/o_container.go * @Description: * @Website: https://www.casaos.io @@ -67,13 +67,12 @@ type MyAppList struct { Index string `json:"index"` //Order string `json:"order"` Port string `json:"port"` - UpTime string `json:"up_time"` // @tiger - 如果是安装时间,应该写 installed_at。 Slogan string `json:"slogan"` Type string `json:"type"` //Rely model.MapStrings `json:"rely"` //[{"mysql":"id"},{"mysql":"id"}] - Image string `json:"image"` - Volumes string `json:"volumes"` - NewVersion bool `json:"new_version"` // @tiger - 无法从词面理解含义,感觉可以更加有描述性 - Host string `json:"host"` - Protocol string `json:"protocol"` + Image string `json:"image"` + Volumes string `json:"volumes"` + Latest bool `json:"latest"` + Host string `json:"host"` + Protocol string `json:"protocol"` } diff --git a/service/model/o_shortcuts.go b/service/model/o_shortcuts.go deleted file mode 100644 index f0fb444..0000000 --- a/service/model/o_shortcuts.go +++ /dev/null @@ -1,17 +0,0 @@ -package model - -import "time" - -type ShortcutsDBModel struct { - Id uint `gorm:"column:id;primary_key" json:"id"` - Title string `json:"title"` - Url string `json:"url"` - Icon string `json:"icon"` - Sort int `json:"sort"` - CreatedAt time.Time `gorm:"<-:create" json:"created_at"` - UpdatedAt time.Time `gorm:"<-:create;<-:update" json:"updated_at"` -} - -func (p *ShortcutsDBModel) TableName() string { - return "o_shortcuts" -} diff --git a/service/notify.go b/service/notify.go index 3cc3022..3981e55 100644 --- a/service/notify.go +++ b/service/notify.go @@ -36,12 +36,28 @@ type NotifyServer interface { SendFileOperateNotify(nowSend bool) SendInstallAppBySocket(app notify.Application) SendAllHardwareStatusBySocket(disk model2.Summary, list []model2.DriveUSB, mem map[string]interface{}, cpu map[string]interface{}, netList []model2.IOCountersStat) + SendStorageBySocket(message notify.StorageMessage) } type notifyServer struct { db *gorm.DB } +func (i *notifyServer) SendStorageBySocket(message notify.StorageMessage) { + body := make(map[string]interface{}) + body["data"] = message + + msg := gosf.Message{} + msg.Body = body + msg.Success = true + msg.Text = "storage_status" + + notify := notify.Message{} + notify.Path = "storage_status" + notify.Msg = msg + + NotifyMsg <- notify +} func (i *notifyServer) SendAllHardwareStatusBySocket(disk model2.Summary, list []model2.DriveUSB, mem map[string]interface{}, cpu map[string]interface{}, netList []model2.IOCountersStat) { body := make(map[string]interface{}) diff --git a/service/service.go b/service/service.go index 6d58b56..2f348fc 100644 --- a/service/service.go +++ b/service/service.go @@ -1,3 +1,13 @@ +/* + * @Author: LinkLeong link@icewhale.com + * @Date: 2022-07-12 09:48:56 + * @LastEditors: LinkLeong + * @LastEditTime: 2022-07-15 10:58:54 + * @FilePath: /CasaOS/service/service.go + * @Description: + * @Website: https://www.casaos.io + * Copyright (c) 2022 by icewhale, All Rights Reserved. + */ package service import ( @@ -23,42 +33,36 @@ type Repository interface { Notify() NotifyServer Rely() RelyService System() SystemService - Shortcuts() ShortcutsService } func NewService(db *gorm.DB) Repository { return &store{ - app: NewAppService(db), - user: NewUserService(db), - docker: NewDockerService(), - casa: NewCasaService(), - disk: NewDiskService(db), - notify: NewNotifyService(db), - rely: NewRelyService(db), - system: NewSystemService(), - shortcuts: NewShortcutsService(db), + app: NewAppService(db), + user: NewUserService(db), + docker: NewDockerService(), + casa: NewCasaService(), + disk: NewDiskService(db), + notify: NewNotifyService(db), + rely: NewRelyService(db), + system: NewSystemService(), } } type store struct { - db *gorm.DB - app AppService - user UserService - docker DockerService - casa CasaService - disk DiskService - notify NotifyServer - rely RelyService - system SystemService - shortcuts ShortcutsService + db *gorm.DB + app AppService + user UserService + docker DockerService + casa CasaService + disk DiskService + notify NotifyServer + rely RelyService + system SystemService } func (c *store) Rely() RelyService { return c.rely } -func (c *store) Shortcuts() ShortcutsService { - return c.shortcuts -} func (c *store) System() SystemService { return c.system diff --git a/service/shortcuts.go b/service/shortcuts.go deleted file mode 100644 index f57404a..0000000 --- a/service/shortcuts.go +++ /dev/null @@ -1,34 +0,0 @@ -package service - -import ( - model2 "github.com/IceWhaleTech/CasaOS/service/model" - "gorm.io/gorm" -) - -type ShortcutsService interface { - DeleteData(id string) - AddData(m model2.ShortcutsDBModel) - EditData(m model2.ShortcutsDBModel) - GetList() (list []model2.ShortcutsDBModel) -} -type shortcutsService struct { - db *gorm.DB -} - -func (s *shortcutsService) AddData(m model2.ShortcutsDBModel) { - s.db.Create(&m) -} -func (s *shortcutsService) EditData(m model2.ShortcutsDBModel) { - s.db.Save(&m) -} -func (s *shortcutsService) DeleteData(id string) { - var m model2.ShortcutsDBModel - s.db.Where("id=?", id).Delete(&m) -} -func (s *shortcutsService) GetList() (list []model2.ShortcutsDBModel) { - s.db.Order("sort desc,id").Find(&list) - return list -} -func NewShortcutsService(db *gorm.DB) ShortcutsService { - return &shortcutsService{db: db} -} diff --git a/service/system.go b/service/system.go index 7d693e3..ba9ff44 100644 --- a/service/system.go +++ b/service/system.go @@ -24,7 +24,6 @@ import ( ) type SystemService interface { - UpSystemConfig(str string, widget string) UpdateSystemVersion(version string) GetSystemConfigDebug() []string GetCasaOSLogs(lineNumber int) string @@ -54,6 +53,12 @@ type SystemService interface { type systemService struct { } +func (s *systemService) UpdateUSBAutoMount(state string) { + config.ServerInfo.USBAutoMount = state + config.Cfg.Section("server").Key("USBAutoMount").SetValue(state) + config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) +} + func (c *systemService) MkdirAll(path string) (int, error) { _, err := os.Stat(path) if err == nil { @@ -66,7 +71,7 @@ func (c *systemService) MkdirAll(path string) (int, error) { return common_err.FILE_OR_DIR_EXISTS, err } } - return common_err.ERROR, err + return common_err.SERVICE_ERROR, err } func (c *systemService) RenameFile(oldF, newF string) (int, error) { @@ -77,12 +82,12 @@ func (c *systemService) RenameFile(oldF, newF string) (int, error) { if os.IsNotExist(err) { err := os.Rename(oldF, newF) if err != nil { - return common_err.ERROR, err + return common_err.SERVICE_ERROR, err } return common_err.SUCCESS, nil } } - return common_err.ERROR, err + return common_err.SERVICE_ERROR, err } func (c *systemService) CreateFile(path string) (int, error) { _, err := os.Stat(path) @@ -94,7 +99,7 @@ func (c *systemService) CreateFile(path string) (int, error) { return common_err.SUCCESS, nil } } - return common_err.ERROR, err + return common_err.SERVICE_ERROR, err } func (c *systemService) GetDeviceTree() string { return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDeviceTree") @@ -232,28 +237,13 @@ func (s *systemService) ExecUSBAutoMountShell(state string) { func (s *systemService) GetSystemConfigDebug() []string { return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetSysInfo") } -func (s *systemService) UpSystemConfig(str string, widget string) { - if len(str) > 0 && str != config.SystemConfigInfo.ConfigStr { - config.Cfg.Section("system").Key("ConfigStr").SetValue(str) - config.SystemConfigInfo.ConfigStr = str - } - if len(widget) > 0 && widget != config.SystemConfigInfo.WidgetList { - config.Cfg.Section("system").Key("WidgetList").SetValue(widget) - config.SystemConfigInfo.WidgetList = widget - } - config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) -} + func (s *systemService) UpAppOrderFile(str, id string) { file.WriteToPath([]byte(str), config.AppInfo.DBPath+"/"+id, "app_order.json") } func (s *systemService) GetAppOrderFile(id string) []byte { return file.ReadFullFile(config.AppInfo.UserDataPath + "/" + id + "/app_order.json") } -func (s *systemService) UpdateUSBAutoMount(state string) { - config.ServerInfo.USBAutoMount = state - config.Cfg.Section("server").Key("USBAutoMount").SetValue(state) - config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) -} func (s *systemService) UpSystemPort(port string) { if len(port) > 0 && port != config.ServerInfo.HttpPort { config.Cfg.Section("server").Key("HttpPort").SetValue(port) diff --git a/web/browserconfig.xml b/web/browserconfig.xml index a221792..a02d62e 100644 --- a/web/browserconfig.xml +++ b/web/browserconfig.xml @@ -1,9 +1,9 @@ - - - - - - #da532c - - - + + + + + + #da532c + + + diff --git a/web/favicon.svg b/web/favicon.svg index 9760ab7..8d176f0 100644 --- a/web/favicon.svg +++ b/web/favicon.svg @@ -1,14 +1,14 @@ - - - - - - - - + + + + + + + + diff --git a/web/img/1-small.1b74d2ba.png b/web/img/1-small.1b74d2ba.png deleted file mode 100644 index 406d0ba..0000000 Binary files a/web/img/1-small.1b74d2ba.png and /dev/null differ diff --git a/web/img/Android-DeviceID.b57fefc8.png b/web/img/Android-DeviceID.b57fefc8.png deleted file mode 100644 index 323d311..0000000 Binary files a/web/img/Android-DeviceID.b57fefc8.png and /dev/null differ diff --git a/web/img/Android-Menu.ed4df0da.png b/web/img/Android-Menu.ed4df0da.png deleted file mode 100644 index d41bef4..0000000 Binary files a/web/img/Android-Menu.ed4df0da.png and /dev/null differ diff --git a/web/img/Android-NewDevice.f00af2cb.png b/web/img/Android-NewDevice.f00af2cb.png deleted file mode 100644 index 5e36a2b..0000000 Binary files a/web/img/Android-NewDevice.f00af2cb.png and /dev/null differ diff --git a/web/img/Android-NewDeviceAdd.784d2f18.png b/web/img/Android-NewDeviceAdd.784d2f18.png deleted file mode 100644 index bd7ebfd..0000000 Binary files a/web/img/Android-NewDeviceAdd.784d2f18.png and /dev/null differ diff --git a/web/img/Android-NewFolder.d71dc444.png b/web/img/Android-NewFolder.d71dc444.png deleted file mode 100644 index c7a362f..0000000 Binary files a/web/img/Android-NewFolder.d71dc444.png and /dev/null differ diff --git a/web/img/Android-NewFolderCreate.b3521b45.png b/web/img/Android-NewFolderCreate.b3521b45.png deleted file mode 100644 index 35d04a8..0000000 Binary files a/web/img/Android-NewFolderCreate.b3521b45.png and /dev/null differ diff --git a/web/img/Android-ShowDeviceID.f7e46fb8.png b/web/img/Android-ShowDeviceID.f7e46fb8.png deleted file mode 100644 index de34139..0000000 Binary files a/web/img/Android-ShowDeviceID.f7e46fb8.png and /dev/null differ diff --git a/web/img/Windows-DeviceID.2e929f75.png b/web/img/Windows-DeviceID.2e929f75.png deleted file mode 100644 index 6222a12..0000000 Binary files a/web/img/Windows-DeviceID.2e929f75.png and /dev/null differ diff --git a/web/img/Windows-NewDevice.c9f2471d.png b/web/img/Windows-NewDevice.c9f2471d.png deleted file mode 100644 index 55367a9..0000000 Binary files a/web/img/Windows-NewDevice.c9f2471d.png and /dev/null differ diff --git a/web/img/Windows-NewDeviceSave.fe1078b1.png b/web/img/Windows-NewDeviceSave.fe1078b1.png deleted file mode 100644 index d75260e..0000000 Binary files a/web/img/Windows-NewDeviceSave.fe1078b1.png and /dev/null differ diff --git a/web/img/Windows-NewFolder.5305cc41.png b/web/img/Windows-NewFolder.5305cc41.png deleted file mode 100644 index 34503b0..0000000 Binary files a/web/img/Windows-NewFolder.5305cc41.png and /dev/null differ diff --git a/web/img/Windows-NewFolderSave.9ce2312f.png b/web/img/Windows-NewFolderSave.9ce2312f.png deleted file mode 100644 index 8ee1a2c..0000000 Binary files a/web/img/Windows-NewFolderSave.9ce2312f.png and /dev/null differ diff --git a/web/img/Windows-ShowID.1000f319.png b/web/img/Windows-ShowID.1000f319.png deleted file mode 100644 index d67fccc..0000000 Binary files a/web/img/Windows-ShowID.1000f319.png and /dev/null differ diff --git a/web/img/icon/safari-pinned-tab.svg b/web/img/icon/safari-pinned-tab.svg index af12e15..e750780 100644 --- a/web/img/icon/safari-pinned-tab.svg +++ b/web/img/icon/safari-pinned-tab.svg @@ -1,25 +1,25 @@ - - - - -Created by potrace 1.14, written by Peter Selinger 2001-2017 - - - - - + + + + +Created by potrace 1.14, written by Peter Selinger 2001-2017 + + + + + diff --git a/web/img/macOS-Config.f419628a.png b/web/img/macOS-Config.f419628a.png deleted file mode 100644 index 35f4991..0000000 Binary files a/web/img/macOS-Config.f419628a.png and /dev/null differ diff --git a/web/img/macOS-DeviceID.968cc84d.png b/web/img/macOS-DeviceID.968cc84d.png deleted file mode 100644 index 1b75247..0000000 Binary files a/web/img/macOS-DeviceID.968cc84d.png and /dev/null differ diff --git a/web/img/macOS-NewFolder.fa9e37d0.png b/web/img/macOS-NewFolder.fa9e37d0.png deleted file mode 100644 index 368236a..0000000 Binary files a/web/img/macOS-NewFolder.fa9e37d0.png and /dev/null differ diff --git a/web/img/macOS-NewFolderSave.6f3f247d.png b/web/img/macOS-NewFolderSave.6f3f247d.png deleted file mode 100644 index 1430d86..0000000 Binary files a/web/img/macOS-NewFolderSave.6f3f247d.png and /dev/null differ diff --git a/web/img/macOS-ShowID.c822acc3.png b/web/img/macOS-ShowID.c822acc3.png deleted file mode 100644 index 610aa10..0000000 Binary files a/web/img/macOS-ShowID.c822acc3.png and /dev/null differ diff --git a/web/img/macOS-icon.ae9e0906.png b/web/img/macOS-icon.ae9e0906.png deleted file mode 100644 index 499d6ea..0000000 Binary files a/web/img/macOS-icon.ae9e0906.png and /dev/null differ diff --git a/web/img/syncthing.257e4f51.svg b/web/img/syncthing.257e4f51.svg deleted file mode 100644 index e18d9ed..0000000 --- a/web/img/syncthing.257e4f51.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/web/img/windows.d98029c3.svg b/web/img/windows.d98029c3.svg deleted file mode 100644 index 6fac0df..0000000 --- a/web/img/windows.d98029c3.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/web/index.html b/web/index.html index 2ebe764..905d50c 100644 --- a/web/index.html +++ b/web/index.html @@ -20,7 +20,7 @@ CasaOS - +