Adjusting shell script location

This commit is contained in:
a624669980@163.com 2022-09-02 17:44:58 +08:00
parent 1c9ad4c63e
commit e57010f803
32 changed files with 398 additions and 1866 deletions

3
.gitignore vendored
View File

@ -28,8 +28,6 @@ gen
/sql/
/out/
/db/
/docs/
/web/
/conf/conf.ini
/conf/conf.conf
/conf/conf.json
@ -38,5 +36,4 @@ main
CasaOS
github.com
.all-contributorsrc
build
dist

View File

@ -65,6 +65,59 @@ builds:
hooks:
post:
- find build/sysroot -type f | xargs -L 1 realpath --relative-to=build/sysroot > build/sysroot.manifest
- id: casaos-migration-tool-amd64
binary: build/sysroot/usr/bin/casaos-migration-tool
main: ./cmd/migration-tool
env:
- CGO_ENABLED=1
- CC=x86_64-linux-gnu-gcc
ldflags:
- -s
- -w
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- amd64
- id: casaos-migration-tool-arm64
binary: build/sysroot/usr/bin/casaos-migration-tool
main: ./cmd/migration-tool
env:
- CGO_ENABLED=1
- CC=aarch64-linux-gnu-gcc
ldflags:
- -s
- -w
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- arm64
- id: casaos-migration-tool-arm-7
binary: build/sysroot/usr/bin/casaos-migration-tool
main: ./cmd/migration-tool
env:
- CGO_ENABLED=1
- CC=arm-linux-gnueabihf-gcc
ldflags:
- -s
- -w
- -extldflags "-static"
tags:
- musl
- netgo
goos:
- linux
goarch:
- arm
goarm:
- "7"
archives:
- name_template: "{{ .Os }}-{{ .Arch }}-{{ .ProjectName }}-v{{ .Version }}"
id: casaos
@ -76,20 +129,38 @@ archives:
arm: arm-7
files:
- build/**/*
- name_template: "{{ .Os }}-{{ .Arch }}-{{ .ProjectName }}-migration-tool-v{{ .Version }}"
id: casaos-migration-tool
builds:
- casaos-migration-tool-amd64
- casaos-migration-tool-arm64
- casaos-migration-tool-arm-7
replacements:
arm: arm-7
files:
- build/sysroot/etc/**/*
checksum:
name_template: "checksums.txt"
snapshot:
name_template: "{{ incpatch .Version }}-snapshot"
name_template: "{{ incpatch .Version }}"
changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
# release:
# github:
# owner: IceWhaleTech
# name: CasaOS
# draft: true
# prerelease: auto
# mode: replace
# name_template: "v{{ .Version }}"
release:
github:
owner: IceWhaleTech
name: CasaOS
owner: LinkLeong
name: casaos-alpha
draft: true
prerelease: auto
mode: replace

View File

@ -18,7 +18,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
## [0.3.5-alpha] - 2022-08-08
## [0.3.6-alpha.1] - 2022-08-30
## [0.3.5] - 2022-08-23
### Added

View File

@ -23,13 +23,23 @@ __error() {
__is_version_gt() {
test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"
}
__normalize_version() {
local version
if [ "${1::1}" = "v" ]; then
version="${1:1}"
else
version="${1}"
fi
echo "$version"
}
__is_migration_needed() {
local version1
local version2
version1="${1}"
version2="${2}"
version1=$(__normalize_version "${1}")
version2=$(__normalize_version "${2}")
if [ "${version1}" = "${version2}" ]; then
return 1
@ -50,7 +60,8 @@ BUILD_PATH=$(dirname "${BASH_SOURCE[0]}")/../../..
SOURCE_ROOT=${BUILD_PATH}/sysroot
APP_NAME="casaos"
APP_NAME_FORMAL="CasaOS"
# APP_NAME_FORMAL="CasaOS"
APP_NAME_FORMAL="casaos-alpha"
# check if migration is needed
SOURCE_BIN_PATH=${SOURCE_ROOT}/usr/bin
@ -74,7 +85,11 @@ if [ "${NEED_MIGRATION}" = "false" ]; then
exit 0
fi
MIGRATION_SERVICE_DIR=${BUILD_PATH}/scripts/migration/service.d/${APP_NAME}
MIGRATION_SERVICE_DIR=${1}
if [ -z "${MIGRATION_SERVICE_DIR}" ]; then
MIGRATION_SERVICE_DIR=${BUILD_PATH}/scripts/migration/service.d/${APP_NAME}
fi
MIGRATION_LIST_FILE=${MIGRATION_SERVICE_DIR}/migration.list
MIGRATION_PATH=()
@ -95,7 +110,7 @@ while read -r VERSION_PAIR; do
# obtain "v0.3.6-alpha2" from "v0.3.5 v0.3.6-alpha2"
VER2=$(echo "${VERSION_PAIR}" | cut -d' ' -f2)
if [ "v${CURRENT_VERSION}" = "${VER1// /}" ] || [ "${CURRENT_VERSION}" = "LEGACY_WITHOUT_VERSION" ]; then
if [ "${CURRENT_VERSION}" = "${VER1// /}" ] || [ "${CURRENT_VERSION}" = "LEGACY_WITHOUT_VERSION" ]; then
CURRENT_VERSION_FOUND="true"
fi
@ -128,9 +143,17 @@ esac
pushd "${MIGRATION_SERVICE_DIR}"
{
for VER2 in "${MIGRATION_PATH[@]}"; do
MIGRATION_TOOL_URL=https://github.com/IceWhaleTech/"${APP_NAME_FORMAL}"/releases/download/"${VER2}"/linux-"${ARCH}"-"${APP_NAME}"-migration-tool-"${VER2}".tar.gz
{ for VER2 in "${MIGRATION_PATH[@]}"; do
MIGRATION_TOOL_FILE=linux-"${ARCH}"-"${APP_NAME}"-migration-tool-"${VER2}".tar.gz
if [ -f "${MIGRATION_TOOL_FILE}" ]; then
__info "Migration tool ${MIGRATION_TOOL_FILE} exists. Skip downloading."
continue
fi
MIGRATION_TOOL_URL=https://github.com/LinkLeong/"${APP_NAME_FORMAL}"/releases/download/"${VER2}"/linux-"${ARCH}"-"${APP_NAME}"-migration-tool-"${VER2}".tar.gz
echo "Dowloading ${MIGRATION_TOOL_URL}..."
curl -sL -O "${MIGRATION_TOOL_URL}"
done
@ -145,9 +168,6 @@ pushd "${MIGRATION_SERVICE_DIR}"
__info "Extracting ${MIGRATION_TOOL_FILE}..."
tar zxvf "${MIGRATION_TOOL_FILE}"
MIGRATION_SYSROOT_DIR=$(realpath -e "${MIGRATION_SERVICE_DIR}"/build/sysroot || __error "Failed to find sysroot directory for migration")
cp -rv "${MIGRATION_SYSROOT_DIR}"/* / || __error "Failed to copy sysroot directory for migration"
MIGRATION_TOOL_PATH=build/sysroot/usr/bin/${APP_NAME}-migration-tool
__info "Running ${MIGRATION_TOOL_PATH}..."
${MIGRATION_TOOL_PATH}

View File

@ -1,2 +1,3 @@
LEGACY_WITHOUT_VERSION v0.3.6-alpha2
v0.3.5 v0.3.6-alpha2
LEGACY_WITHOUT_VERSION v0.3.6
v0.3.5 v0.3.6
v0.3.5.1 v0.3.6

View File

@ -1,4 +1,15 @@
#!/bin/bash
###
# @Author: LinkLeong link@icewhale.org
# @Date: 2022-08-25 11:41:22
# @LastEditors: LinkLeong
# @LastEditTime: 2022-08-31 17:54:17
# @FilePath: /CasaOS/build/scripts/setup/service.d/casaos/debian/setup-casaos.sh
# @Description:
# @Website: https://www.casaos.io
# Copyright (c) 2022 by icewhale, All Rights Reserved.
###
set -e
@ -6,19 +17,29 @@ APP_NAME="casaos"
# copy config files
CONF_PATH=/etc/casaos
OLD_CONF_PATH=/etc/casaos.conf
CONF_FILE=${CONF_PATH}/${APP_NAME}.conf
CONF_FILE_SAMPLE=${CONF_PATH}/${APP_NAME}.conf.sample
if [ ! -f "${CONF_FILE}" ]; then \
if [ -f "${OLD_CONF_PATH}" ]; then
echo "copy old conf"
cp "${OLD_CONF_PATH}" "${CONF_FILE}"
fi
if [ ! -f "${CONF_FILE}" ]; then
echo "Initializing config file..."
cp -v "${CONF_FILE_SAMPLE}" "${CONF_FILE}"; \
cp -v "${CONF_FILE_SAMPLE}" "${CONF_FILE}"
fi
# enable and start service
systemctl daemon-reload
if systemctl is-active "${APP_NAME}.service" &>/dev/null ;then
echo "server started"
else
# enable and start service
systemctl daemon-reload
echo "Enabling service..."
systemctl enable --force --no-ask-password "${APP_NAME}.service"
echo "Enabling service..."
systemctl enable --force --no-ask-password "${APP_NAME}.service"
echo "Starting service..."
systemctl start --force --no-ask-password "${APP_NAME}.service"
echo "Starting service..."
systemctl start --force --no-ask-password "${APP_NAME}.service"
fi

47
cmd/migration-tool/log.go Normal file
View File

@ -0,0 +1,47 @@
/*
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-30 22:15:30
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-30 22:15:47
* @FilePath: /CasaOS/cmd/migration-tool/log.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package main
import (
"log"
"os"
)
type Logger struct {
DebugMode bool
_debug *log.Logger
_info *log.Logger
_error *log.Logger
}
func NewLogger() *Logger {
return &Logger{
DebugMode: false,
_debug: log.New(os.Stdout, "DEBUG: ", 0),
_info: log.New(os.Stdout, "", 0),
_error: log.New(os.Stderr, "ERROR: ", 0),
}
}
func (l *Logger) Debug(format string, v ...interface{}) {
if l.DebugMode {
l._debug.Printf(format, v...)
}
}
func (l *Logger) Info(format string, v ...interface{}) {
l._info.Printf(format, v...)
}
func (l *Logger) Error(format string, v ...interface{}) {
l._error.Printf(format, v...)
}

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-23 18:09:11
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-24 18:02:59
* @LastEditTime: 2022-08-31 14:17:51
* @FilePath: /CasaOS/cmd/migration-tool/main.go
* @Description:
* @Website: https://www.casaos.io
@ -18,18 +18,41 @@ import (
interfaces "github.com/IceWhaleTech/CasaOS-Common"
"github.com/IceWhaleTech/CasaOS-Common/utils/systemctl"
"github.com/IceWhaleTech/CasaOS-Gateway/common"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/sqlite"
"github.com/IceWhaleTech/CasaOS/service"
"gorm.io/gorm"
)
const (
casaosServiceName = "casaos.service"
)
var _logger *Logger
var sqliteDB *gorm.DB
var configFlag = ""
var dbFlag = ""
func init() {
config.InitSetup(configFlag)
config.UpdateSetup()
if len(dbFlag) == 0 {
dbFlag = config.AppInfo.DBPath + "/db"
}
sqliteDB = sqlite.GetDb(dbFlag)
//gredis.GetRedisConn(config.RedisInfo),
service.MyService = service.NewService(sqliteDB, "")
}
func main() {
versionFlag := flag.Bool("v", false, "version")
debugFlag := flag.Bool("d", true, "debug")
forceFlag := flag.Bool("f", false, "force")
forceFlag := flag.Bool("f", true, "force")
flag.Parse()
_logger = NewLogger()
if *versionFlag {
fmt.Println(common.Version)
os.Exit(0)
@ -40,7 +63,7 @@ func main() {
}
if *debugFlag {
// _logger.DebugMode = true
_logger.DebugMode = true
}
if !*forceFlag {
@ -50,7 +73,7 @@ func main() {
}
if serviceEnabled {
//_logger.Info("%s is already enabled. If migration is still needed, try with -f.", userServiceName)
_logger.Info("%s is already enabled. If migration is still needed, try with -f.", casaosServiceName)
os.Exit(1)
}
}
@ -75,6 +98,7 @@ func main() {
}
if selectedMigrationTool == nil {
_logger.Error("selectedMigrationTool is null")
return
}
@ -86,7 +110,8 @@ func main() {
panic(err)
}
if err := selectedMigrationTool.PostMigrate(); err != nil {
panic(err)
}
selectedMigrationTool.PostMigrate()
_logger.Info("casaos migration ok")
//panic(err)
}

View File

@ -0,0 +1,89 @@
/*
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-24 17:36:00
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-31 17:20:26
* @FilePath: /CasaOS/cmd/migration-tool/migration-034-035.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package main
import (
"strings"
interfaces "github.com/IceWhaleTech/CasaOS-Common"
"github.com/IceWhaleTech/CasaOS-Common/utils/version"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/service"
)
type migrationTool struct{}
func (u *migrationTool) IsMigrationNeeded() (bool, error) {
majorVersion, minorVersion, patchVersion, err := version.DetectLegacyVersion()
if err != nil {
if err == version.ErrLegacyVersionNotFound {
return false, nil
}
return false, err
}
if majorVersion > 0 {
return false, nil
}
if minorVersion > 3 {
return false, nil
}
if minorVersion == 3 && patchVersion > 5 {
return false, nil
}
_logger.Info("Migration is needed for a CasaOS version 0.3.5 and older...")
return true, nil
}
func (u *migrationTool) PreMigrate() error {
return nil
}
func (u *migrationTool) Migrate() error {
if service.MyService.System().GetSysInfo().KernelArch == "aarch64" && config.ServerInfo.USBAutoMount != "True" && strings.Contains(service.MyService.System().GetDeviceTree(), "Raspberry Pi") {
service.MyService.System().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False")
}
newAPIUrl := "https://api.casaos.io/casaos-api"
if config.ServerInfo.ServerApi == "https://api.casaos.zimaboard.com" {
config.ServerInfo.ServerApi = newAPIUrl
config.Cfg.Section("server").Key("ServerApi").SetValue(newAPIUrl)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
command.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/assist.sh | bash")
if !file.CheckNotExist("/casaOS") {
command.OnlyExec("source /casaOS/server/shell/update.sh ;")
command.OnlyExec("source " + config.AppInfo.ShellPath + "/delete-old-service.sh ;")
}
service.MyService.App().ImportApplications(true)
_logger.Info("update done")
return nil
}
func (u *migrationTool) PostMigrate() error {
return nil
}
func NewMigrationToolFor_035() interfaces.MigrationTool {
return &migrationTool{}
}

View File

@ -1,52 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-24 17:36:00
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-24 18:11:16
* @FilePath: /CasaOS/cmd/migration-tool/migration-035.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package main
import (
interfaces "github.com/IceWhaleTech/CasaOS-Common"
"github.com/IceWhaleTech/CasaOS-Common/utils/version"
)
type migrationTool struct{}
func (u *migrationTool) IsMigrationNeeded() (bool, error) {
minorVersion, err := version.DetectMinorVersion()
if err != nil {
return false, err
}
if minorVersion != 3 {
return false, nil
}
// this is the best way to tell if CasaOS version is between 0.3.3 and 0.3.5
//return true, nil
return false, nil
}
func (u *migrationTool) PreMigrate() error {
return nil
}
func (u *migrationTool) Migrate() error {
return nil
}
func (u *migrationTool) PostMigrate() error {
return nil
}
func NewMigrationToolFor_035() interfaces.MigrationTool {
return &migrationTool{}
}

View File

@ -21,3 +21,6 @@ Token =
USBAutoMount =
[system]
[common]
RuntimePath=/var/run/casaos

5
go.mod
View File

@ -4,8 +4,8 @@ go 1.16
require (
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220811222508-6c2a1d77be66
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha1
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220830042034-a4df79c84ce6
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha4
github.com/Microsoft/go-winio v0.5.0 // indirect
github.com/ambelovsky/go-structs v1.1.0 // indirect
github.com/ambelovsky/gosf v0.0.0-20201109201340-237aea4d6109
@ -29,7 +29,6 @@ require (
github.com/gorilla/websocket v1.4.2
github.com/hirochachacha/go-smb2 v1.1.0
github.com/jinzhu/copier v0.3.2
github.com/klauspost/compress v1.13.6 // indirect
github.com/lucas-clemente/quic-go v0.25.0
github.com/mholt/archiver/v3 v3.5.1
github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect

8
go.sum
View File

@ -83,10 +83,10 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d h1:62lEBImTxZ83pgzywgDNIrPPuQ+j4ep9QjqrWBn1hrU=
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d/go.mod h1:lW9x+yEjqKdPbE3+cf2fGPJXCw/hChX3Omi9QHTLFsQ=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220811222508-6c2a1d77be66 h1:JXzgOmP4HCWbZ7qCl6gr2nRB5RnUN0oTFF8ohv05sZk=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220811222508-6c2a1d77be66/go.mod h1:XGqdbedN9UlF3/rylcXKJ2BW4ayugBmEMa4Z0tk2KbQ=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha1 h1:VTjFhgaDy+yDZZOkGACLoynp2fxCL1PJuwYM+tLL68o=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha1/go.mod h1:wWBJTVHt0P0AGNfoOgI2+HhZ5bGZU4d5xbz/dXNBzAY=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220830042034-a4df79c84ce6 h1:ICitt/XvD1oh3BTdQbzV95G48TFY/aiZr55iA8dMD8M=
github.com/IceWhaleTech/CasaOS-Common v0.0.0-20220830042034-a4df79c84ce6/go.mod h1:5sqNKg5cEH7IUnCklLSTrVoGx1dMBhm9DFDsCYVPvPQ=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha4 h1:fSlA5kNBS/Q4D6bFWiNZTwUfsYQ5F/78vJLvUoowXao=
github.com/IceWhaleTech/CasaOS-Gateway v0.3.6-alpha4/go.mod h1:8E5T8HJn2OUXz+KBZRD84CzwhBdCWsIBuQChZJ7XDwE=
github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw=

33
main.go
View File

@ -11,9 +11,7 @@ import (
"github.com/IceWhaleTech/CasaOS/pkg/cache"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/sqlite"
"github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/pkg/utils/random"
"github.com/IceWhaleTech/CasaOS/route"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/IceWhaleTech/CasaOS/types"
@ -28,8 +26,6 @@ var sqliteDB *gorm.DB
var configFlag = flag.String("c", "", "config address")
var dbFlag = flag.String("db", "", "db path")
var resetUser = flag.Bool("ru", false, "reset user")
var user = flag.String("user", "", "user name")
var versionFlag = flag.Bool("v", false, "version")
func init() {
@ -79,24 +75,6 @@ func main() {
if *versionFlag {
return
}
if *resetUser {
if user == nil || len(*user) == 0 {
fmt.Println("user is empty")
return
}
userData := service.MyService.User().GetUserAllInfoByName(*user)
if userData.Id == 0 {
fmt.Println("user not exist")
return
}
password := random.RandomString(6, false)
userData.Password = encryption.GetMD5ByStr(password)
service.MyService.User().UpdateUserPassword(userData)
fmt.Println("User reset successful")
fmt.Println("UserName:" + userData.Username)
fmt.Println("Password:" + password)
return
}
go route.SocketInit(service.NotifyMsg)
go route.MonitoryUSB()
//model.Setup()
@ -140,6 +118,17 @@ func main() {
panic(err)
}
}
//v0.3.6
if config.ServerInfo.HttpPort != "" {
changePort := common.ChangePortRequest{}
changePort.Port = config.ServerInfo.HttpPort
err := service.MyService.Gateway().ChangePort(&changePort)
if err == nil {
config.Cfg.Section("server").Key("HttpPort").SetValue("")
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
}
// s := &http.Server{
// Addr: listener.Addr().String(), //fmt.Sprintf(":%v", config.ServerInfo.HttpPort),
// Handler: r,

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2021-09-30 18:18:14
* @LastEditors: LinkLeong
* @LastEditTime: 2022-06-21 11:09:30
* @LastEditTime: 2022-08-31 17:04:02
* @FilePath: /CasaOS/pkg/config/config.go
* @Description:
* @Website: https://www.casaos.io
@ -11,5 +11,5 @@
package config
const (
USERCONFIGURL = "/etc/casaos.conf"
USERCONFIGURL = "/etc/casaos/casaos.conf"
)

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-13 18:15:46
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-22 10:18:41
* @LastEditTime: 2022-09-01 22:05:32
* @FilePath: /CasaOS/pkg/config/init.go
* @Description:
* @Website: https://www.casaos.io
@ -32,9 +32,7 @@ var UserInfo = &model.UserModel{}
//用户相关
var AppInfo = &model.APPModel{}
var CommonInfo = &model.CommonModel{
RuntimePath: "/var/run/casaos",
}
var CommonInfo = &model.CommonModel{}
//var RedisInfo = &model.RedisModel{}
@ -63,8 +61,11 @@ func InitSetup(config string) {
//读取文件
Cfg, err = ini.Load(configDir)
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
Cfg, err = ini.Load("/etc/casaos.conf")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
}
mapTo("user", UserInfo)
@ -77,24 +78,23 @@ func InitSetup(config string) {
SystemConfigInfo.ConfigPath = configDir
if len(AppInfo.DBPath) == 0 {
AppInfo.DBPath = "/var/lib/casaos"
Cfg.SaveTo(configDir)
}
if len(AppInfo.LogPath) == 0 {
AppInfo.LogPath = "/var/log/casaos/"
Cfg.SaveTo(configDir)
}
if len(AppInfo.ShellPath) == 0 {
AppInfo.ShellPath = "/usr/share/casaos/shell"
Cfg.SaveTo(configDir)
}
if len(AppInfo.UserDataPath) == 0 {
AppInfo.UserDataPath = "/var/lib/casaos/conf"
Cfg.SaveTo(configDir)
}
if len(AppInfo.TempPath) == 0 {
AppInfo.TempPath = "/var/lib/casaos/temp"
Cfg.SaveTo(configDir)
}
if len(CommonInfo.RuntimePath) == 0 {
CommonInfo.RuntimePath = "/var/run/casaos"
}
Cfg.SaveTo(configDir)
// AppInfo.ProjectPath = getCurrentDirectory() //os.Getwd()
}

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-13 18:15:46
* @LastEditors: LinkLeong
* @LastEditTime: 2022-07-27 11:25:26
* @LastEditTime: 2022-08-31 13:39:24
* @FilePath: /CasaOS/pkg/sqlite/db.go
* @Description:
* @Website: https://www.casaos.io
@ -43,17 +43,7 @@ func GetDb(dbPath string) *gorm.DB {
}
gdb = db
db.Exec(`alter table o_user rename to old_user;
create table o_users ( id integer primary key,username text,password text,role text,email text,nickname text,avatar text,description text,created_at datetime,updated_at datetime);
insert into o_users select id,user_name,password,role,email,nick_name,avatar,description,created_at,updated_at from old_user;
drop table old_user;
drop table o_user;
`)
err = db.AutoMigrate(&model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.UserDBModel{}, model2.SharesDBModel{}, model2.ConnectionsDBModel{})
err = db.AutoMigrate(&model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.SharesDBModel{}, model2.ConnectionsDBModel{})
db.Exec("DROP TABLE IF EXISTS o_application")
db.Exec("DROP TABLE IF EXISTS o_friend")
db.Exec("DROP TABLE IF EXISTS o_person_download")

View File

@ -5,7 +5,7 @@
* @Author: LinkLeong link@icewhale.org
* @Date: 2022-08-12 14:22:28
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-24 18:52:36
* @LastEditTime: 2022-08-31 16:02:31
* @FilePath: /CasaOS/route/darwin.go
* @Description:
* @Website: https://www.casaos.io

View File

@ -10,25 +10,16 @@ import (
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/samba"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
"github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
uuid "github.com/satori/go.uuid"
"go.uber.org/zap"
)
func InitFunction() {
ShellInit()
CheckSerialDiskMount()
CheckToken2_11()
ImportApplications()
// Soon to be removed
ChangeAPIUrl()
MoveUserToDB()
go InitNetworkMount()
}
func CheckSerialDiskMount() {
@ -70,79 +61,6 @@ func CheckSerialDiskMount() {
service.MyService.Disk().RemoveLSBLKCache()
command.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;AutoRemoveUnuseDir")
}
func ShellInit() {
command.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/assist.sh | bash")
if !file.CheckNotExist("/casaOS") {
command.OnlyExec("source /casaOS/server/shell/update.sh ;")
command.OnlyExec("source " + config.AppInfo.ShellPath + "/delete-old-service.sh ;")
}
}
func CheckToken2_11() {
if len(config.ServerInfo.Token) == 0 {
token := uuid.NewV4().String
config.ServerInfo.Token = token()
config.Cfg.Section("server").Key("Token").SetValue(token())
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 service.MyService.System().GetSysInfo().KernelArch == "aarch64" && config.ServerInfo.USBAutoMount != "True" && strings.Contains(service.MyService.System().GetDeviceTree(), "Raspberry Pi") {
service.MyService.System().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False")
}
// str := []string{}
// str = append(str, "ddd")
// str = append(str, "aaa")
// ddd := strings.Join(str, "|")
// config.Cfg.Section("file").Key("ShareDir").SetValue(ddd)
// config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
func ImportApplications() {
service.MyService.App().ImportApplications(true)
}
// 0.3.1
func ChangeAPIUrl() {
newAPIUrl := "https://api.casaos.io/casaos-api"
if config.ServerInfo.ServerApi == "https://api.casaos.zimaboard.com" {
config.ServerInfo.ServerApi = newAPIUrl
config.Cfg.Section("server").Key("ServerApi").SetValue(newAPIUrl)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
}
//0.3.3
//Transferring user data to the database
func MoveUserToDB() {
if len(config.UserInfo.UserName) > 0 && service.MyService.User().GetUserInfoByUserName(config.UserInfo.UserName).Id == 0 {
user := model2.UserDBModel{}
user.Username = config.UserInfo.UserName
user.Email = config.UserInfo.Email
user.Nickname = config.UserInfo.NickName
user.Password = encryption.GetMD5ByStr(config.UserInfo.PWD)
user.Role = "admin"
user = service.MyService.User().CreateUser(user)
if user.Id > 0 {
userPath := config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id)
file.MkDir(userPath)
os.Rename("/casaOS/server/conf/app_order.json", userPath+"/app_order.json")
}
}
}
func InitNetworkMount() {
time.Sleep(time.Second * 10)

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-07-01 15:11:36
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-24 18:54:03
* @LastEditTime: 2022-08-31 17:20:54
* @FilePath: /CasaOS/route/periodical.go
* @Description:
* @Website: https://www.casaos.io

View File

@ -1,9 +1,9 @@
package route
import (
jwt2 "github.com/IceWhaleTech/CasaOS-Common/utils/jwt"
"github.com/IceWhaleTech/CasaOS/middleware"
"github.com/IceWhaleTech/CasaOS/pkg/config"
jwt2 "github.com/IceWhaleTech/CasaOS/pkg/utils/jwt"
v1 "github.com/IceWhaleTech/CasaOS/route/v1"
"github.com/gin-contrib/gzip"
@ -27,14 +27,14 @@ func InitRouter() *gin.Engine {
// c.Redirect(http.StatusMovedPermanently, "ui/")
//})
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/users/refresh", v1.PostUserRefreshToken)
// No short-term modifications
r.GET("/v1/users/image", v1.GetUserImage)
// 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/users/refresh", v1.PostUserRefreshToken)
// // No short-term modifications
// r.GET("/v1/users/image", v1.GetUserImage)
r.GET("/v1/users/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
@ -45,28 +45,28 @@ func InitRouter() *gin.Engine {
v1Group.Use(jwt2.JWT())
{
v1UsersGroup := v1Group.Group("/users")
v1UsersGroup.Use()
{
v1UsersGroup.GET("/current", v1.GetUserInfo)
v1UsersGroup.PUT("/current", v1.PutUserInfo)
v1UsersGroup.PUT("/current/password", v1.PutUserPassword)
// 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.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)
v1UsersGroup.PUT("/current/image/:key", v1.PutUserImage)
//v1UserGroup.POST("/file/image/:key", v1.PostUserFileImage)
v1UsersGroup.DELETE("/current/image", v1.DeleteUserImage)
// v1UsersGroup.POST("/current/image/:key", v1.PostUserUploadImage)
// v1UsersGroup.PUT("/current/image/:key", v1.PutUserImage)
// //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)
}
// //v1UserGroup.PUT("/avatar", v1.PutUserAvatar)
// //v1UserGroup.GET("/avatar", v1.GetUserAvatar)
// v1UsersGroup.DELETE("/:id", v1.DeleteUser)
// v1UsersGroup.GET("/:username", v1.GetUserInfoByUsername)
// v1UsersGroup.DELETE("", v1.DeleteUserAll)
// }
v1AppsGroup := v1Group.Group("/apps")
v1AppsGroup.Use()

View File

@ -421,6 +421,9 @@ func GetSystemUtilization(c *gin.Context) {
cpuData := make(map[string]interface{})
cpuData["percent"] = cpu
cpuData["num"] = num
cpuData["temperature"] = service.MyService.System().GetCPUTemperature()
cpuData["power"] = service.MyService.System().GetCPUPower()
data["cpu"] = cpuData
data["mem"] = service.MyService.System().GetMemInfo()

View File

@ -1,683 +0,0 @@
package v1
import (
json2 "encoding/json"
"io/ioutil"
"net/http"
url2 "net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/model/system_model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
"github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/jwt"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
uuid "github.com/satori/go.uuid"
"github.com/tidwall/gjson"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin"
)
// @Summary register user
// @Router /user/register/ [post]
func PostUserRegister(c *gin.Context) {
json := make(map[string]string)
c.ShouldBind(&json)
username := json["username"]
pwd := json["password"]
key := json["key"]
if _, ok := service.UserRegisterHash[key]; !ok {
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(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(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(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(pwd)
user.Role = "admin"
user = service.MyService.User().CreateUser(user)
if user.Id == 0 {
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(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
}
// @Summary login
// @Produce application/json
// @Accept application/json
// @Tags user
// @Param user_name query string true "User name"
// @Param pwd query string true "password"
// @Success 200 {string} string "ok"
// @Router /user/login [post]
func PostUserLogin(c *gin.Context) {
json := make(map[string]string)
c.ShouldBind(&json)
username := json["username"]
password := json["password"]
//check params is empty
if len(username) == 0 || len(password) == 0 {
c.JSON(common_err.CLIENT_ERROR,
model.Result{
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(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(common_err.CLIENT_ERROR,
model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
return
}
token := system_model.VerifyInformation{}
token.AccessToken = jwt.GetAccessToken(user.Username, user.Password, user.Id)
token.RefreshToken = jwt.GetRefreshToken(user.Username, user.Password, user.Id)
token.ExpiresAt = time.Now().Add(3 * time.Hour * time.Duration(1)).Unix()
data := make(map[string]interface{}, 2)
user.Password = ""
data["token"] = token
// TODO:1 Database fields cannot be external
data["user"] = user
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
Data: data,
})
}
// @Summary edit user head
// @Produce application/json
// @Accept multipart/form-data
// @Tags user
// @Param file formData file true "用户头像"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /user/avatar [put]
func PutUserAvatar(c *gin.Context) {
id := c.GetHeader("user_id")
user := service.MyService.User().GetUserInfoById(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
}
f, err := c.FormFile("file")
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: err.Error()})
return
}
if len(user.Avatar) > 0 {
os.RemoveAll(config.AppInfo.UserDataPath + "/" + id + "/" + user.Avatar)
}
ext := filepath.Ext(f.Filename)
avatarPath := config.AppInfo.UserDataPath + "/" + id + "/avatar" + ext
c.SaveUploadedFile(f, avatarPath)
user.Avatar = avatarPath
service.MyService.User().UpdateUser(user)
c.JSON(http.StatusOK,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
Data: user,
})
}
// @Summary edit user name
// @Produce application/json
// @Accept application/json
// @Tags user
// @Param old_name query string true "Old user name"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /user/name/:id [put]
func PutUserInfo(c *gin.Context) {
id := c.GetHeader("user_id")
json := model2.UserDBModel{}
c.ShouldBind(&json)
user := service.MyService.User().GetUserInfoById(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 len(json.Username) > 0 {
u := service.MyService.User().GetUserInfoByUserName(json.Username)
if u.Id > 0 {
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.Email) == 0 {
json.Email = user.Email
}
if len(json.Avatar) == 0 {
json.Avatar = user.Avatar
}
if len(json.Role) == 0 {
json.Role = user.Role
}
if len(json.Description) == 0 {
json.Description = user.Description
}
if len(json.Nickname) == 0 {
json.Nickname = user.Nickname
}
service.MyService.User().UpdateUser(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
// @Produce application/json
// @Accept application/json
// @Tags user
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /user/password/:id [put]
func PutUserPassword(c *gin.Context) {
id := c.GetHeader("user_id")
json := make(map[string]string)
c.ShouldBind(&json)
oldPwd := json["old_password"]
pwd := json["password"]
if len(oldPwd) == 0 || len(pwd) == 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 user.Password != encryption.GetMD5ByStr(oldPwd) {
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(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: user})
}
// @Summary edit user nick
// @Produce application/json
// @Accept application/json
// @Tags user
// @Param nick_name query string false "nick name"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /user/nick [put]
func PutUserNick(c *gin.Context) {
id := c.GetHeader("user_id")
json := make(map[string]string)
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)})
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)})
return
}
user.Nickname = Nickname
service.MyService.User().UpdateUser(user)
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: user})
}
// @Summary edit user description
// @Produce application/json
// @Accept multipart/form-data
// @Tags user
// @Param description formData string false "Description"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /user/desc [put]
func PutUserDesc(c *gin.Context) {
id := c.GetHeader("user_id")
json := make(map[string]string)
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)})
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)})
return
}
user.Description = desc
service.MyService.User().UpdateUser(user)
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: user})
}
// @Summary get user info
// @Produce application/json
// @Accept application/json
// @Tags user
// @Success 200 {string} string "ok"
// @Router /user/info/:id [get]
func GetUserInfo(c *gin.Context) {
id := c.GetHeader("user_id")
user := service.MyService.User().GetUserInfoById(id)
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
Data: user,
})
}
/**
* @description:
* @param {*gin.Context} c
* @param {string} Username
* @return {*}
* @method:
* @router:
*/
func GetUserInfoByUsername(c *gin.Context) {
username := c.Param("username")
if len(username) == 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().GetUserInfoByUserName(username)
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
}
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
Data: user,
})
}
/**
* @description: get all Usernames
* @method:GET
* @router:/user/all/name
*/
func GetUserAllUsername(c *gin.Context) {
users := service.MyService.User().GetAllUserName()
names := []string{}
for _, v := range users {
names = append(names, v.Username)
}
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
Data: names,
})
}
/**
* @description:get custom file by user
* @param {path} name string "file name"
* @method: GET
* @router: /user/custom/:key
*/
func GetUserCustomConf(c *gin.Context) {
name := c.Param("key")
if len(name) == 0 {
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)
// user := service.MyService.User().GetUserInfoByUsername(Username)
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
}
filePath := config.AppInfo.UserDataPath + "/" + id + "/" + name + ".json"
data := file.ReadFullFile(filePath)
if !gjson.ValidBytes(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(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json2.RawMessage(string(data))})
}
/**
* @description:create or update custom conf by user
* @param {path} name string "file name"
* @method:POST
* @router:/user/custom/:key
*/
func PostUserCustomConf(c *gin.Context) {
name := c.Param("key")
if len(name) == 0 {
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(common_err.SERVICE_ERROR,
model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
return
}
data, _ := ioutil.ReadAll(c.Request.Body)
filePath := config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id)
file.WriteToPath(data, filePath, name+".json")
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json2.RawMessage(string(data))})
}
/**
* @description: delete user custom config
* @param {path} key string
* @method:delete
* @router:/user/custom/:key
*/
func DeleteUserCustomConf(c *gin.Context) {
name := c.Param("key")
if len(name) == 0 {
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(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"
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)})
}
/**
* @description:
* @param {path} id string "user id"
* @method:DELETE
* @router:/user/delete/:id
*/
func DeleteUser(c *gin.Context) {
id := c.Param("id")
service.MyService.User().DeleteUserById(id)
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: id})
}
/**
* @description:update user image
* @method:POST
* @router:/user/current/image/:key
*/
func PutUserImage(c *gin.Context) {
id := c.GetHeader("user_id")
json := make(map[string]string)
c.ShouldBind(&json)
path := json["path"]
key := c.Param("key")
if len(path) == 0 || len(key) == 0 {
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
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)})
return
}
_, err := file.GetImageExt(path)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: common_err.NOT_IMAGE, Message: common_err.GetMsg(common_err.NOT_IMAGE)})
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)})
return
}
fstat, _ := os.Stat(path)
if fstat.Size() > 10<<20 {
c.JSON(http.StatusOK, model.Result{Success: common_err.IMAGE_TOO_LARGE, Message: common_err.GetMsg(common_err.IMAGE_TOO_LARGE)})
return
}
ext := file.GetExt(path)
filePath := config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id) + "/" + key + ext
file.CopySingleFile(path, filePath, "overwrite")
data := make(map[string]string, 3)
data["path"] = filePath
data["file_name"] = key + ext
data["online_path"] = "/v1/users/image?path=" + filePath
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
/**
* @description:
* @param {*gin.Context} c
* @param {file} file
* @param {string} key
* @param {string} type:avatar,background
* @return {*}
* @method:
* @router:
*/
func PostUserUploadImage(c *gin.Context) {
id := c.GetHeader("user_id")
f, err := c.FormFile("file")
key := c.Param("key")
t := c.PostForm("type")
if len(key) == 0 {
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(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(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(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" {
key = "avatar"
}
path := config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id) + "/" + key + ext
c.SaveUploadedFile(f, path)
data := make(map[string]string, 3)
data["path"] = path
data["file_name"] = key + ext
data["online_path"] = "/v1/users/image?path=" + path
c.JSON(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
/**
* @description: get current user's image
* @method:GET
* @router:/user/image/:id
*/
func GetUserImage(c *gin.Context) {
filePath := c.Query("path")
if len(filePath) == 0 {
c.JSON(http.StatusNotFound, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
return
}
if !file.Exists(filePath) {
c.JSON(http.StatusNotFound, model.Result{Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST)})
return
}
if !strings.Contains(filePath, config.AppInfo.UserDataPath) {
c.JSON(http.StatusNotFound, model.Result{Success: common_err.INSUFFICIENT_PERMISSIONS, Message: common_err.GetMsg(common_err.INSUFFICIENT_PERMISSIONS)})
return
}
fileTmp, _ := os.Open(filePath)
defer fileTmp.Close()
fileName := path.Base(filePath)
// @tiger - RESTful 规范下不应该返回文件本身内容而是返回文件的静态URL由前端去解析
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
c.File(filePath)
}
func DeleteUserImage(c *gin.Context) {
id := c.GetHeader("user_id")
path := c.Query("path")
if len(path) == 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().GetUserInfoById(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 !file.Exists(path) {
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(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(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
}
/**
* @description:
* @param {*gin.Context} c
* @param {string} refresh_token
* @return {*}
* @method:
* @router:
*/
func PostUserRefreshToken(c *gin.Context) {
js := make(map[string]string)
c.ShouldBind(&js)
refresh := js["refresh_token"]
claims, err := jwt.ParseToken(refresh, true)
if err != nil {
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(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)
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(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(common_err.SUCCESS, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
}
// @Summary 检查是否进入引导状态
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/init/check [get]
func GetUserStatus(c *gin.Context) {
data := make(map[string]interface{}, 2)
if service.MyService.User().GetUserCount() > 0 {
data["initialized"] = true
data["key"] = ""
} else {
key := uuid.NewV4().String()
service.UserRegisterHash[key] = key
data["key"] = key
data["initialized"] = false
}
c.JSON(common_err.SUCCESS,
model.Result{
Success: common_err.SUCCESS,
Message: common_err.GetMsg(common_err.SUCCESS),
Data: data,
})
}

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-07-12 09:48:56
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-19 17:46:29
* @LastEditTime: 2022-09-02 10:57:12
* @FilePath: /CasaOS/service/service.go
* @Description:
* @Website: https://www.casaos.io
@ -27,7 +27,7 @@ var SocketRun bool
type Repository interface {
App() AppService
User() UserService
//User() UserService
Docker() DockerService
Casa() CasaService
Disk() DiskService
@ -40,15 +40,16 @@ type Repository interface {
}
func NewService(db *gorm.DB, RuntimePath string) Repository {
gatewayManagement, err := gateway.NewManagementService(RuntimePath)
if err != nil {
if err != nil && len(RuntimePath) > 0 {
panic(err)
}
return &store{
gateway: gatewayManagement,
app: NewAppService(db),
user: NewUserService(db),
gateway: gatewayManagement,
app: NewAppService(db),
//user: NewUserService(db),
docker: NewDockerService(),
casa: NewCasaService(),
disk: NewDiskService(db),
@ -61,9 +62,9 @@ func NewService(db *gorm.DB, RuntimePath string) Repository {
}
type store struct {
db *gorm.DB
app AppService
user UserService
db *gorm.DB
app AppService
//user UserService
docker DockerService
casa CasaService
disk DiskService
@ -101,9 +102,9 @@ func (c *store) App() AppService {
return c.app
}
func (c *store) User() UserService {
return c.user
}
// func (c *store) User() UserService {
// return c.user
// }
func (c *store) Docker() DockerService {
return c.docker

View File

@ -1,6 +0,0 @@
# copy to /etc/udev/rules.d path
KERNEL=="sd[a-z]*[0-9]", SUBSYSTEMS=="usb", ACTION=="add", RUN+="/bin/systemctl start usb-mount@%k.service"
KERNEL=="sd[a-z]*[0-9]", SUBSYSTEMS=="usb", ACTION=="remove", RUN+="/bin/systemctl stop usb-mount@%k.service"

View File

@ -1,3 +0,0 @@
#!/bin/bash

View File

@ -1,105 +0,0 @@
#!/bin/bash
###
# @Author: LinkLeong link@icewhale.com
# @Date: 2022-06-30 10:08:33
# @LastEditors: LinkLeong
# @LastEditTime: 2022-07-01 11:17:54
# @FilePath: /CasaOS/shell/delete-old-service.sh
# @Description:
###
((EUID)) && sudo_cmd="sudo"
# SYSTEM INFO
readonly UNAME_M="$(uname -m)"
# CasaOS PATHS
readonly CASA_REPO=IceWhaleTech/CasaOS
readonly CASA_UNZIP_TEMP_FOLDER=/tmp/casaos
readonly CASA_BIN=casaos
readonly CASA_BIN_PATH=/usr/bin/casaos
readonly CASA_CONF_PATH=/etc/casaos.conf
readonly CASA_SERVICE_PATH=/etc/systemd/system/casaos.service
readonly CASA_HELPER_PATH=/usr/share/casaos/shell/
readonly CASA_USER_CONF_PATH=/var/lib/casaos/conf/
readonly CASA_DB_PATH=/var/lib/casaos/db/
readonly CASA_TEMP_PATH=/var/lib/casaos/temp/
readonly CASA_LOGS_PATH=/var/log/casaos/
readonly CASA_PACKAGE_EXT=".tar.gz"
readonly CASA_RELEASE_API="https://api.github.com/repos/${CASA_REPO}/releases"
readonly CASA_OPENWRT_DOCS="https://github.com/IceWhaleTech/CasaOS-OpenWrt"
readonly COLOUR_RESET='\e[0m'
readonly aCOLOUR=(
'\e[38;5;154m' # green | Lines, bullets and separators
'\e[1m' # Bold white | Main descriptions
'\e[90m' # Grey | Credits
'\e[91m' # Red | Update notifications Alert
'\e[33m' # Yellow | Emphasis
)
Target_Arch=""
Target_Distro="debian"
Target_OS="linux"
Casa_Tag=""
#######################################
# Custom printing function
# Globals:
# None
# Arguments:
# $1 0:OK 1:FAILED 2:INFO 3:NOTICE
# message
# Returns:
# None
#######################################
Show() {
# OK
if (($1 == 0)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} OK $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# FAILED
elif (($1 == 1)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[3]}FAILED$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# INFO
elif (($1 == 2)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} INFO $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# NOTICE
elif (($1 == 3)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[4]}NOTICE$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
fi
}
Warn() {
echo -e "${aCOLOUR[3]}$1$COLOUR_RESET"
}
# 0 Check_exist
Check_Exist() {
#Create Dir
Show 2 "Create Folders."
${sudo_cmd} mkdir -p ${CASA_HELPER_PATH}
${sudo_cmd} mkdir -p ${CASA_LOGS_PATH}
${sudo_cmd} mkdir -p ${CASA_USER_CONF_PATH}
${sudo_cmd} mkdir -p ${CASA_DB_PATH}
${sudo_cmd} mkdir -p ${CASA_TEMP_PATH}
Show 2 "Start cleaning up the old version."
${sudo_cmd} rm -rf /usr/lib/systemd/system/casaos.service
${sudo_cmd} rm -rf /lib/systemd/system/casaos.service
${sudo_cmd} rm -rf /usr/local/bin/${CASA_BIN}
#Clean
if [[ -d "/casaOS" ]]; then
${sudo_cmd} rm -rf /casaOS
fi
Show 0 "Clearance completed."
$sudo_cmd systemctl restart ${CASA_BIN}
}
Check_Exist

View File

@ -1,388 +0,0 @@
#!/bin/bash
# 获取系统信息
GetSysInfo() {
if [ -s "/etc/redhat-release" ]; then
SYS_VERSION=$(cat /etc/redhat-release)
elif [ -s "/etc/issue" ]; then
SYS_VERSION=$(cat /etc/issue)
fi
SYS_INFO=$(uname -a)
SYS_BIT=$(getconf LONG_BIT)
MEM_TOTAL=$(free -m | grep Mem | awk '{print $2}')
CPU_INFO=$(getconf _NPROCESSORS_ONLN)
echo -e ${SYS_VERSION}
echo -e Bit:${SYS_BIT} Mem:${MEM_TOTAL}M Core:${CPU_INFO}
echo -e ${SYS_INFO}
}
#获取网卡信息
GetNetCard() {
if [ "$1" == "1" ]; then
if [ -d "/sys/devices/virtual/net" ]; then
ls /sys/devices/virtual/net
fi
else
if [ -d "/sys/devices/virtual/net" ] && [ -d "/sys/class/net" ]; then
ls /sys/class/net/ | grep -v "$(ls /sys/devices/virtual/net/)"
fi
fi
}
GetTimeZone(){
timedatectl | grep "Time zone" | awk '{printf $3}'
}
#查看网卡状态
#param 网卡名称
CatNetCardState() {
if [ -e "/sys/class/net/$1/operstate" ]; then
cat /sys/class/net/$1/operstate
fi
}
#获取docker根目录
GetDockerRootDir() {
if hash docker 2>/dev/null; then
docker info | grep 'Docker Root Dir' | awk -F ':' '{print $2}'
else
echo ""
fi
}
#删除安装应用文件夹
#param 需要删除的文件夹路径
DelAppConfigDir() {
if [ -d $1 ]; then
rm -fr $1
fi
}
#zerotier本机已加入的网络
#result start,end,sectors
GetLocalJoinNetworks() {
zerotier-cli listnetworks -j
}
#移除挂载点,删除已挂在的文件夹
UMountPorintAndRemoveDir() {
DEVICE=$1
MOUNT_POINT=$(mount | grep ${DEVICE} | awk '{ print $3 }')
if [[ -z ${MOUNT_POINT} ]]; then
${log} "Warning: ${DEVICE} is not mounted"
else
umount -lf ${DEVICE}
/bin/rmdir "${MOUNT_POINT}"
fi
}
#格式化fat32磁盘
#param 需要格式化的目录 /dev/sda1
#param 格式
FormatDisk() {
if [ "$2" == "fat32" ]; then
mkfs.vfat -F 32 $1
elif [ "$2" == "ntfs" ]; then
mkfs.ntfs $1
elif [ "$2" == "ext4" ]; then
mkfs.ext4 -m 1 -F $1
elif [ "$2" == "exfat" ]; then
mkfs.exfat $1
else
mkfs.ext4 -m 1 -F $1
fi
}
#删除分区
#param 路径 /dev/sdb
#param 删除分区的区号
DelPartition() {
fdisk $1 <<EOF
d
$2
wq
EOF
}
#添加分区只有一个分区
#param 路径 /dev/sdb
#param 要挂载的目录
AddPartition() {
DelPartition $1
parted -s $1 mklabel gpt
parted -s $1 mkpart primary ext4 0 100%
P=`lsblk -r $1 | sort | grep part | head -n 1 | awk '{print $1}'`
mkfs.ext4 -m 1 -F /dev/${P}
partprobe $1
}
#磁盘类型
GetDiskType() {
fdisk $1 -l | grep Disklabel | awk -F: '{print $2}'
}
#获磁盘的插入路径
#param 路径 /dev/sda
GetPlugInDisk() {
fdisk -l | grep 'Disk' | grep 'sd' | awk -F , '{print substr($1,11,3)}'
}
#获取磁盘状态
#param 磁盘路径
GetDiskHealthState() {
smartctl -H $1 | grep "SMART Health Status" | awk -F ":" '{print$2}'
}
#获取磁盘字节数量和扇区数量
#param 磁盘路径 /dev/sda
#result bytes
#result sectors
GetDiskSizeAndSectors() {
fdisk $1 -l | grep "$1:" | awk -F, 'BEGIN {OFS="\n"}{print $2,$3}' | awk '{print $1}'
}
#获取磁盘分区数据扇区
#param 磁盘路径 /dev/sda
#result start,end,sectors
GetPartitionSectors() {
fdisk $1 -l | grep "$1[1-9]" | awk 'BEGIN{OFS=","}{print $1,$2,$3,$4}'
}
#检查没有使用的挂载点删除文件夹
AutoRemoveUnuseDir() {
DIRECTORY="/DATA/"
dir=$(ls -l $DIRECTORY | grep "USB_Storage_sd[a-z][0-9]" | awk '/^d/ {print $NF}')
for i in $dir; do
path="$DIRECTORY$i"
mountStr=$(mountpoint $path)
notMountpoint="is not a mountpoint"
if [[ $mountStr =~ $notMountpoint ]]; then
if [ "$(ls -A $path)" = "" ]; then
rm -fr $path
else
echo "$path is not empty"
fi
fi
done
}
#重载samba服务
ReloadSamba() {
/etc/init.d/smbd reload
}
# $1=sda1
# $2=volume{1}
do_mount() {
DEVBASE=$1
DEVICE="${DEVBASE}"
# See if this drive is already mounted, and if so where
MOUNT_POINT=$(lsblk -o name,mountpoint | grep ${DEVICE} | awk '{print $2}')
if [ -n "${MOUNT_POINT}" ]; then
${log} "Warning: ${DEVICE} is already mounted at ${MOUNT_POINT}"
exit 1
fi
# Get info for this drive: $ID_FS_LABEL and $ID_FS_TYPE
eval $(blkid -o udev ${DEVICE} | grep -i -e "ID_FS_LABEL" -e "ID_FS_TYPE")
LABEL=$2
if grep -q " ${LABEL} " /etc/mtab; then
# Already in use, make a unique one
LABEL+="-${DEVBASE}"
fi
DEV_LABEL="${LABEL}"
# Use the device name in case the drive doesn't have label
if [ -z ${DEV_LABEL} ]; then
DEV_LABEL="${DEVBASE}"
fi
MOUNT_POINT="${DEV_LABEL}"
${log} "Mount point: ${MOUNT_POINT}"
mkdir -p ${MOUNT_POINT}
case ${ID_FS_TYPE} in
vfat)
mount -t vfat -o rw,relatime,users,gid=100,umask=000,shortname=mixed,utf8=1,flush ${DEVICE} ${MOUNT_POINT}
;;
ext[2-4])
mount -o noatime ${DEVICE} ${MOUNT_POINT} >/dev/null 2>&1
;;
exfat)
mount -t exfat ${DEVICE} ${MOUNT_POINT} >/dev/null 2>&1
;;
ntfs)
ntfs-3g ${DEVICE} ${MOUNT_POINT}
;;
iso9660)
mount -t iso9660 ${DEVICE} ${MOUNT_POINT}
;;
*)
/bin/rmdir "${MOUNT_POINT}"
exit 0
;;
esac
}
# $1=sda1
do_umount() {
log="logger -t usb-mount.sh -s "
DEVBASE=$1
DEVICE="${DEVBASE}"
MOUNT_POINT=$(mount | grep ${DEVICE} | awk '{ print $3 }')
if [[ -z ${MOUNT_POINT} ]]; then
${log} "Warning: ${DEVICE} is not mounted"
else
/bin/kill -9 $(lsof ${MOUNT_POINT})
umount -l ${DEVICE}
${log} "Unmounted ${DEVICE} from ${MOUNT_POINT}"
if [ "`ls -A ${MOUNT_POINT}`" = "" ]; then
/bin/rm -fr "${MOUNT_POINT}"
fi
sed -i.bak "\@${MOUNT_POINT}@d" /var/log/usb-mount.track
fi
}
# $1=/mnt/volume1/data.img
# $2=100G
PackageDocker() {
image=$1
docker="/mnt/casa_docker"
#判断目录docker存在不存在则创建,存在检查是否为空
if [ ! -d "$docker" ]; then
mkdir ${docker}
fi
if [ "$(ls -A $docker)" = "" ]; then
echo "$docker count is 0"
else
mkdir ${docker}_bak
mv -r ${docker} ${docker}_bak
fi
daemon="/etc/docker/daemon.json"
#1创建img文件在挂载的目录
fallocate -l $2 $image
#2初始化img文件
mkfs -t ext4 $image
#3挂载img文件
sudo mount -o loop $image $docker
#4给移动/var/lib/docker数据到img挂载的目录
systemctl stop docker.socket
systemctl stop docker
cp -r /var/lib/docker/* ${docker}/
#5在/etc/docker写入daemon.json(需要检查)
if [ -d "$daemon" ]; then
mv -r $daemon ${daemon}.bak
fi
echo "{\"data-root\": \"$docker\"}" >$daemon
#删除老数据腾出空间
#rm -fr /var/lib/docker
systemctl start docker.socket
systemctl start docker
}
DockerImgMove() {
image=$1
systemctl stop docker.socket
systemctl stop docker
sudo umount -f $image
}
GetDockerDataRoot() {
docker info | grep "Docker Root Dir:"
}
SetLink() {
ln -s /mnt/casa_sda1/AppData /DATA/AppData
#删除所有软链
find /DATA -type l -delete
}
#压缩文件夹
TarFolder() {
#压缩
tar -zcvf data.tar.gz -C/DATA/ AppDataBak/
#解压
tar zxvf data.tar.gz
#查看某文件夹下的所有包括子文件夹文件
ls /DATA/Media -lR | grep "^-" | wc -l
# ls -lR|grep "^d"| wc -l 查看某个文件夹下文件夹的个数,包括子文件夹下的文件夹个数。
#查看固定文件夹大小
du -sh /DATA
}
USB_Start_Auto() {
((EUID)) && sudo_cmd="sudo"
$sudo_cmd systemctl enable devmon@devmon
$sudo_cmd systemctl start devmon@devmon
}
USB_Stop_Auto() {
((EUID)) && sudo_cmd="sudo"
$sudo_cmd systemctl stop devmon@devmon
$sudo_cmd systemctl disable devmon@devmon
$sudo_cmd udevil clean
}
GetDeviceTree(){
cat /proc/device-tree/model
}
# restart samba service
RestartSMBD(){
$sudo_cmd systemctl restart smbd
}
# edit user password $1:username
EditSmabaUserPassword(){
$sudo_cmd smbpasswd $1
}
AddSmabaUser(){
$sudo_cmd useradd $1
$sudo_cmd smbpasswd -a $1 <<EOF
$2
$2
EOF
}
# $1:username $2:host $3:share $4:port $5:mountpoint $6:password
MountCIFS(){
$sudo_cmd mount -t cifs -o username=$1,password=$6,port=$4 //$2/$3 $5
}
# $1:service name
CheckServiceStatus(){
rs="`systemctl status $1 |grep -E 'Active|PID'`"
#echo "$rs"
run="`echo "$rs" |grep -B 2 'running'`"
fai="`echo "$rs" |grep -E -B 2 'failed|inactive|dead'`"
if [ "$run" == "" ]
then
echo "failed"
else
echo "running"
fi
}
UDEVILUmount(){
$sudo_cmd udevil umount -f $1
}

View File

@ -1,268 +0,0 @@
#!/bin/bash
###
# @Author: LinkLeong link@icewhale.com
# @Date: 2022-06-30 10:08:33
# @LastEditors: LinkLeong
# @LastEditTime: 2022-07-01 11:18:07
# @FilePath: /CasaOS/shell/update.sh
# @Description:
###
((EUID)) && sudo_cmd="sudo"
# SYSTEM INFO
readonly UNAME_M="$(uname -m)"
# CasaOS PATHS
readonly CASA_REPO=IceWhaleTech/CasaOS
readonly CASA_UNZIP_TEMP_FOLDER=/tmp/casaos
readonly CASA_BIN=casaos
readonly CASA_BIN_PATH=/usr/bin/casaos
readonly CASA_CONF_PATH=/etc/casaos.conf
readonly CASA_SERVICE_PATH=/etc/systemd/system/casaos.service
readonly CASA_HELPER_PATH=/usr/share/casaos/shell/
readonly CASA_USER_CONF_PATH=/var/lib/casaos/conf/
readonly CASA_DB_PATH=/var/lib/casaos/db/
readonly CASA_TEMP_PATH=/var/lib/casaos/temp/
readonly CASA_LOGS_PATH=/var/log/casaos/
readonly CASA_PACKAGE_EXT=".tar.gz"
readonly CASA_RELEASE_API="https://api.github.com/repos/${CASA_REPO}/releases"
readonly CASA_OPENWRT_DOCS="https://github.com/IceWhaleTech/CasaOS-OpenWrt"
readonly COLOUR_RESET='\e[0m'
readonly aCOLOUR=(
'\e[38;5;154m' # green | Lines, bullets and separators
'\e[1m' # Bold white | Main descriptions
'\e[90m' # Grey | Credits
'\e[91m' # Red | Update notifications Alert
'\e[33m' # Yellow | Emphasis
)
Target_Arch=""
Target_Distro="debian"
Target_OS="linux"
Casa_Tag=""
#######################################
# Custom printing function
# Globals:
# None
# Arguments:
# $1 0:OK 1:FAILED 2:INFO 3:NOTICE
# message
# Returns:
# None
#######################################
Show() {
# OK
if (($1 == 0)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} OK $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# FAILED
elif (($1 == 1)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[3]}FAILED$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# INFO
elif (($1 == 2)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[0]} INFO $COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
# NOTICE
elif (($1 == 3)); then
echo -e "${aCOLOUR[2]}[$COLOUR_RESET${aCOLOUR[4]}NOTICE$COLOUR_RESET${aCOLOUR[2]}]$COLOUR_RESET $2"
fi
}
Warn() {
echo -e "${aCOLOUR[3]}$1$COLOUR_RESET"
}
# 0 Check_exist
Check_Exist() {
#Create Dir
Show 2 "Create Folders."
${sudo_cmd} mkdir -p ${CASA_HELPER_PATH}
${sudo_cmd} mkdir -p ${CASA_LOGS_PATH}
${sudo_cmd} mkdir -p ${CASA_USER_CONF_PATH}
${sudo_cmd} mkdir -p ${CASA_DB_PATH}
${sudo_cmd} mkdir -p ${CASA_TEMP_PATH}
Show 2 "Start cleaning up the old version."
${sudo_cmd} rm -rf /usr/lib/systemd/system/casaos.service
${sudo_cmd} rm -rf /lib/systemd/system/casaos.service
if [[ -f "/casaOS/server/conf/conf.ini" ]]; then
${sudo_cmd} cp -rf /casaOS/server/conf/conf.ini ${CASA_CONF_PATH}
${sudo_cmd} cp -rf /casaOS/server/conf/*.json ${CASA_USER_CONF_PATH}
fi
if [[ -d "/casaOS/server/db" ]]; then
${sudo_cmd} cp -rf /casaOS/server/db/* ${CASA_DB_PATH}
fi
Show 0 "Clearance completed."
}
# 1 Check Arch
Check_Arch() {
case $UNAME_M in
*aarch64*)
Target_Arch="arm64"
;;
*64*)
Target_Arch="amd64"
;;
*armv7*)
Target_Arch="arm-7"
;;
*)
Show 1 "Aborted, unsupported or unknown architecture: $UNAME_M"
exit 1
;;
esac
Show 0 "Your hardware architecture is : $UNAME_M"
}
#Download CasaOS Package
Download_CasaOS() {
Show 2 "Downloading CasaOS for ${Target_OS}/${Target_Arch}..."
Net_Getter="curl -fsSLk"
Casa_Package="${Target_OS}-${Target_Arch}-casaos${CASA_PACKAGE_EXT}"
if [[ ! -n "$version" ]]; then
Casa_Tag="$(${Net_Getter} ${CASA_RELEASE_API}/latest | grep -o '"tag_name": ".*"' | sed 's/"//g' | sed 's/tag_name: //g')"
elif [[ $version == "pre" ]]; then
Casa_Tag="$(${net_getter} ${CASA_RELEASE_API} | grep -o '"tag_name": ".*"' | sed 's/"//g' | sed 's/tag_name: //g' | sed -n '1p')"
else
Casa_Tag="$version"
fi
Casa_Package_URL="https://github.com/${CASA_REPO}/releases/download/${Casa_Tag}/${Casa_Package}"
echo
# Remove Temp File
${sudo_cmd} rm -rf "$PREFIX/tmp/${Casa_Package}"
# Download Package
${Net_Getter} "${Casa_Package_URL}" >"$PREFIX/tmp/${Casa_Package}"
if [[ $? -ne 0 ]]; then
Show 1 "Download failed, Please check if your internet connection is working and retry."
exit 1
else
Show 0 "Download successful!"
fi
#Extract CasaOS Package
Show 2 "Extracting..."
case "${Casa_Package}" in
*.zip) ${sudo_cmd} unzip -o "$PREFIX/tmp/${Casa_Package}" -d "$PREFIX/tmp/" ;;
*.tar.gz) ${sudo_cmd} tar -xzf "$PREFIX/tmp/${Casa_Package}" -C "$PREFIX/tmp/" ;;
esac
#Setting Executable Permissions
${sudo_cmd} chmod +x "$PREFIX${CASA_UNZIP_TEMP_FOLDER}/${CASA_BIN}"
}
#Install Addons
Install_Addons() {
Show 2 "Installing CasaOS Addons"
${sudo_cmd} cp -rf "$PREFIX${CASA_UNZIP_TEMP_FOLDER}/shell/11-usb-mount.rules" "/etc/udev/rules.d/"
${sudo_cmd} cp -rf "$PREFIX${CASA_UNZIP_TEMP_FOLDER}/shell/usb-mount@.service" "/etc/systemd/system/"
sync
}
#Clean Temp Files
Clean_Temp_Files() {
Show 0 "Clean..."
${sudo_cmd} rm -rf "$PREFIX${CASA_UNZIP_TEMP_FOLDER}"
sync
}
#Install CasaOS
Install_CasaOS() {
Show 2 "Installing..."
# Install Bin
${sudo_cmd} mv -f $PREFIX${CASA_UNZIP_TEMP_FOLDER}/${CASA_BIN} ${CASA_BIN_PATH}
# Install Helper
if [[ -d ${CASA_HELPER_PATH} ]]; then
${sudo_cmd} rm -rf ${CASA_HELPER_PATH}*
fi
${sudo_cmd} cp -rf $PREFIX${CASA_UNZIP_TEMP_FOLDER}/shell/* ${CASA_HELPER_PATH}
#Setting Executable Permissions
${sudo_cmd} chmod +x $PREFIX${CASA_HELPER_PATH}*
# Install Conf
if [[ ! -f ${CASA_CONF_PATH} ]]; then
if [[ -f $PREFIX${CASA_UNZIP_TEMP_FOLDER}/conf/conf.ini.sample ]]; then
${sudo_cmd} mv -f $PREFIX${CASA_UNZIP_TEMP_FOLDER}/conf/conf.ini.sample ${CASA_CONF_PATH}
else
${sudo_cmd} mv -f $PREFIX${CASA_UNZIP_TEMP_FOLDER}/conf/conf.conf.sample ${CASA_CONF_PATH}
fi
fi
sync
if [[ ! -x "$(command -v ${CASA_BIN})" ]]; then
Show 1 "Installation failed, please try again."
exit 1
else
Show 0 "CasaOS Successfully installed."
fi
}
#Generate Service File
Generate_Service() {
if [ -f ${CASA_SERVICE_PATH} ]; then
Show 2 "Try stop CasaOS system service."
# Stop before generation
if [[ $(systemctl is-active ${CASA_BIN} &>/dev/null) ]]; then
${sudo_cmd} systemctl stop ${CASA_BIN}
fi
fi
Show 2 "Create system service for CasaOS."
${sudo_cmd} tee ${CASA_SERVICE_PATH} >/dev/null <<EOF
[Unit]
Description=CasaOS Service
StartLimitIntervalSec=0
[Service]
Type=simple
LimitNOFILE=15210
Restart=always
RestartSec=1
User=root
ExecStart=${CASA_BIN_PATH} -c ${CASA_CONF_PATH}
[Install]
WantedBy=multi-user.target
EOF
Show 0 "CasaOS service Successfully created."
}
# Start CasaOS
Start_CasaOS() {
Show 2 "Create a system startup service for CasaOS."
$sudo_cmd systemctl daemon-reload
$sudo_cmd systemctl enable ${CASA_BIN}
}
Check_Arch
# Step 7: Download CasaOS
Check_Exist
Download_CasaOS
# Step 8: Install Addon
Install_Addons
# Step 9: Install CasaOS
Install_CasaOS
# Step 10: Generate_Service
Generate_Service
# Step 11: Start CasaOS
Start_CasaOS
Clean_Temp_Files

View File

@ -1,136 +0,0 @@
#!/bin/bash
# copy to /casaOS/util/shell path
# chmod 755
log="logger -t usb-mount.sh -s "
ACTION=$1
DEVBASE=$2
DEVICE="/dev/${DEVBASE}"
# See if this drive is already mounted, and if so where
MOUNT_POINT=$(lsblk -l -p -o name,mountpoint | grep ${DEVICE} | awk '{print $2}')
do_mount() {
if [ -n "${MOUNT_POINT}" ]; then
${log} "Warning: ${DEVICE} is already mounted at ${MOUNT_POINT}"
exit 1
fi
# Get info for this drive: $ID_FS_LABEL and $ID_FS_TYPE
eval $(blkid -o udev ${DEVICE} | grep -i -e "ID_FS_LABEL" -e "ID_FS_TYPE")
#ID_FS_LABEL=新加卷
#ID_FS_LABEL_ENC=新加卷
#ID_FS_TYPE=ntfs
# Figure out a mount point to use
# LABEL=${ID_FS_LABEL}
LABEL=${DEVBASE}
if grep -q " /DATA/USB_Storage_${LABEL} " /etc/mtab; then
# Already in use, make a unique one
LABEL+="_${DEVBASE}"
fi
DEV_LABEL="${LABEL}"
# Use the device name in case the drive doesn't have label
if [ -z ${DEV_LABEL} ]; then
DEV_LABEL="${DEVBASE}"
fi
MOUNT_POINT="/DATA/USB_Storage_${DEV_LABEL}"
${log} "Mount point: ${MOUNT_POINT}"
mkdir -p ${MOUNT_POINT}
# MOUNT_POINT="/DATA/USB_Storage1"
# arr=("/DATA/USB_Storage1" "/DATA/USB_Storage2" "/DATA/USB_Storage3" "/DATA/USB_Storage4" "/DATA/USB_Storage5" "/DATA/USB_Storage6" "/DATA/USB_Storage7" "/DATA/USB_Storage8" "/DATA/USB_Storage9" "/DATA/USB_Storage10" "/DATA/USB_Storage11" "/DATA/USB_Storage12")
# for folder in ${arr[@]}; do
# #如果文件夹不存在,创建文件夹
# if [ ! -d "$folder" ]; then
# mkdir -p ${folder}
# MOUNT_POINT=$folder
# break
# fi
# done
# ${log} "Mount point: ${MOUNT_POINT}"
# # Global mount options
# OPTS="rw,relatime"
#
# # File system type specific mount options
# if [[ ${ID_FS_TYPE} == "vfat" ]]; then
# OPTS+=",users,gid=100,umask=000,shortname=mixed,utf8=1,flush"
# fi
# if ! mount -o ${OPTS} ${DEVICE} ${MOUNT_POINT}; then
# ${log} "Error mounting ${DEVICE} (status = $?)"
# rmdir "${MOUNT_POINT}"
# exit 1
# else
# # Track the mounted drives
# echo "${MOUNT_POINT}:${DEVBASE}" | cat >>"/var/log/usb-mount.track"
# fi
#
# ${log} "Mounted ${DEVICE} at ${MOUNT_POINT}"
case ${ID_FS_TYPE} in
vfat)
mount -t vfat -o rw,relatime,users,gid=100,umask=000,shortname=mixed,utf8=1,flush ${DEVICE} ${MOUNT_POINT}
;;
ext[2-4])
mount -o noatime ${DEVICE} ${MOUNT_POINT} >/dev/null 2>&1
;;
exfat)
mount -t exfat ${DEVICE} ${MOUNT_POINT} >/dev/null 2>&1
;;
ntfs)
ntfs-3g ${DEVICE} ${MOUNT_POINT}
;;
iso9660)
mount -t iso9660 ${DEVICE} ${MOUNT_POINT}
;;
*)
/bin/rmdir "${MOUNT_POINT}"
exit 0
;;
esac
}
do_umount() {
if [[ -z ${MOUNT_POINT} ]]; then
${log} "Warning: ${DEVICE} is not mounted"
else
#/bin/kill -9 $(lsof ${MOUNT_POINT})
umount -l ${DEVICE}
${log} "Unmounted ${DEVICE} from ${MOUNT_POINT}"
if [ "`ls -A ${MOUNT_POINT}`" = "" ]; then
/bin/rm -fr "${MOUNT_POINT}"
fi
sed -i.bak "\@${MOUNT_POINT}@d" /var/log/usb-mount.track
fi
}
case "${ACTION}" in
add)
do_mount
;;
remove)
do_umount
;;
*)
exit 1
;;
esac

View File

@ -1,8 +0,0 @@
# copy to /etc/systemd/system path
[Unit]
Description=Mount USB Drive on %i
[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/casaOS/server/shell/usb-mount.sh add %i
ExecStop=/casaOS/server/shell/usb-mount.sh remove %i

View File

@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-02-17 18:53:22
* @LastEditors: LinkLeong
* @LastEditTime: 2022-08-10 13:50:57
* @LastEditTime: 2022-08-25 12:06:41
* @FilePath: /CasaOS/types/system.go
* @Description:
* @Website: https://www.casaos.io
@ -10,6 +10,6 @@
*/
package types
const CURRENTVERSION = "0.3.5"
const CURRENTVERSION = "0.3.6"
const BODY = " "