mirror of
https://github.com/IceWhaleTech/CasaOS.git
synced 2025-12-23 21:14:41 +00:00
Compare commits
28 Commits
v0.3.1.1
...
v0.3.3-alp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
752134942a | ||
|
|
faf683a02c | ||
|
|
f99f49dd7e | ||
|
|
b0dc30277b | ||
|
|
d91fef0a19 | ||
|
|
6bb044ab04 | ||
|
|
78479f9604 | ||
|
|
8fe893847f | ||
|
|
f506d6ce49 | ||
|
|
5d7c5ba120 | ||
|
|
eedffd7c19 | ||
|
|
0885c1386d | ||
|
|
0297fe67af | ||
|
|
3f53e6f33b | ||
|
|
94d0efdb12 | ||
|
|
1e821d1c10 | ||
|
|
2c80b53ee8 | ||
|
|
c33af66c6e | ||
|
|
9d47874ae3 | ||
|
|
c7b7a30210 | ||
|
|
fde665cd4d | ||
|
|
eaf2341a2a | ||
|
|
d4bed3e5c7 | ||
|
|
fcb2b3f5a5 | ||
|
|
60349c941a | ||
|
|
11bc70a710 | ||
|
|
665766019f | ||
|
|
57cef9624c |
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Questions, Ideas, Discussions
|
||||
url: https://github.com/IceWhaleTech/CasaOS/discussions
|
||||
about: Ask questions, propose ideas, or discuss anything related to CasaOS
|
||||
4
.github/workflows/demo.yml
vendored
4
.github/workflows/demo.yml
vendored
@@ -33,7 +33,7 @@ jobs:
|
||||
|
||||
- name: Get old instance and snapshot name, create new instance name
|
||||
run: |
|
||||
echo "OLD_INSTANCE_SNAPSHOT_NAME=$(aws lightsail get-instance-snapshots | grep '"name": "CasaOS-Demo-Snapshot-[0-9]' | sed 's/ //g' | sed 's/"//g' | sed 's/,//g' | sed 's/name://g')" >> $GITHUB_ENV
|
||||
echo "OLD_INSTANCE_SNAPSHOT_NAME=$(aws lightsail get-instance-snapshots | grep '"name": "CasaOS-Demo-Snapshot-1652856810' | sed 's/ //g' | sed 's/"//g' | sed 's/,//g' | sed 's/name://g')" >> $GITHUB_ENV
|
||||
echo "OLD_INSTANCE_NAME=$(aws lightsail get-instances | grep '"name": "CasaOS-Demo-[0-9]' | sed 's/ //g' | sed 's/"//g' | sed 's/,//g' | sed 's/name://g')" >> $GITHUB_ENV
|
||||
echo "NEW_INSTANCE_NAME=CasaOS-Demo-$(date +%s)" >> $GITHUB_ENV
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
--instance-snapshot-name ${{ env.OLD_INSTANCE_SNAPSHOT_NAME }} \
|
||||
--instance-names ${{ env.NEW_INSTANCE_NAME }} \
|
||||
--availability-zone us-west-2a \
|
||||
--bundle-id large_2_0
|
||||
--bundle-id medium_2_0
|
||||
|
||||
- name: Wait for new instance running
|
||||
run: |
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -29,7 +29,9 @@ gen
|
||||
/out/
|
||||
/db/
|
||||
/docs/
|
||||
/web/
|
||||
/conf/conf.ini
|
||||
/conf/conf.json
|
||||
__debug_bin
|
||||
main
|
||||
CasaOS
|
||||
|
||||
78
CHANGELOG.md
78
CHANGELOG.md
@@ -11,12 +11,90 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
### Removed
|
||||
|
||||
### Security
|
||||
|
||||
### Fixed
|
||||
|
||||
## [0.3.3-pre] - 2022-07-01(UTC)
|
||||
|
||||
### Added
|
||||
|
||||
- [System]Add interface call log
|
||||
- Adding Developing file ([#311](https://github.com/IceWhaleTech/CasaOS/pull/311))
|
||||
- [App] add new tips for app section.
|
||||
- [System] UI Configurable function modules: support turning off the search bar and recommended apps module in the settings.
|
||||
- [System] Custom wallpapers: two new preset wallpapers, support for custom uploads, support for setting images from Files as wallpapers, Also support right click on dashboard to change wallpaper.
|
||||
|
||||
### Changed
|
||||
|
||||
- [App] Cache app store index and category data
|
||||
- [System] casaos master program adapted to FHS standards
|
||||
- [App] Update casaos icons.
|
||||
- [System] Update translation.
|
||||
|
||||
### Removed
|
||||
|
||||
- [System] Remove upnp function module
|
||||
- [System] Remove ddns function module
|
||||
- [System] Remove search function module
|
||||
- [System] Remove zerotier function module
|
||||
- [System] Remove task function module
|
||||
- [System] Remove file share function module
|
||||
|
||||
### Fixed
|
||||
|
||||
- [Disk] Fixed hard drive won't hibernate problem ([#202](https://github.com/IceWhaleTech/CasaOS/issues/202))
|
||||
- [File] Fixed the backspace key that causes the folder to rewind ([#252](https://github.com/IceWhaleTech/CasaOS/issues/252))
|
||||
- [App] Fixed app logo is not loading when imported. ([#320](https://github.com/IceWhaleTech/CasaOS/issues/320))
|
||||
|
||||
## [0.3.2.1] - 2022-06-16(UTC)
|
||||
|
||||
### Changed
|
||||
|
||||
- [System] Adjusted the display style.
|
||||
|
||||
### Fixed
|
||||
|
||||
- [System] Fixed the issue of widgets displaying wrongly on mobile devices.
|
||||
- [App] Fix the problem of application opening failure on non-80 ports ([#283](https://github.com/IceWhaleTech/CasaOS/issues/283) [#280](https://github.com/IceWhaleTech/CasaOS/issues/280))
|
||||
- [System] Modify port failure problem ([#282](https://github.com/IceWhaleTech/CasaOS/issues/282))
|
||||
- [App]Modify environment variables disappearing problem([#284](https://github.com/IceWhaleTech/CasaOS/issues/284))
|
||||
- [System]Fix no update alert([#278](https://github.com/IceWhaleTech/CasaOS/issues/278))
|
||||
- [System] Fixed some bugs of application cpu usage and memory staging([#272](https://github.com/IceWhaleTech/CasaOS/issues/272))
|
||||
- [App] Fixed plex and HA network mode error issues ([#299](https://github.com/IceWhaleTech/CasaOS/issues/299))
|
||||
- [App] Fix application terminal not working ([#266](https://github.com/IceWhaleTech/CasaOS/issues/266))
|
||||
|
||||
## [0.3.2] - 2022-06-10
|
||||
|
||||
### Added
|
||||
|
||||
- [Files] Files can now be selected multiple files and downloaded, deleted, moved, etc.
|
||||
- [Apps] Support to modify the application opening address.([#204](https://github.com/IceWhaleTech/CasaOS/issues/204))
|
||||
|
||||
### Changed
|
||||
|
||||
- [Apps] Hide the display of non-essential environment variables in the application.([#196](https://github.com/IceWhaleTech/CasaOS/issues/196))
|
||||
- [System] Network, disk, cpu, memory, etc. information is modified to be pushed via socket.
|
||||
- [System] Optimize opening speed.([#214](https://github.com/IceWhaleTech/CasaOS/issues/214))
|
||||
- [Language] Update language pack [zarevskaya](https://github.com/zarevskaya) [patrickhilker](https://github.com/patrickhilker)
|
||||
- [System] Interface path adjustment
|
||||
|
||||
### Removed
|
||||
|
||||
- [Files] Remove the online preview function of PDF files
|
||||
|
||||
### Fixed
|
||||
|
||||
- [System] Fixed the problem that sync data cannot submit the device ID ([#68](https://github.com/IceWhaleTech/CasaOS/issues/68))
|
||||
- [Files] Fixed the code editor center alignment display problem.([#210](https://github.com/IceWhaleTech/CasaOS/issues/210))
|
||||
- [Files] Fixed the problem of wrong name when downloading files.([#240](https://github.com/IceWhaleTech/CasaOS/issues/240))
|
||||
- [System] Fixed the network display as a negative number problem.([#224](https://github.com/IceWhaleTech/CasaOS/issues/224))
|
||||
- [System] Fixed the problem of wireless network card traffic display.([#222](https://github.com/IceWhaleTech/CasaOS/issues/222))
|
||||
|
||||
|
||||
## [0.3.1.1] - 2022-05-17
|
||||
|
||||
### Fixed
|
||||
|
||||
33
DEVELOPING.md
Normal file
33
DEVELOPING.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# CasaOS Development
|
||||
Here we will describe the steps required to setup a development environment with CasaOS.
|
||||
|
||||
- [Setting up development environment](#setting-up-development-environment)
|
||||
- [Pre-requisites](#pre-requisites)
|
||||
- [1. Fork the Repo](#1.-fork-the-repo)
|
||||
- [2. Clone the repo down](#2.-clone-the-repo-down)
|
||||
- [3. Install dependencies](#3.-install-dependencies)
|
||||
|
||||
|
||||
## Setting up a development environment
|
||||
In this section we will walk you through the general process of setting up your development environment to get started.
|
||||
|
||||
### Pre-requisites
|
||||
The following must be installed in order to get started. The details of how to install them is outside the scope of this doc, but generally they should be able to be installed with your systems package manager (apt, yum, brew, choco, etc).
|
||||
- Go > v1.17.0
|
||||
- yarn
|
||||
- node.js
|
||||
|
||||
### 1. Fork the Repo
|
||||
[Fork the repo](https://docs.github.com/en/get-started/quickstart/fork-a-repo) onto your own GitHub account for developing.
|
||||
|
||||
### 2. Clone the repo down
|
||||
1. Navigate into your go workspace (check with `go env GOPATH`).
|
||||
2. Navigate to the appropriate path for github. It should look something like this: `<path from GOPATH>/github.com/<GitHub Username>/`. If it doesn't exist create it.
|
||||
3. Clone down the repo with the following: `git clone --recurse-submodules --remote-submodules https://github.com/<your GitHub Username>/CasaOS.git`
|
||||
|
||||
### 3. Install dependencies
|
||||
1. `cd UI`
|
||||
2. `yarn install`
|
||||
3. `yarn build`
|
||||
4. `cd ..`
|
||||
5. `go get`
|
||||
2
UI
2
UI
Submodule UI updated: 70d9529d06...7af1bf549d
41
alpha.md
Normal file
41
alpha.md
Normal file
@@ -0,0 +1,41 @@
|
||||
<!--
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-06-27 11:37:26
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-30 14:16:31
|
||||
* @FilePath: /CasaOS/alpha.md
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
-->
|
||||
|
||||
# alpha Test Description
|
||||
|
||||
## :warning: Warning
|
||||
|
||||
There is a risk of data loss in non-release versions, so please be careful to back up your data.
|
||||
|
||||
## Install/Update
|
||||
|
||||
``` curl -fsSL https://get.casaos.io | bash -v v0.3.3-alpha ```
|
||||
|
||||
## Check change log
|
||||
|
||||
[CHANGELOG](https://github.com/IceWhaleTech/CasaOS/blob/main/CHANGELOG.md)
|
||||
|
||||
## Check Design drawings
|
||||
|
||||
[Design drawings](https://www.figma.com/file/pvlGobvuWEvbCb3GLqXfim/CasaOS-V0.3.3)
|
||||
|
||||
## Feedback questions
|
||||
|
||||
Go [here]() to give feedback on your question, note that try to match the picture or video
|
||||
|
||||
|
||||
## Retest after update
|
||||
|
||||
Wait for the fix to appear and update and retest, and follow up on the issue
|
||||
|
||||
## Thanks
|
||||
|
||||
Thank you for your great support, we will return your support from time to time.
|
||||
40
conf/conf.conf
Normal file
40
conf/conf.conf
Normal file
@@ -0,0 +1,40 @@
|
||||
[app]
|
||||
PAGE_SIZE = 10
|
||||
RuntimeRootPath = runtime/
|
||||
LogPath = ./CasaOS/logs/server/
|
||||
LogSaveName = log
|
||||
LogFileExt = log
|
||||
DateStrFormat = 20060102
|
||||
DateTimeFormat = 2006-01-02 15:04:05
|
||||
TimeFormat = 15:04:05
|
||||
DateFormat = 2006-01-02
|
||||
DBPath = ./CasaOS/server/db
|
||||
ShellPath = ./CasaOS/server/shell
|
||||
UserDataPath = ./CasaOS/conf
|
||||
TempPath = ./CasaOS/temp
|
||||
|
||||
[server]
|
||||
HttpPort = 8089
|
||||
UDPPort = 54216
|
||||
RunMode = release
|
||||
;ServerApi = https://api.casaos.io/casaos-api
|
||||
ServerApi = http://127.0.0.1:8091
|
||||
Handshake = socket.casaos.io
|
||||
Token = af268e4f-9f3a-408a-b59b-cf1a4f7f88c8
|
||||
USBAutoMount =
|
||||
SocketPort = 58313
|
||||
|
||||
[system]
|
||||
ConfigStr = {"auto_update":false,"background":"","background_type":"","search_engine":"https://duckduckgo.com/?q=","search_switch":false,"shortcuts_switch":false,"widgets_switch":false,"lang":"en_us"}
|
||||
WidgetList = [{"name":"clock","show":true},{"name":"cpu","show":true},{"name":"disks","show":true},{"name":"network","show":true}]
|
||||
|
||||
[file]
|
||||
ShareDir =
|
||||
DownloadDir = ./CasaOS/DATA/Downloads
|
||||
|
||||
[user]
|
||||
Description = nothing
|
||||
UserName = casaos
|
||||
Initialized = true
|
||||
PWD = 123456
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
[app]
|
||||
PAGE_SIZE = 10
|
||||
RuntimeRootPath = runtime/
|
||||
LogSavePath = /casaOS/logs/server/
|
||||
LogPath = /var/log/casaos/
|
||||
LogSaveName = log
|
||||
LogFileExt = log
|
||||
DateStrFormat = 20060102
|
||||
DateTimeFormat = 2006-01-02 15:04:05
|
||||
TimeFormat = 15:04:05
|
||||
DateFormat = 2006-01-02
|
||||
ProjectPath = /casaOS/server
|
||||
RootPath = /casaOS
|
||||
|
||||
DBPath = /var/lib/casaos
|
||||
ShellPath = /usr/share/casaos/shell
|
||||
UserDataPath = /var/lib/casaos/conf
|
||||
TempPath = /var/lib/casaos/temp
|
||||
|
||||
[server]
|
||||
HttpPort = 8089
|
||||
HttpPort = 80
|
||||
UDPPort =
|
||||
RunMode = release
|
||||
ServerApi = https://api.casaos.io/casaos-api
|
||||
@@ -21,20 +22,9 @@ Handshake = socket.casaos.io
|
||||
Token =
|
||||
USBAutoMount =
|
||||
|
||||
[user]
|
||||
UserName =
|
||||
PWD =
|
||||
Email = user@gmail.com
|
||||
Description = description
|
||||
Initialized = false
|
||||
Avatar =
|
||||
NickName =
|
||||
PublicKey =
|
||||
|
||||
[system]
|
||||
ConfigStr =
|
||||
WidgetList =
|
||||
Analyse =
|
||||
|
||||
|
||||
[file]
|
||||
10
go.mod
10
go.mod
@@ -7,6 +7,9 @@ require (
|
||||
github.com/Microsoft/go-winio v0.5.0 // indirect
|
||||
github.com/Microsoft/hcsshim v0.8.22 // indirect
|
||||
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 // indirect
|
||||
github.com/ambelovsky/go-structs v1.1.0 // indirect
|
||||
github.com/ambelovsky/gosf v0.0.0-20201109201340-237aea4d6109
|
||||
github.com/ambelovsky/gosf-socketio v0.0.0-20201109193639-add9d32f8b19 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.2.1 // indirect
|
||||
github.com/containerd/containerd v1.5.7
|
||||
github.com/containerd/continuity v0.2.0 // indirect
|
||||
@@ -24,11 +27,12 @@ require (
|
||||
github.com/go-openapi/spec v0.20.4 // indirect
|
||||
github.com/go-playground/validator/v10 v10.6.1 // indirect
|
||||
github.com/gogo/googleapis v1.4.1 // indirect
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/golang-jwt/jwt/v4 v4.4.1
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/gomodule/redigo v1.8.5
|
||||
github.com/google/go-github/v36 v36.0.0
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/googollee/go-socket.io v1.6.2
|
||||
github.com/gorilla/mux v1.8.0 // indirect
|
||||
github.com/gorilla/websocket v1.4.2
|
||||
github.com/jinzhu/copier v0.3.2
|
||||
@@ -39,6 +43,7 @@ require (
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/mattn/go-isatty v0.0.14 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.11 // indirect
|
||||
github.com/mholt/archiver/v3 v3.5.1
|
||||
github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect
|
||||
github.com/morikuni/aec v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.0.2 // indirect
|
||||
@@ -53,13 +58,13 @@ require (
|
||||
github.com/sirupsen/logrus v1.8.1
|
||||
github.com/smartystreets/assertions v1.2.0 // indirect
|
||||
github.com/smartystreets/goconvey v1.6.4 // indirect
|
||||
github.com/spf13/afero v1.2.2
|
||||
github.com/swaggo/gin-swagger v1.3.0
|
||||
github.com/swaggo/swag v1.7.3
|
||||
github.com/tidwall/gjson v1.10.2
|
||||
github.com/tklauser/go-sysconf v0.3.6 // indirect
|
||||
github.com/ugorji/go v1.2.6 // indirect
|
||||
go.opencensus.io v0.23.0 // indirect
|
||||
go.uber.org/zap v1.10.0
|
||||
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
|
||||
golang.org/x/mod v0.5.0 // indirect
|
||||
golang.org/x/net v0.0.0-20211020060615-d418f374d309 // indirect
|
||||
@@ -73,6 +78,7 @@ require (
|
||||
google.golang.org/grpc v1.41.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
gopkg.in/ini.v1 v1.62.0 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
|
||||
gorm.io/driver/sqlite v1.2.6
|
||||
gorm.io/gorm v1.22.5
|
||||
|
||||
44
go.sum
44
go.sum
@@ -54,6 +54,7 @@ github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935
|
||||
github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k=
|
||||
github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8=
|
||||
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
|
||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d h1:62lEBImTxZ83pgzywgDNIrPPuQ+j4ep9QjqrWBn1hrU=
|
||||
@@ -99,6 +100,14 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy
|
||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0=
|
||||
github.com/ambelovsky/go-structs v1.1.0 h1:LXj4/mHnYw0qhXQhOo96+ULGQ88H8qMcZd5SHef8boY=
|
||||
github.com/ambelovsky/go-structs v1.1.0/go.mod h1:zN3RBXQvxgjjq/Q/WZS7p5AEK+qC9mNg7ycnvoQ63Ak=
|
||||
github.com/ambelovsky/gosf v0.0.0-20201109201340-237aea4d6109 h1:Tp8GVfUOEmJftBqi4+/aXTwJzm24POo6wIHeuTqaT+Y=
|
||||
github.com/ambelovsky/gosf v0.0.0-20201109201340-237aea4d6109/go.mod h1:MUREokfMKREm1fOm2babarrkYdk/dGHWY+ITC3qHHPQ=
|
||||
github.com/ambelovsky/gosf-socketio v0.0.0-20201109193639-add9d32f8b19 h1:suVCm9PiIhz7ftTbWQNe7u2YjVfr8AEuUiNWKWApdMM=
|
||||
github.com/ambelovsky/gosf-socketio v0.0.0-20201109193639-add9d32f8b19/go.mod h1:o0+8DH+3X+FEOgSdNud0+8jJAsjtR9H3hF+O10Zcj/c=
|
||||
github.com/andybalholm/brotli v1.0.1 h1:KqhlKozYbRtJvsPrrEeXcO+N2l6NYT5A2QAFmSULpEc=
|
||||
github.com/andybalholm/brotli v1.0.1/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
|
||||
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
|
||||
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
|
||||
@@ -289,6 +298,9 @@ github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDD
|
||||
github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1/go.mod h1:cyGadeNEkKy96OOhEzfZl+yxihPEzKnqJwvfuSUqbZE=
|
||||
github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM=
|
||||
github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE=
|
||||
github.com/dsnet/compress v0.0.2-0.20210315054119-f66993602bf5 h1:iFaUwBSo5Svw6L7HYpRu/0lE3e0BaElwnNO1qkNQxBY=
|
||||
github.com/dsnet/compress v0.0.2-0.20210315054119-f66993602bf5/go.mod h1:qssHWj60/X5sZFNxpG4HBPDHVqxNm4DfnCKgrbZOT+s=
|
||||
github.com/dsnet/golib v0.0.0-20171103203638-1ea166775780/go.mod h1:Lj+Z9rebOhdfkVLjJ8T6VcRQv3SXugXy999NBtR9aFY=
|
||||
github.com/dsoprea/go-exif/v2 v2.0.0-20200321225314-640175a69fe4/go.mod h1:Lm2lMM2zx8p4a34ZemkaUV95AnMl4ZvLbCUbwOvLC2E=
|
||||
github.com/dsoprea/go-exif/v3 v3.0.0-20200717053412-08f1b6708903/go.mod h1:0nsO1ce0mh5czxGeLo4+OCZ/C6Eo6ZlMWsz7rH/Gxv8=
|
||||
github.com/dsoprea/go-exif/v3 v3.0.0-20210625224831-a6301f85c82b h1:NgNuLvW/gAFKU30ULWW0gtkCt56JfB7FrZ2zyo0wT8I=
|
||||
@@ -401,6 +413,7 @@ github.com/godbus/dbus v0.0.0-20180201030542-885f9cc04c9c/go.mod h1:/YcGZj5zSblf
|
||||
github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4=
|
||||
github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw=
|
||||
github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/gogo/googleapis v1.2.0/go.mod h1:Njal3psf3qN6dwBtQfUmBZh2ybovJ0tlu3o/AC7HYjU=
|
||||
github.com/gogo/googleapis v1.4.0/go.mod h1:5YRNX2z1oM5gXdAkurHa942MDgEJyk02w4OecKY87+c=
|
||||
@@ -413,8 +426,8 @@ github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXP
|
||||
github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang-jwt/jwt/v4 v4.4.1 h1:pC5DB52sCeK48Wlb9oPcdhnjkz1TKt1D/P7WKJ0kUcQ=
|
||||
github.com/golang-jwt/jwt/v4 v4.4.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/golang/geo v0.0.0-20190916061304-5b978397cfec/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
|
||||
github.com/golang/geo v0.0.0-20200319012246-673a6f80352d h1:C/hKUcHT483btRbeGkrRjJz+Zbcj8audldIi9tRJDCc=
|
||||
github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
|
||||
@@ -453,6 +466,9 @@ github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw=
|
||||
github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/gomodule/redigo v1.8.4/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
|
||||
github.com/gomodule/redigo v1.8.5 h1:nRAxCa+SVsyjSBrtZmG/cqb6VbTmuRzpg/PoTFlpumc=
|
||||
github.com/gomodule/redigo v1.8.5/go.mod h1:P9dn9mFrCBvWhGE1wpxx6fgq7BAeLBk+UUUzlpkBYO0=
|
||||
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
@@ -499,6 +515,8 @@ github.com/googleapis/gax-go/v2 v2.0.3/go.mod h1:LLvjysVCY1JZeum8Z6l8qUty8fiNwE0
|
||||
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
|
||||
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
|
||||
github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg=
|
||||
github.com/googollee/go-socket.io v1.6.2 h1:olKLLHJtHz1IkL/OrTyNriZZvVQYEORNkJAqsOwPask=
|
||||
github.com/googollee/go-socket.io v1.6.2/go.mod h1:0vGP8/dXR9SZUMMD4+xxaGo/lohOw3YWMh2WRiWeKxg=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gorilla/handlers v0.0.0-20150720190736-60c7bfde3e33/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=
|
||||
@@ -563,10 +581,15 @@ github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvW
|
||||
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.4.1/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
|
||||
github.com/klauspost/compress v1.11.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
|
||||
github.com/klauspost/compress v1.11.4/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
|
||||
github.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs=
|
||||
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/cpuid v1.2.0/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek=
|
||||
github.com/klauspost/pgzip v1.2.5 h1:qnWYvvKqedOF2ulHpMG72XQol4ILEJ8k2wwRl/Km8oE=
|
||||
github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
@@ -619,10 +642,13 @@ github.com/mattn/go-sqlite3 v1.14.11 h1:gt+cp9c0XGqe9S/wAHTL3n/7MqY+siPWgWJgqdsF
|
||||
github.com/mattn/go-sqlite3 v1.14.11/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
|
||||
github.com/mholt/archiver/v3 v3.5.1 h1:rDjOBX9JSF5BvoJGvjqK479aL70qh9DIpZCl+k7Clwo=
|
||||
github.com/mholt/archiver/v3 v3.5.1/go.mod h1:e3dqJ7H78uzsRSEACH1joayhuSyhnonssnDhppzS1L4=
|
||||
github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=
|
||||
github.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=
|
||||
github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
|
||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
github.com/mitchellh/osext v0.0.0-20151018003038-5e2d6d41470f/go.mod h1:OkQIRizQZAeMln+1tSwduZz7+Af5oFlKirV/MSYes2A=
|
||||
github.com/moby/locker v1.0.1 h1:fOXqR41zeveg4fFODix+1Ch4mj/gT0NE1XJbp/epuBg=
|
||||
@@ -651,6 +677,8 @@ github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/
|
||||
github.com/neelance/astrewrite v0.0.0-20160511093645-99348263ae86/go.mod h1:kHJEU3ofeGjhHklVoIGuVj85JJwZ6kWPaJwCIxgnFmo=
|
||||
github.com/neelance/sourcemap v0.0.0-20151028013722-8c68805598ab/go.mod h1:Qr6/a/Q4r9LP1IltGz7tA7iOK1WonHEYhu1HRBA7ZiM=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/nwaples/rardecode v1.1.0 h1:vSxaY8vQhOcVr4mm5e8XllHWTiM4JF507A0Katqw7MQ=
|
||||
github.com/nwaples/rardecode v1.1.0/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0=
|
||||
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
|
||||
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
|
||||
@@ -711,6 +739,8 @@ github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTK
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc=
|
||||
github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=
|
||||
github.com/pierrec/lz4/v4 v4.1.2 h1:qvY3YFXRQE/XB8MlLzJH7mSzBs74eA2gg52YTk6jUPM=
|
||||
github.com/pierrec/lz4/v4 v4.1.2/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
@@ -813,7 +843,6 @@ github.com/sourcegraph/annotate v0.0.0-20160123013949-f4cad6c6324d/go.mod h1:Udh
|
||||
github.com/sourcegraph/syntaxhighlight v0.0.0-20170531221838-bd320f5d308e/go.mod h1:HuIsMU8RRBOtsCgI77wP899iHVBQpCmg4ErYMZB+2IA=
|
||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
|
||||
github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc=
|
||||
github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk=
|
||||
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
@@ -875,6 +904,9 @@ github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLY
|
||||
github.com/ugorji/go/codec v1.1.13/go.mod h1:oNVt3Dq+FO91WNQ/9JnHKQP2QJxTzoN7wCBFCq1OeuU=
|
||||
github.com/ugorji/go/codec v1.2.6 h1:7kbGefxLoDBuYXOms4yD7223OpNMMPNPZxXk5TvFcyQ=
|
||||
github.com/ugorji/go/codec v1.2.6/go.mod h1:V6TCNZ4PHqoHGFZuSG1W8nrCzzdgA2DozYxWFFpvxTw=
|
||||
github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/ulikunitz/xz v0.5.9 h1:RsKRIA2MO8x56wkkcd3LbtcE/uMszhb6DpRf+3uwa3I=
|
||||
github.com/ulikunitz/xz v0.5.9/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
|
||||
github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
|
||||
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
|
||||
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
@@ -893,6 +925,8 @@ github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
|
||||
github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
|
||||
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
|
||||
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
|
||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
|
||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
@@ -919,8 +953,11 @@ go.opencensus.io v0.23.0 h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M=
|
||||
go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E=
|
||||
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
|
||||
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU=
|
||||
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/multierr v1.1.0 h1:HoEmRHQPVSqub6w2z2d2EOVs2fjyFRGyofhKuyDq0QI=
|
||||
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
||||
go.uber.org/zap v1.10.0 h1:ORx85nbTijNz8ljznvCMR1ZBIPKFn3jQrag10X2AsuM=
|
||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE=
|
||||
golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw=
|
||||
@@ -1350,6 +1387,7 @@ gopkg.in/go-playground/validator.v8 v8.18.2/go.mod h1:RX2a/7Ha8BgOhfk7j780h4/u/R
|
||||
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
|
||||
gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU=
|
||||
gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
|
||||
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
||||
gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI=
|
||||
|
||||
74
main.go
74
main.go
@@ -6,14 +6,15 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model/notify"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/cache"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/sqlite"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"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"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
|
||||
"github.com/robfig/cron"
|
||||
"gorm.io/gorm"
|
||||
@@ -24,23 +25,23 @@ var sqliteDB *gorm.DB
|
||||
var configFlag = flag.String("c", "", "config address")
|
||||
var dbFlag = flag.String("db", "", "db path")
|
||||
var showUserInfo = flag.Bool("show-user-info", false, "show user info")
|
||||
var resetUser = flag.Bool("ru", false, "reset user")
|
||||
var user = flag.String("user", "", "user name")
|
||||
|
||||
func init() {
|
||||
flag.Parse()
|
||||
config.InitSetup(*configFlag)
|
||||
config.UpdateSetup()
|
||||
loger2.LogSetup()
|
||||
loger.LogInit()
|
||||
if len(*dbFlag) == 0 {
|
||||
*dbFlag = config.AppInfo.ProjectPath + "/db"
|
||||
*dbFlag = config.AppInfo.DBPath + "/db"
|
||||
}
|
||||
sqliteDB = sqlite.GetDb(*dbFlag)
|
||||
//gredis.GetRedisConn(config.RedisInfo),
|
||||
service.MyService = service.NewService(sqliteDB, loger2.NewOLoger())
|
||||
service.MyService = service.NewService(sqliteDB)
|
||||
service.Cache = cache.Init()
|
||||
|
||||
go service.UDPService()
|
||||
|
||||
fmt.Println("token", service.GetToken())
|
||||
service.GetToken()
|
||||
service.UDPAddressMap = make(map[string]string)
|
||||
//go service.SocketConnect()
|
||||
service.CancelList = make(map[string]string)
|
||||
@@ -48,7 +49,6 @@ func init() {
|
||||
service.NewVersionApp = make(map[string]string)
|
||||
route.InitFunction()
|
||||
|
||||
go service.SendIPToServer()
|
||||
// go service.LoopFriend()
|
||||
// go service.MyService.App().CheckNewImage()
|
||||
|
||||
@@ -66,12 +66,45 @@ func init() {
|
||||
// @name Authorization
|
||||
// @BasePath /v1
|
||||
func main() {
|
||||
service.NotifyMsg = make(chan notify.Message, 10)
|
||||
if *showUserInfo {
|
||||
fmt.Println("CasaOS User Info")
|
||||
fmt.Println("UserName:" + config.UserInfo.UserName)
|
||||
fmt.Println("Password:" + config.UserInfo.PWD)
|
||||
return
|
||||
}
|
||||
fmt.Println("Reset User", *resetUser)
|
||||
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 func() {
|
||||
service.UDPService()
|
||||
service.SendIPToServer()
|
||||
}()
|
||||
go route.SocketInit(service.NotifyMsg)
|
||||
go func() {
|
||||
for i := 0; i < 1000; i++ {
|
||||
time.Sleep(2 * time.Second)
|
||||
//service.NotifyMsg <- strconv.Itoa(i)
|
||||
}
|
||||
}()
|
||||
|
||||
//model.Setup()
|
||||
//gredis.Setup()
|
||||
r := route.InitRouter()
|
||||
@@ -86,18 +119,20 @@ func main() {
|
||||
service.SendIPToServer()
|
||||
|
||||
service.LoopFriend()
|
||||
service.MyService.App().CheckNewImage()
|
||||
//service.MyService.App().CheckNewImage()
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
err = cron2.AddFunc("0/1 * * * * *", func() {
|
||||
notify := model2.AppNotify{}
|
||||
notify.CustomId = ""
|
||||
notify.Type = types.NOTIFY_TYPE_HEALTH_CHECK
|
||||
|
||||
go service.MyService.Notify().SendText(notify)
|
||||
|
||||
err = cron2.AddFunc("0/5 * * * * *", func() {
|
||||
if service.ClientCount > 0 {
|
||||
//route.SendNetINfoBySocket()
|
||||
//route.SendCPUBySocket()
|
||||
//route.SendMemBySocket()
|
||||
// route.SendDiskBySocket()
|
||||
//route.SendUSBBySocket()
|
||||
route.SendAllHardwareStatusBySocket()
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
@@ -114,4 +149,7 @@ func main() {
|
||||
|
||||
s.ListenAndServe()
|
||||
|
||||
// if err := r.Run(fmt.Sprintf(":%v", config.ServerInfo.HttpPort)); err != nil {
|
||||
// fmt.Println("failed run app: ", err)
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -1,29 +1,37 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2021-10-08 10:29:08
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-21 15:10:03
|
||||
* @FilePath: /CasaOS/middleware/gin.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func Cors() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
method := c.Request.Method
|
||||
//origin := c.Request.Header.Get("Origin") //请求头部
|
||||
//if origin != "" {
|
||||
//接收客户端发送的origin (重要!)
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
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-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")
|
||||
//允许客户端传递校验信息比如 cookie (重要)
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
c.Set("content-type", "application/json")
|
||||
//}
|
||||
@@ -42,3 +50,9 @@ func Cors() gin.HandlerFunc {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
func WriteLog() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
loger.Info("request:", zap.Any("path", c.Request.URL.String()), zap.Any("param", c.Params), zap.Any("query", c.Request.URL.Query()), zap.Any("body", c.Request.Body), zap.Any("method", c.Request.Method))
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,13 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type ServerAppListCollection struct {
|
||||
List []ServerAppList `json:"list"`
|
||||
Recommend []ServerAppList `json:"recommend"`
|
||||
Community []ServerAppList `json:"community"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type ServerAppList struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
Title string `json:"title"`
|
||||
@@ -15,6 +22,7 @@ type ServerAppList struct {
|
||||
Icon string `json:"icon"`
|
||||
ScreenshotLink Strings `gorm:"type:json" json:"screenshot_link"`
|
||||
Category string `json:"category"`
|
||||
CategoryId int `json:"category_id"`
|
||||
CategoryFont string `json:"category_font"`
|
||||
PortMap string `json:"port_map"`
|
||||
ImageVersion string `json:"image_version"`
|
||||
@@ -38,6 +46,7 @@ type ServerAppList struct {
|
||||
Plugins Strings `json:"plugins"`
|
||||
Origin string `json:"origin"`
|
||||
Type int `json:"type"`
|
||||
QueryCount int `json:"query_count"`
|
||||
Developer string `json:"developer"`
|
||||
HostName string `json:"host_name"`
|
||||
Privileged bool `json:"privileged"`
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
/*
|
||||
* @Author: link a624669980@163.com
|
||||
* @Date: 2022-05-16 17:37:08
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-22 17:45:53
|
||||
* @FilePath: /CasaOS/model/category.go
|
||||
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
|
||||
|
||||
*/
|
||||
package model
|
||||
|
||||
type ServerCategoryList struct {
|
||||
Version string `json:"version"`
|
||||
Item []CategoryList `json:"item"`
|
||||
}
|
||||
type CategoryList struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
//CreatedAt time.Time `json:"created_at"`
|
||||
//
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2021-12-08 18:10:25
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-14 17:20:36
|
||||
* @FilePath: /CasaOS/model/docker.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package model
|
||||
|
||||
type DockerStatsModel struct {
|
||||
|
||||
33
model/file.go
Normal file
33
model/file.go
Normal file
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-20 16:27:12
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-09 18:18:46
|
||||
* @FilePath: /CasaOS/model/file.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package model
|
||||
|
||||
type FileOperate struct {
|
||||
Type string `json:"type" binding:"required"`
|
||||
Item []FileItem `json:"item" binding:"required"`
|
||||
TotalSize int64 `json:"total_size"`
|
||||
ProcessedSize int64 `json:"processed_size"`
|
||||
To string `json:"to" binding:"required"`
|
||||
Style string `json:"style"`
|
||||
Finished bool `json:"finished"`
|
||||
}
|
||||
|
||||
type FileItem struct {
|
||||
From string `json:"from" binding:"required"`
|
||||
Finished bool `json:"finished"`
|
||||
Size int64 `json:"size"`
|
||||
ProcessedSize int64 `json:"processed_size"`
|
||||
}
|
||||
|
||||
type FileUpdate struct {
|
||||
FilePath string `json:"path" binding:"required"`
|
||||
FileContent string `json:"content" binding:"required"`
|
||||
}
|
||||
@@ -127,4 +127,6 @@ type CustomizationPostData struct {
|
||||
Privileged bool `json:"privileged"`
|
||||
CapAdd []string `json:"cap_add"`
|
||||
Cmd []string `json:"cmd"`
|
||||
Protocol string `json:"protocol"`
|
||||
Host string `json:"host"`
|
||||
}
|
||||
|
||||
21
model/notify/application.go
Normal file
21
model/notify/application.go
Normal file
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-27 15:01:58
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-05-31 14:51:21
|
||||
* @FilePath: /CasaOS/model/notify/application.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package notify
|
||||
|
||||
type Application struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
Type string `json:"type"`
|
||||
Icon string `json:"icon"`
|
||||
Message string `json:"message"`
|
||||
Finished bool `json:"finished"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
22
model/notify/file.go
Normal file
22
model/notify/file.go
Normal file
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-26 14:21:57
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-02 11:14:15
|
||||
* @FilePath: /CasaOS/model/notify/file.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package notify
|
||||
|
||||
type File struct {
|
||||
Finished bool `json:"finished"`
|
||||
ProcessedSize int64 `json:"processed_size"`
|
||||
ProcessingPath string `json:"processing_path"`
|
||||
Status string `json:"status"`
|
||||
TotalSize int64 `json:"total_size"`
|
||||
Id string `json:"id"`
|
||||
To string `json:"to"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
20
model/notify/message.go
Normal file
20
model/notify/message.go
Normal file
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-26 14:39:22
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-05-26 19:08:52
|
||||
* @FilePath: /CasaOS/model/notify/message.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package notify
|
||||
|
||||
import (
|
||||
f "github.com/ambelovsky/gosf"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Path string `json:"path"`
|
||||
Msg f.Message `json:"msg"`
|
||||
}
|
||||
16
model/notify/person.go
Normal file
16
model/notify/person.go
Normal file
@@ -0,0 +1,16 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-27 18:42:42
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-05-27 18:43:08
|
||||
* @FilePath: /CasaOS/model/notify/person.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package notify
|
||||
|
||||
type Person struct {
|
||||
ShareId string `json:"share_id"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
18
model/notify/result.go
Normal file
18
model/notify/result.go
Normal file
@@ -0,0 +1,18 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-26 14:21:11
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-05-27 11:15:59
|
||||
* @FilePath: /CasaOS/model/notify/result.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
|
||||
package notify
|
||||
|
||||
// Notify struct for Notify
|
||||
type NotifyModel struct {
|
||||
Data interface{} `json:"data"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-13 18:15:46
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-16 17:50:56
|
||||
* @FilePath: /CasaOS/model/sys_common.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package model
|
||||
|
||||
import "time"
|
||||
@@ -31,19 +41,22 @@ type ServerModel struct {
|
||||
Token string
|
||||
UDPPort string
|
||||
USBAutoMount string
|
||||
SocketPort string
|
||||
}
|
||||
|
||||
//服务配置
|
||||
type APPModel struct {
|
||||
LogSavePath string
|
||||
LogPath string
|
||||
LogSaveName string
|
||||
LogFileExt string
|
||||
DateStrFormat string
|
||||
DateTimeFormat string
|
||||
UserDataPath string
|
||||
TimeFormat string
|
||||
DateFormat string
|
||||
ProjectPath string
|
||||
RootPath string
|
||||
DBPath string
|
||||
ShellPath string
|
||||
TempPath string
|
||||
}
|
||||
|
||||
//公共返回模型
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
package model
|
||||
17
model/system_model/verify_information.go
Normal file
17
model/system_model/verify_information.go
Normal file
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-06-15 11:30:47
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-23 18:40:40
|
||||
* @FilePath: /CasaOS/model/system_model/verify_information.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package system_model
|
||||
|
||||
type VerifyInformation struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
@@ -1,5 +1,15 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2021-09-30 18:18:14
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-21 11:09:30
|
||||
* @FilePath: /CasaOS/pkg/config/config.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package config
|
||||
|
||||
const (
|
||||
USERCONFIGURL = "conf/conf.ini"
|
||||
USERCONFIGURL = "/etc/casaos.conf"
|
||||
)
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-13 18:15:46
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-21 16:01:26
|
||||
* @FilePath: /CasaOS/pkg/config/init.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package config
|
||||
|
||||
import (
|
||||
@@ -42,6 +52,9 @@ func InitSetup(config string) {
|
||||
if len(config) > 0 {
|
||||
configDir = config
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
configDir = "./conf/conf.conf"
|
||||
}
|
||||
var err error
|
||||
//读取文件
|
||||
Cfg, err = ini.Load(configDir)
|
||||
@@ -57,6 +70,26 @@ func InitSetup(config string) {
|
||||
mapTo("system", SystemConfigInfo)
|
||||
mapTo("file", FileSettingInfo)
|
||||
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)
|
||||
}
|
||||
// AppInfo.ProjectPath = getCurrentDirectory() //os.Getwd()
|
||||
|
||||
}
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-13 18:15:46
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-22 18:50:44
|
||||
* @FilePath: /CasaOS/pkg/sqlite/db.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -16,7 +27,7 @@ func GetDb(dbPath string) *gorm.DB {
|
||||
if gdb != nil {
|
||||
return gdb
|
||||
}
|
||||
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
|
||||
// Refer https://github.com/go-sql-driver/mysql#dsn-data-source-name
|
||||
//dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", m.User, m.PWD, m.IP, m.Port, m.DBName)
|
||||
//db, err := gorm.Open(mysql2.Open(dsn), &gorm.Config{})
|
||||
file.IsNotExistMkDir(dbPath)
|
||||
@@ -26,14 +37,15 @@ func GetDb(dbPath string) *gorm.DB {
|
||||
c.SetMaxOpenConns(100)
|
||||
c.SetConnMaxIdleTime(time.Second * 1000)
|
||||
if err != nil {
|
||||
fmt.Println("连接数据失败!")
|
||||
panic("数据库连接失败")
|
||||
loger.Error("sqlite connect error", zap.Any("db connect error", err))
|
||||
panic("sqlite connect error")
|
||||
return nil
|
||||
}
|
||||
gdb = db
|
||||
err = db.AutoMigrate(&model2.TaskDBModel{}, &model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.PersonDownloadDBModel{}, model2.FriendModel{}, model2.PersonDownRecordDBModel{}, model2.ApplicationModel{})
|
||||
err = db.AutoMigrate(&model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.PersonDownloadDBModel{}, model2.FriendModel{}, model2.PersonDownRecordDBModel{}, model2.UserDBModel{})
|
||||
db.Exec("DROP TABLE IF EXISTS o_application")
|
||||
if err != nil {
|
||||
fmt.Println("检查和创建数据库出错", err)
|
||||
loger.Error("check or create db error", zap.Any("error", err))
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func GetCtrlUrl(host, device string) string {
|
||||
request := ctrlUrlRequest(host, device)
|
||||
response, _ := http.DefaultClient.Do(request)
|
||||
resultBody, _ := ioutil.ReadAll(response.Body)
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode == 200 {
|
||||
return resolve(string(resultBody))
|
||||
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func ctrlUrlRequest(host string, deviceDescUrl string) *http.Request {
|
||||
//请求头
|
||||
header := http.Header{}
|
||||
header.Set("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
|
||||
header.Set("User-Agent", "preston")
|
||||
header.Set("Host", host)
|
||||
header.Set("Connection", "keep-alive")
|
||||
request, _ := http.NewRequest("GET", "http://"+host+deviceDescUrl, nil)
|
||||
request.Header = header
|
||||
return request
|
||||
}
|
||||
|
||||
func resolve(resultStr string) string {
|
||||
inputReader := strings.NewReader(resultStr)
|
||||
|
||||
// 从文件读取,如可以如下:
|
||||
// content, err := ioutil.ReadFile("studygolang.xml")
|
||||
// decoder := xml.NewDecoder(bytes.NewBuffer(content))
|
||||
|
||||
lastLabel := ""
|
||||
|
||||
ISUpnpServer := false
|
||||
|
||||
IScontrolURL := false
|
||||
var controlURL string //`controlURL`
|
||||
// var eventSubURL string //`eventSubURL`
|
||||
// var SCPDURL string //`SCPDURL`
|
||||
|
||||
decoder := xml.NewDecoder(inputReader)
|
||||
for t, err := decoder.Token(); err == nil && !IScontrolURL; t, err = decoder.Token() {
|
||||
switch token := t.(type) {
|
||||
// 处理元素开始(标签)
|
||||
case xml.StartElement:
|
||||
if ISUpnpServer {
|
||||
name := token.Name.Local
|
||||
lastLabel = name
|
||||
}
|
||||
|
||||
// 处理元素结束(标签)
|
||||
case xml.EndElement:
|
||||
// log.Println("结束标记:", token.Name.Local)
|
||||
// 处理字符数据(这里就是元素的文本)
|
||||
case xml.CharData:
|
||||
//得到url后其他标记就不处理了
|
||||
content := string([]byte(token))
|
||||
//找到提供端口映射的服务
|
||||
if content == "urn:schemas-upnp-org:service:WANIPConnection:1" {
|
||||
ISUpnpServer = true
|
||||
continue
|
||||
}
|
||||
|
||||
if ISUpnpServer {
|
||||
switch lastLabel {
|
||||
case "controlURL":
|
||||
controlURL = content
|
||||
IScontrolURL = true
|
||||
case "eventSubURL":
|
||||
// eventSubURL = content
|
||||
case "SCPDURL":
|
||||
// SCPDURL = content
|
||||
}
|
||||
}
|
||||
default:
|
||||
// ...
|
||||
}
|
||||
}
|
||||
return controlURL
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
|
||||
)
|
||||
|
||||
func TestGetCtrlUrl(t *testing.T) {
|
||||
upnp, err := Gateway()
|
||||
if err == nil {
|
||||
upnp.CtrlUrl = GetCtrlUrl(upnp.GatewayHost, upnp.DeviceDescUrl)
|
||||
upnp.LocalHost = ip_helper2.GetLoclIp()
|
||||
upnp.AddPortMapping(8090, 8090, "TCP")
|
||||
//upnp.DelPortMapping(9999, "TCP")
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import (
|
||||
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
|
||||
"github.com/pkg/errors"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func Gateway() (*Upnp, error) {
|
||||
result, error := send()
|
||||
if result == "" || error != nil {
|
||||
return nil, error
|
||||
}
|
||||
upnp := resolvesss(result)
|
||||
return upnp, nil
|
||||
}
|
||||
|
||||
func send() (string, error) {
|
||||
var str = "M-SEARCH * HTTP/1.1\r\n" +
|
||||
"HOST: 239.255.255.250:1900\r\n" +
|
||||
"ST: urn:schemas-upnp-org:service:WANIPConnection:1\r\n" +
|
||||
"MAN: \"ssdp:discover\"\r\n" + "MX: 3\r\n\r\n"
|
||||
var conn *net.UDPConn
|
||||
remoteAddr, err := net.ResolveUDPAddr("udp", "239.255.255.250:1900")
|
||||
if err != nil {
|
||||
return "", errors.New("组播地址格式不正确")
|
||||
}
|
||||
localAddr, err := net.ResolveUDPAddr("udp", ip_helper2.GetLoclIp()+":")
|
||||
|
||||
if err != nil {
|
||||
return "", errors.New("本地ip地址格式不正确")
|
||||
}
|
||||
conn, err = net.ListenUDP("udp", localAddr)
|
||||
defer conn.Close()
|
||||
if err != nil {
|
||||
return "", errors.New("监听udp出错")
|
||||
}
|
||||
_, err = conn.WriteToUDP([]byte(str), remoteAddr)
|
||||
if err != nil {
|
||||
return "", errors.New("发送msg到组播地址出错")
|
||||
}
|
||||
buf := make([]byte, 1024)
|
||||
n, _, err := conn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
return "", errors.New("从组播地址接搜消息出错")
|
||||
}
|
||||
result := string(buf[:n])
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func resolvesss(result string) *Upnp {
|
||||
var upnp = &Upnp{}
|
||||
lines := strings.Split(result, "\r\n")
|
||||
for _, line := range lines {
|
||||
//按照第一个冒号分为两个字符串
|
||||
nameValues := strings.SplitAfterN(line, ":", 2)
|
||||
if len(nameValues) < 2 {
|
||||
continue
|
||||
}
|
||||
switch strings.ToUpper(strings.Trim(strings.Split(nameValues[0], ":")[0], " ")) {
|
||||
case "ST":
|
||||
//fmt.Println(nameValues[1])
|
||||
case "CACHE-CONTROL":
|
||||
//fmt.Println(nameValues[1])
|
||||
case "LOCATION":
|
||||
urls := strings.Split(strings.Split(nameValues[1], "//")[1], "/")
|
||||
upnp.GatewayHost = (urls[0])
|
||||
upnp.DeviceDescUrl = ("/" + urls[1])
|
||||
case "SERVER":
|
||||
upnp.GatewayName = (nameValues[1])
|
||||
default:
|
||||
}
|
||||
}
|
||||
return upnp
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGateway(t *testing.T) {
|
||||
|
||||
Gateway()
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
//
|
||||
////添加一个端口映射
|
||||
func (n *Upnp) AddPortMapping(localPort, remotePort int, protocol string) (err error) {
|
||||
defer func() {
|
||||
if errTemp := recover(); errTemp != nil {
|
||||
loger2.NewOLoger().Error("upnp模块报错了", errTemp)
|
||||
}
|
||||
}()
|
||||
|
||||
if isSuccess := addSend(localPort, remotePort, protocol, n.GatewayHost, n.CtrlUrl, n.LocalHost); isSuccess {
|
||||
return nil
|
||||
} else {
|
||||
return errors.New("添加一个端口映射失败")
|
||||
}
|
||||
}
|
||||
|
||||
func addSend(localPort, remotePort int, protocol, host, ctrUrl, localHost string) bool {
|
||||
request := addRequest(localPort, remotePort, protocol, host, ctrUrl, localHost)
|
||||
response, _ := http.DefaultClient.Do(request)
|
||||
defer response.Body.Close()
|
||||
//resultBody, _ := ioutil.ReadAll(response.Body)
|
||||
//fmt.Println(string(resultBody))
|
||||
return response.StatusCode == 200
|
||||
}
|
||||
|
||||
type Node struct {
|
||||
Name string
|
||||
Content string
|
||||
Attr map[string]string
|
||||
Child []Node
|
||||
}
|
||||
|
||||
func addRequest(localPort, remotePort int, protocol string, gatewayHost, ctlUrl, localHost string) *http.Request {
|
||||
//请求头
|
||||
header := http.Header{}
|
||||
header.Set("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
|
||||
header.Set("SOAPAction", `"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"`)
|
||||
header.Set("Content-Type", "text/xml")
|
||||
header.Set("Connection", "Close")
|
||||
header.Set("Content-Length", "")
|
||||
//请求体
|
||||
body := Node{Name: "SOAP-ENV:Envelope",
|
||||
Attr: map[string]string{"xmlns:SOAP-ENV": `"http://schemas.xmlsoap.org/soap/envelope/"`,
|
||||
"SOAP-ENV:encodingStyle": `"http://schemas.xmlsoap.org/soap/encoding/"`}}
|
||||
childOne := Node{Name: `SOAP-ENV:Body`}
|
||||
childTwo := Node{Name: `m:AddPortMapping`,
|
||||
Attr: map[string]string{"xmlns:m": `"urn:schemas-upnp-org:service:WANIPConnection:1"`}}
|
||||
|
||||
childList1 := Node{Name: "NewExternalPort", Content: strconv.Itoa(remotePort)}
|
||||
childList2 := Node{Name: "NewInternalPort", Content: strconv.Itoa(localPort)}
|
||||
childList3 := Node{Name: "NewProtocol", Content: protocol}
|
||||
childList4 := Node{Name: "NewEnabled", Content: "1"}
|
||||
childList5 := Node{Name: "NewInternalClient", Content: localHost}
|
||||
childList6 := Node{Name: "NewLeaseDuration", Content: "0"}
|
||||
childList7 := Node{Name: "NewPortMappingDescription", Content: "Oasis"}
|
||||
childList8 := Node{Name: "NewRemoteHost"}
|
||||
childTwo.AddChild(childList1)
|
||||
childTwo.AddChild(childList2)
|
||||
childTwo.AddChild(childList3)
|
||||
childTwo.AddChild(childList4)
|
||||
childTwo.AddChild(childList5)
|
||||
childTwo.AddChild(childList6)
|
||||
childTwo.AddChild(childList7)
|
||||
childTwo.AddChild(childList8)
|
||||
|
||||
childOne.AddChild(childTwo)
|
||||
body.AddChild(childOne)
|
||||
bodyStr := body.BuildXML()
|
||||
//请求
|
||||
request, _ := http.NewRequest("POST", "http://"+gatewayHost+ctlUrl,
|
||||
strings.NewReader(bodyStr))
|
||||
request.Header = header
|
||||
request.Header.Set("Content-Length", strconv.Itoa(len([]byte(bodyStr))))
|
||||
return request
|
||||
}
|
||||
|
||||
func (n *Node) AddChild(node Node) {
|
||||
n.Child = append(n.Child, node)
|
||||
}
|
||||
|
||||
func (n *Node) BuildXML() string {
|
||||
buf := bytes.NewBufferString("<")
|
||||
buf.WriteString(n.Name)
|
||||
for key, value := range n.Attr {
|
||||
buf.WriteString(" ")
|
||||
buf.WriteString(key + "=" + value)
|
||||
}
|
||||
buf.WriteString(">" + n.Content)
|
||||
|
||||
for _, node := range n.Child {
|
||||
buf.WriteString(node.BuildXML())
|
||||
}
|
||||
buf.WriteString("</" + n.Name + ">")
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (n *Upnp) DelPortMapping(remotePort int, protocol string) bool {
|
||||
isSuccess := delSendSend(remotePort, protocol, n.GatewayHost, n.CtrlUrl)
|
||||
if isSuccess {
|
||||
//this.MappingPort.delMapping(remotePort, protocol)
|
||||
//fmt.Println("删除了一个端口映射: remote:", remotePort)
|
||||
}
|
||||
return isSuccess
|
||||
}
|
||||
|
||||
func delSendSend(remotePort int, protocol, host, ctlUrl string) bool {
|
||||
delrequest := delbuildRequest(remotePort, protocol, host, ctlUrl)
|
||||
response, _ := http.DefaultClient.Do(delrequest)
|
||||
//resultBody, _ := ioutil.ReadAll(response.Body)
|
||||
defer response.Body.Close()
|
||||
|
||||
return response.StatusCode == 200
|
||||
}
|
||||
|
||||
func delbuildRequest(remotePort int, protocol, host, ctlUrl string) *http.Request {
|
||||
//请求头
|
||||
header := http.Header{}
|
||||
header.Set("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
|
||||
header.Set("SOAPAction", `"urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping"`)
|
||||
header.Set("Content-Type", "text/xml")
|
||||
header.Set("Connection", "Close")
|
||||
header.Set("Content-Length", "")
|
||||
//请求体
|
||||
body := Node{Name: "SOAP-ENV:Envelope",
|
||||
Attr: map[string]string{"xmlns:SOAP-ENV": `"http://schemas.xmlsoap.org/soap/envelope/"`,
|
||||
"SOAP-ENV:encodingStyle": `"http://schemas.xmlsoap.org/soap/encoding/"`}}
|
||||
childOne := Node{Name: `SOAP-ENV:Body`}
|
||||
childTwo := Node{Name: `m:DeletePortMapping`,
|
||||
Attr: map[string]string{"xmlns:m": `"urn:schemas-upnp-org:service:WANIPConnection:1"`}}
|
||||
childList1 := Node{Name: "NewExternalPort", Content: strconv.Itoa(remotePort)}
|
||||
childList2 := Node{Name: "NewProtocol", Content: protocol}
|
||||
childList3 := Node{Name: "NewRemoteHost"}
|
||||
childTwo.AddChild(childList1)
|
||||
childTwo.AddChild(childList2)
|
||||
childTwo.AddChild(childList3)
|
||||
childOne.AddChild(childTwo)
|
||||
body.AddChild(childOne)
|
||||
bodyStr := body.BuildXML()
|
||||
|
||||
//请求
|
||||
request, _ := http.NewRequest("POST", "http://"+host+ctlUrl,
|
||||
strings.NewReader(bodyStr))
|
||||
request.Header = header
|
||||
request.Header.Set("Content-Length", strconv.Itoa(len([]byte(bodyStr))))
|
||||
return request
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAddPortMapping(t *testing.T) {
|
||||
//AddPortMapping(6666,6666,"TCP","192.168.2.1:5000",)
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/prestonTao/upnp"
|
||||
)
|
||||
|
||||
type Upnp struct {
|
||||
LocalHost string `json:"local_host"`
|
||||
GatewayName string `json:"gateway_name"` //网关名称
|
||||
GatewayHost string `json:"gateway_host"` //网关ip和端口
|
||||
DeviceDescUrl string `json:"device_desc_url"` //设备描述url
|
||||
CtrlUrl string `json:"ctrl_url"` //控制请求url
|
||||
}
|
||||
|
||||
func Testaaa() {
|
||||
upnpMan := new(upnp.Upnp)
|
||||
err := upnpMan.SearchGateway()
|
||||
if err != nil {
|
||||
fmt.Println(err.Error())
|
||||
} else {
|
||||
fmt.Println("local ip address: ", upnpMan.LocalHost)
|
||||
fmt.Println("gateway ip address: ", upnpMan.Gateway.Host)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package upnp
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTestaaa(t *testing.T) {
|
||||
(Testaaa())
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package oasis_err
|
||||
package common_err
|
||||
|
||||
const (
|
||||
SUCCESS = 200
|
||||
@@ -7,20 +7,25 @@ const (
|
||||
ERROR_AUTH_TOKEN = 401
|
||||
|
||||
//user
|
||||
PWD_INVALID = 10001
|
||||
PWD_IS_EMPTY = 10002
|
||||
PWD_INVALID = 10001
|
||||
PWD_IS_EMPTY = 10002
|
||||
PWD_INVALID_OLD = 10003
|
||||
ACCOUNT_LOCK = 10004
|
||||
PWD_IS_TOO_SIMPLE = 10005
|
||||
USER_NOT_EXIST = 10006
|
||||
USER_EXIST = 10007
|
||||
KEY_NOT_EXIST = 10008
|
||||
NOT_IMAGE = 10009
|
||||
IMAGE_TOO_LARGE = 10010
|
||||
INSUFFICIENT_PERMISSIONS = 10011
|
||||
|
||||
PWD_INVALID_OLD = 10003
|
||||
ACCOUNT_LOCK = 10004
|
||||
//system
|
||||
DIR_ALREADY_EXISTS = 20001
|
||||
FILE_ALREADY_EXISTS = 20002
|
||||
FILE_OR_DIR_EXISTS = 20003
|
||||
PORT_IS_OCCUPIED = 20004
|
||||
COMMAND_ERROR_INVALID_OPERATION = 20005
|
||||
|
||||
//zerotier
|
||||
GET_TOKEN_ERROR = 30001
|
||||
VERIFICATION_FAILURE = 20006
|
||||
|
||||
//disk
|
||||
NAME_NOT_AVAILABLE = 40001
|
||||
@@ -40,6 +45,7 @@ const (
|
||||
FILE_READ_ERROR = 60002
|
||||
FILE_DELETE_ERROR = 60003
|
||||
DIR_NOT_EXISTS = 60004
|
||||
SOURCE_DES_SAME = 60005
|
||||
|
||||
//shortcuts
|
||||
SHORTCUTS_URL_ERROR = 70001
|
||||
@@ -60,19 +66,24 @@ var MsgFlags = map[int]string{
|
||||
ERROR_AUTH_TOKEN: "Error auth token",
|
||||
|
||||
//user
|
||||
PWD_INVALID: "Invalid password",
|
||||
PWD_IS_EMPTY: "Password is empty",
|
||||
PWD_INVALID_OLD: "Invalid old password",
|
||||
ACCOUNT_LOCK: "Account is locked",
|
||||
PWD_INVALID: "Invalid password",
|
||||
PWD_IS_EMPTY: "Password is empty",
|
||||
PWD_INVALID_OLD: "Invalid old password",
|
||||
ACCOUNT_LOCK: "Account is locked",
|
||||
PWD_IS_TOO_SIMPLE: "Password is too simple",
|
||||
USER_NOT_EXIST: "User does not exist",
|
||||
USER_EXIST: "User already exists",
|
||||
KEY_NOT_EXIST: "Key does not exist",
|
||||
IMAGE_TOO_LARGE: "Image is too large",
|
||||
NOT_IMAGE: "Not an image",
|
||||
INSUFFICIENT_PERMISSIONS: "Insufficient permissions",
|
||||
|
||||
//system
|
||||
DIR_ALREADY_EXISTS: "Folder already exists",
|
||||
FILE_ALREADY_EXISTS: "File already exists",
|
||||
FILE_OR_DIR_EXISTS: "File or folder already exists",
|
||||
PORT_IS_OCCUPIED: "Port is occupied",
|
||||
|
||||
//zerotier
|
||||
GET_TOKEN_ERROR: "Get token error,Please log in to zerotier's official website to confirm whether the account is available",
|
||||
DIR_ALREADY_EXISTS: "Folder already exists",
|
||||
FILE_ALREADY_EXISTS: "File already exists",
|
||||
FILE_OR_DIR_EXISTS: "File or folder already exists",
|
||||
PORT_IS_OCCUPIED: "Port is occupied",
|
||||
VERIFICATION_FAILURE: "Verification failure",
|
||||
|
||||
//app
|
||||
UNINSTALL_APP_ERROR: "Error uninstalling app",
|
||||
@@ -88,6 +99,7 @@ var MsgFlags = map[int]string{
|
||||
FORMAT_ERROR: "Formatting failed, please check if the directory is occupied",
|
||||
|
||||
//
|
||||
SOURCE_DES_SAME: "Source and destination cannot be the same.",
|
||||
FILE_DOES_NOT_EXIST: "File does not exist",
|
||||
|
||||
DIR_NOT_EXISTS: "Directory does not exist",
|
||||
22
pkg/utils/encryption/md5_helper.go
Normal file
22
pkg/utils/encryption/md5_helper.go
Normal file
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-06-14 14:33:25
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-14 14:33:49
|
||||
* @FilePath: /CasaOS/pkg/utils/encryption/md5_helper.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package encryption
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
func GetMD5ByStr(str string) string {
|
||||
h := md5.New()
|
||||
h.Write([]byte(str))
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
@@ -2,9 +2,11 @@ package file
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path"
|
||||
@@ -12,6 +14,8 @@ import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/mholt/archiver/v3"
|
||||
)
|
||||
|
||||
// GetSize get the file size
|
||||
@@ -182,7 +186,7 @@ func ReadFullFile(path string) []byte {
|
||||
}
|
||||
|
||||
// File copies a single file from src to dst
|
||||
func CopyFile(src, dst string) error {
|
||||
func CopyFile(src, dst, style string) error {
|
||||
var err error
|
||||
var srcfd *os.File
|
||||
var dstfd *os.File
|
||||
@@ -193,20 +197,55 @@ func CopyFile(src, dst string) error {
|
||||
if !strings.HasSuffix(dst, "/") {
|
||||
dst += "/"
|
||||
}
|
||||
dstPath := dst
|
||||
dst += lastPath
|
||||
for i := 0; Exists(dst); i++ {
|
||||
name := strings.Split(lastPath, ".")
|
||||
nameIndex := 0
|
||||
if len(name) > 2 {
|
||||
nameIndex = len(name) - 2
|
||||
if Exists(dst) {
|
||||
if style == "skip" {
|
||||
return nil
|
||||
} else {
|
||||
os.Remove(dst)
|
||||
}
|
||||
name[nameIndex] = name[nameIndex] + "(Copy)"
|
||||
dst = dstPath
|
||||
for _, v := range name {
|
||||
dst += v + "."
|
||||
}
|
||||
|
||||
if srcfd, err = os.Open(src); err != nil {
|
||||
return err
|
||||
}
|
||||
defer srcfd.Close()
|
||||
|
||||
if dstfd, err = os.Create(dst); err != nil {
|
||||
return err
|
||||
}
|
||||
defer dstfd.Close()
|
||||
|
||||
if _, err = io.Copy(dstfd, srcfd); err != nil {
|
||||
return err
|
||||
}
|
||||
if srcinfo, err = os.Stat(src); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(dst, srcinfo.Mode())
|
||||
}
|
||||
|
||||
/**
|
||||
* @description:
|
||||
* @param {*} src
|
||||
* @param {*} dst
|
||||
* @param {string} style
|
||||
* @return {*}
|
||||
* @method:
|
||||
* @router:
|
||||
*/
|
||||
func CopySingleFile(src, dst, style string) error {
|
||||
var err error
|
||||
var srcfd *os.File
|
||||
var dstfd *os.File
|
||||
var srcinfo os.FileInfo
|
||||
|
||||
if Exists(dst) {
|
||||
if style == "skip" {
|
||||
return nil
|
||||
} else {
|
||||
os.Remove(dst)
|
||||
}
|
||||
dst = strings.TrimSuffix(dst, ".")
|
||||
}
|
||||
|
||||
if srcfd, err = os.Open(src); err != nil {
|
||||
@@ -240,7 +279,7 @@ func GetNoDuplicateFileName(fullPath string) string {
|
||||
}
|
||||
|
||||
// Dir copies a whole directory recursively
|
||||
func CopyDir(src string, dst string) error {
|
||||
func CopyDir(src string, dst string, style string) error {
|
||||
var err error
|
||||
var fds []os.FileInfo
|
||||
var srcinfo os.FileInfo
|
||||
@@ -249,16 +288,23 @@ func CopyDir(src string, dst string) error {
|
||||
return err
|
||||
}
|
||||
if !srcinfo.IsDir() {
|
||||
if err = CopyFile(src, dst); err != nil {
|
||||
if err = CopyFile(src, dst, style); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
dstPath := dst
|
||||
//dstPath := dst
|
||||
lastPath := src[strings.LastIndex(src, "/")+1:]
|
||||
dst += "/" + lastPath
|
||||
for i := 0; Exists(dst); i++ {
|
||||
dst = dstPath + "/" + lastPath + strconv.Itoa(i+1)
|
||||
// for i := 0; Exists(dst); i++ {
|
||||
// dst = dstPath + "/" + lastPath + strconv.Itoa(i+1)
|
||||
// }
|
||||
if Exists(dst) {
|
||||
if style == "skip" {
|
||||
return nil
|
||||
} else {
|
||||
os.Remove(dst)
|
||||
}
|
||||
}
|
||||
if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
|
||||
return err
|
||||
@@ -271,11 +317,11 @@ func CopyDir(src string, dst string) error {
|
||||
dstfp := dst //path.Join(dst, fd.Name())
|
||||
|
||||
if fd.IsDir() {
|
||||
if err = CopyDir(srcfp, dstfp); err != nil {
|
||||
if err = CopyDir(srcfp, dstfp, style); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
} else {
|
||||
if err = CopyFile(srcfp, dstfp); err != nil {
|
||||
if err = CopyFile(srcfp, dstfp, style); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
@@ -332,3 +378,149 @@ func SpliceFiles(dir, path string, length int, startPoint int) error {
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetCompressionAlgorithm(t string) (string, archiver.Writer, error) {
|
||||
|
||||
switch t {
|
||||
case "zip", "":
|
||||
return ".zip", archiver.NewZip(), nil
|
||||
case "tar":
|
||||
return ".tar", archiver.NewTar(), nil
|
||||
case "targz":
|
||||
return ".tar.gz", archiver.NewTarGz(), nil
|
||||
case "tarbz2":
|
||||
return ".tar.bz2", archiver.NewTarBz2(), nil
|
||||
case "tarxz":
|
||||
return ".tar.xz", archiver.NewTarXz(), nil
|
||||
case "tarlz4":
|
||||
return ".tar.lz4", archiver.NewTarLz4(), nil
|
||||
case "tarsz":
|
||||
return ".tar.sz", archiver.NewTarSz(), nil
|
||||
default:
|
||||
return "", nil, errors.New("format not implemented")
|
||||
}
|
||||
}
|
||||
func AddFile(ar archiver.Writer, path, commonPath string) error {
|
||||
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !info.IsDir() && !info.Mode().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if path != commonPath {
|
||||
filename := info.Name()
|
||||
err = ar.Write(archiver.File{
|
||||
FileInfo: archiver.FileInfo{
|
||||
FileInfo: info,
|
||||
CustomName: filename,
|
||||
},
|
||||
ReadCloser: file,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if info.IsDir() {
|
||||
names, err := file.Readdirnames(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, name := range names {
|
||||
err = AddFile(ar, filepath.Join(path, name), commonPath)
|
||||
if err != nil {
|
||||
log.Printf("Failed to archive %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
func CommonPrefix(sep byte, paths ...string) string {
|
||||
// Handle special cases.
|
||||
switch len(paths) {
|
||||
case 0:
|
||||
return ""
|
||||
case 1:
|
||||
return path.Clean(paths[0])
|
||||
}
|
||||
|
||||
// Note, we treat string as []byte, not []rune as is often
|
||||
// done in Go. (And sep as byte, not rune). This is because
|
||||
// most/all supported OS' treat paths as string of non-zero
|
||||
// bytes. A filename may be displayed as a sequence of Unicode
|
||||
// runes (typically encoded as UTF-8) but paths are
|
||||
// not required to be valid UTF-8 or in any normalized form
|
||||
// (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
|
||||
// file names.
|
||||
c := []byte(path.Clean(paths[0]))
|
||||
|
||||
// We add a trailing sep to handle the case where the
|
||||
// common prefix directory is included in the path list
|
||||
// (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
|
||||
// path.Clean will have cleaned off trailing / separators with
|
||||
// the exception of the root directory, "/" (in which case we
|
||||
// make it "//", but this will get fixed up to "/" bellow).
|
||||
c = append(c, sep)
|
||||
|
||||
// Ignore the first path since it's already in c
|
||||
for _, v := range paths[1:] {
|
||||
// Clean up each path before testing it
|
||||
v = path.Clean(v) + string(sep)
|
||||
|
||||
// Find the first non-common byte and truncate c
|
||||
if len(v) < len(c) {
|
||||
c = c[:len(v)]
|
||||
}
|
||||
for i := 0; i < len(c); i++ {
|
||||
if v[i] != c[i] {
|
||||
c = c[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove trailing non-separator characters and the final separator
|
||||
for i := len(c) - 1; i >= 0; i-- {
|
||||
if c[i] == sep {
|
||||
c = c[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return string(c)
|
||||
}
|
||||
|
||||
func GetFileOrDirSize(path string) (int64, error) {
|
||||
fileInfo, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if fileInfo.IsDir() {
|
||||
return DirSizeB(path + "/")
|
||||
}
|
||||
return fileInfo.Size(), nil
|
||||
}
|
||||
|
||||
//getFileSize get file size by path(B)
|
||||
func DirSizeB(path string) (int64, error) {
|
||||
var size int64
|
||||
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
|
||||
if !info.IsDir() {
|
||||
size += info.Size()
|
||||
}
|
||||
return err
|
||||
})
|
||||
return size, err
|
||||
}
|
||||
|
||||
@@ -2,9 +2,13 @@ package file
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/dsoprea/go-exif/v3"
|
||||
@@ -82,3 +86,176 @@ func GetThumbnailByWebPhoto(path string, width, height int) ([]byte, error) {
|
||||
imaging.Encode(&buf, img, f)
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func ImageExtArray() []string {
|
||||
|
||||
ext := []string{
|
||||
"ase",
|
||||
"art",
|
||||
"bmp",
|
||||
"blp",
|
||||
"cd5",
|
||||
"cit",
|
||||
"cpt",
|
||||
"cr2",
|
||||
"cut",
|
||||
"dds",
|
||||
"dib",
|
||||
"djvu",
|
||||
"egt",
|
||||
"exif",
|
||||
"gif",
|
||||
"gpl",
|
||||
"grf",
|
||||
"icns",
|
||||
"ico",
|
||||
"iff",
|
||||
"jng",
|
||||
"jpeg",
|
||||
"jpg",
|
||||
"jfif",
|
||||
"jp2",
|
||||
"jps",
|
||||
"lbm",
|
||||
"max",
|
||||
"miff",
|
||||
"mng",
|
||||
"msp",
|
||||
"nitf",
|
||||
"ota",
|
||||
"pbm",
|
||||
"pc1",
|
||||
"pc2",
|
||||
"pc3",
|
||||
"pcf",
|
||||
"pcx",
|
||||
"pdn",
|
||||
"pgm",
|
||||
"PI1",
|
||||
"PI2",
|
||||
"PI3",
|
||||
"pict",
|
||||
"pct",
|
||||
"pnm",
|
||||
"pns",
|
||||
"ppm",
|
||||
"psb",
|
||||
"psd",
|
||||
"pdd",
|
||||
"psp",
|
||||
"px",
|
||||
"pxm",
|
||||
"pxr",
|
||||
"qfx",
|
||||
"raw",
|
||||
"rle",
|
||||
"sct",
|
||||
"sgi",
|
||||
"rgb",
|
||||
"int",
|
||||
"bw",
|
||||
"tga",
|
||||
"tiff",
|
||||
"tif",
|
||||
"vtf",
|
||||
"xbm",
|
||||
"xcf",
|
||||
"xpm",
|
||||
"3dv",
|
||||
"amf",
|
||||
"ai",
|
||||
"awg",
|
||||
"cgm",
|
||||
"cdr",
|
||||
"cmx",
|
||||
"dxf",
|
||||
"e2d",
|
||||
"egt",
|
||||
"eps",
|
||||
"fs",
|
||||
"gbr",
|
||||
"odg",
|
||||
"svg",
|
||||
"stl",
|
||||
"vrml",
|
||||
"x3d",
|
||||
"sxd",
|
||||
"v2d",
|
||||
"vnd",
|
||||
"wmf",
|
||||
"emf",
|
||||
"art",
|
||||
"xar",
|
||||
"png",
|
||||
"webp",
|
||||
"jxr",
|
||||
"hdp",
|
||||
"wdp",
|
||||
"cur",
|
||||
"ecw",
|
||||
"iff",
|
||||
"lbm",
|
||||
"liff",
|
||||
"nrrd",
|
||||
"pam",
|
||||
"pcx",
|
||||
"pgf",
|
||||
"sgi",
|
||||
"rgb",
|
||||
"rgba",
|
||||
"bw",
|
||||
"int",
|
||||
"inta",
|
||||
"sid",
|
||||
"ras",
|
||||
"sun",
|
||||
"tga",
|
||||
}
|
||||
|
||||
return ext
|
||||
}
|
||||
|
||||
/**
|
||||
* @description:get a image's ext
|
||||
* @param {string} path "file path"
|
||||
* @return {string} ext "file ext"
|
||||
* @return {error} err "error info"
|
||||
*/
|
||||
func GetImageExt(p string) (string, error) {
|
||||
file, err := os.Open(p)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
buff := make([]byte, 512)
|
||||
|
||||
_, err = file.Read(buff)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
filetype := http.DetectContentType(buff)
|
||||
|
||||
ext := ImageExtArray()
|
||||
|
||||
for i := 0; i < len(ext); i++ {
|
||||
if strings.Contains(ext[i], filetype[6:]) {
|
||||
return ext[i], nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", errors.New("invalid image type")
|
||||
}
|
||||
|
||||
func GetImageExtByName(p string) (string, error) {
|
||||
|
||||
extArr := ImageExtArray()
|
||||
ext := filepath.Ext(p)
|
||||
for i := 0; i < len(extArr); i++ {
|
||||
if strings.Contains(ext, extArr[i]) {
|
||||
return extArr[i], nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("invalid image type")
|
||||
}
|
||||
|
||||
@@ -1,11 +1,65 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2021-09-30 18:18:14
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-24 10:02:46
|
||||
* @FilePath: /CasaOS/pkg/utils/jwt/jwt.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
jwt "github.com/golang-jwt/jwt"
|
||||
jwt "github.com/golang-jwt/jwt/v4"
|
||||
)
|
||||
|
||||
// type Claims struct {
|
||||
// UserName string `json:"username"`
|
||||
// PassWord string `json:"password"`
|
||||
// Id int `json:"id"`
|
||||
// jwt.RegisteredClaims
|
||||
// }
|
||||
|
||||
// var jwtSecret []byte
|
||||
|
||||
// //创建token
|
||||
// func GenerateToken(username, password string, id int, issuer string, t time.Duration) (string, error) {
|
||||
// clims := Claims{
|
||||
// username,
|
||||
// password,
|
||||
// id,
|
||||
// jwt.RegisteredClaims{
|
||||
// ExpiresAt: jwt.NewNumericDate(time.Now().Add(t)),
|
||||
// IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
// NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
// Issuer: issuer,
|
||||
// },
|
||||
// }
|
||||
|
||||
// tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, clims)
|
||||
// token, err := tokenClaims.SignedString(jwtSecret)
|
||||
// return token, err
|
||||
|
||||
// }
|
||||
|
||||
// //解析token
|
||||
// func ParseToken(token string) (*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
|
||||
// }
|
||||
// }
|
||||
// return nil, err
|
||||
// }
|
||||
|
||||
//****************** soon to be removed ******************
|
||||
|
||||
type Claims struct {
|
||||
UserName string `json:"username"`
|
||||
PassWord string `json:"password"`
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-06-17 14:01:25
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-24 10:13:52
|
||||
* @FilePath: /CasaOS/pkg/utils/jwt/jwt_helper.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package jwt
|
||||
|
||||
import (
|
||||
@@ -5,36 +15,87 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func JWT(swagHandler gin.HandlerFunc) gin.HandlerFunc {
|
||||
// func JWT() gin.HandlerFunc {
|
||||
// return func(c *gin.Context) {
|
||||
// var code int
|
||||
// code = common_err.SUCCESS
|
||||
// token := c.GetHeader("Authorization")
|
||||
// if len(token) == 0 {
|
||||
// token = c.Query("token")
|
||||
// }
|
||||
// if token == "" {
|
||||
// code = common_err.INVALID_PARAMS
|
||||
// }
|
||||
|
||||
// claims, err := ParseToken(token)
|
||||
// //_, err := ParseToken(token)
|
||||
// if err != nil {
|
||||
// code = common_err.ERROR_AUTH_TOKEN
|
||||
// } else if !claims.VerifyExpiresAt(time.Now(), true) || !claims.VerifyIssuer("casaos", true) {
|
||||
// code = common_err.ERROR_AUTH_TOKEN
|
||||
// }
|
||||
// if code != common_err.SUCCESS {
|
||||
// c.JSON(code, model.Result{Success: code, Message: common_err.GetMsg(code)})
|
||||
// c.Abort()
|
||||
// return
|
||||
// }
|
||||
// c.Request.Header.Add("user_id", strconv.Itoa(claims.Id))
|
||||
// c.Next()
|
||||
// }
|
||||
// }
|
||||
|
||||
// //get AccessToken
|
||||
// func GetAccessToken(username, pwd string, id int) string {
|
||||
// token, err := GenerateToken(username, pwd, id, "casaos", 3*time.Hour*time.Duration(1))
|
||||
// if err == nil {
|
||||
// return token
|
||||
// } else {
|
||||
// loger2.Error(fmt.Sprintf("Get Token Fail: %V", err))
|
||||
// return ""
|
||||
// }
|
||||
// }
|
||||
|
||||
// func GetRefreshToken(username, pwd string, id int) string {
|
||||
// token, err := GenerateToken(username, pwd, id, "fresh", 7*24*time.Hour*time.Duration(1))
|
||||
// if err == nil {
|
||||
// return token
|
||||
// } else {
|
||||
// loger2.Error(fmt.Sprintf("Get Token Fail: %V", err))
|
||||
// return ""
|
||||
// }
|
||||
// }
|
||||
|
||||
//*************** soon to be removed *****************
|
||||
|
||||
func JWT() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var code int
|
||||
code = oasis_err2.SUCCESS
|
||||
code = common_err.SUCCESS
|
||||
token := c.GetHeader("Authorization")
|
||||
if len(token) == 0 {
|
||||
token = c.Query("token")
|
||||
}
|
||||
if token == "" {
|
||||
code = oasis_err2.INVALID_PARAMS
|
||||
}
|
||||
if swagHandler == nil {
|
||||
//claims, err := ParseToken(token)
|
||||
_, err := ParseToken(token)
|
||||
if err != nil {
|
||||
code = oasis_err2.ERROR_AUTH_TOKEN
|
||||
|
||||
}
|
||||
//else if time.Now().Unix() > claims.ExpiresAt {
|
||||
// code = oasis_err2.ERROR_AUTH_TOKEN
|
||||
//}
|
||||
code = common_err.INVALID_PARAMS
|
||||
}
|
||||
|
||||
if code != oasis_err2.SUCCESS {
|
||||
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)})
|
||||
//claims, err := ParseToken(token)
|
||||
_, err := ParseToken(token)
|
||||
if err != nil {
|
||||
code = common_err.ERROR_AUTH_TOKEN
|
||||
|
||||
}
|
||||
//else if time.Now().Unix() > claims.ExpiresAt {
|
||||
// code = oasis_err2.ERROR_AUTH_TOKEN
|
||||
//}
|
||||
|
||||
if code != common_err.SUCCESS {
|
||||
c.JSON(http.StatusOK, model.Result{Success: code, Message: common_err.GetMsg(code)})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,109 +1,92 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-06-02 15:09:38
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-27 15:47:49
|
||||
* @FilePath: /CasaOS/pkg/utils/loger/log.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package loger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
file2 "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
//定义一个int的别名
|
||||
type Level int
|
||||
var loggers *zap.Logger
|
||||
|
||||
type OLog interface {
|
||||
Debug(v ...interface{})
|
||||
Info(v ...interface{})
|
||||
Warn(v ...interface{})
|
||||
Error(v ...interface{})
|
||||
Fatal(v ...interface{})
|
||||
Path() string
|
||||
}
|
||||
|
||||
type oLog struct {
|
||||
}
|
||||
|
||||
var (
|
||||
F *os.File
|
||||
DefaultPrefix = ""
|
||||
DefaultCallerDepth = 2
|
||||
logger *log.Logger
|
||||
logPrefix = ""
|
||||
levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
|
||||
)
|
||||
|
||||
//iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。
|
||||
const (
|
||||
DEBUG Level = iota
|
||||
INFO
|
||||
WARN
|
||||
ERROR
|
||||
FATAL
|
||||
)
|
||||
|
||||
//日志初始化
|
||||
func LogSetup() {
|
||||
var err error
|
||||
filePath := fmt.Sprintf("%s", config.AppInfo.LogSavePath)
|
||||
fileName := fmt.Sprintf("%s.%s",
|
||||
config.AppInfo.LogSaveName,
|
||||
config.AppInfo.LogFileExt,
|
||||
)
|
||||
F, err = file2.MustOpen(fileName, filePath)
|
||||
if err != nil {
|
||||
log.Fatalf("logging.Setup err: %v", err)
|
||||
func getFileLogWriter() (writeSyncer zapcore.WriteSyncer) {
|
||||
// 使用 lumberjack 实现 log rotate
|
||||
lumberJackLogger := &lumberjack.Logger{
|
||||
Filename: filepath.Join(config.AppInfo.LogPath, fmt.Sprintf("%s.%s",
|
||||
config.AppInfo.LogSaveName,
|
||||
config.AppInfo.LogFileExt,
|
||||
)),
|
||||
MaxSize: 10,
|
||||
MaxBackups: 60,
|
||||
MaxAge: 1,
|
||||
Compress: true,
|
||||
}
|
||||
|
||||
logger = log.New(F, DefaultPrefix, log.LstdFlags)
|
||||
|
||||
return zapcore.AddSync(lumberJackLogger)
|
||||
}
|
||||
func (o *oLog) Path() string {
|
||||
filePath := fmt.Sprintf("%s", config.AppInfo.LogSavePath)
|
||||
fileName := fmt.Sprintf("%s.%s",
|
||||
config.AppInfo.LogSaveName,
|
||||
config.AppInfo.LogFileExt,
|
||||
|
||||
func LogInit() {
|
||||
encoderConfig := zap.NewProductionEncoderConfig()
|
||||
encoderConfig.EncodeTime = zapcore.EpochTimeEncoder
|
||||
encoder := zapcore.NewJSONEncoder(encoderConfig)
|
||||
fileWriteSyncer := getFileLogWriter()
|
||||
core := zapcore.NewTee(
|
||||
zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel),
|
||||
zapcore.NewCore(encoder, fileWriteSyncer, zapcore.InfoLevel),
|
||||
)
|
||||
return filePath + fileName
|
||||
}
|
||||
func (o *oLog) Debug(v ...interface{}) {
|
||||
setPrefix(DEBUG)
|
||||
logger.Println(v)
|
||||
loggers = zap.New(core)
|
||||
|
||||
}
|
||||
|
||||
func (o *oLog) Info(v ...interface{}) {
|
||||
setPrefix(INFO)
|
||||
logger.Println(v)
|
||||
func Info(message string, fields ...zap.Field) {
|
||||
callerFields := getCallerInfoForLog()
|
||||
fields = append(fields, callerFields...)
|
||||
loggers.Info(message, fields...)
|
||||
}
|
||||
|
||||
func (o *oLog) Warn(v ...interface{}) {
|
||||
setPrefix(WARN)
|
||||
logger.Println(v)
|
||||
func Debug(message string, fields ...zap.Field) {
|
||||
callerFields := getCallerInfoForLog()
|
||||
fields = append(fields, callerFields...)
|
||||
loggers.Debug(message, fields...)
|
||||
}
|
||||
|
||||
func (o *oLog) Error(v ...interface{}) {
|
||||
setPrefix(ERROR)
|
||||
logger.Println(v)
|
||||
func Error(message string, fields ...zap.Field) {
|
||||
callerFields := getCallerInfoForLog()
|
||||
fields = append(fields, callerFields...)
|
||||
loggers.Error(message, fields...)
|
||||
}
|
||||
|
||||
func (o *oLog) Fatal(v ...interface{}) {
|
||||
setPrefix(FATAL)
|
||||
logger.Println(v)
|
||||
func Warn(message string, fields ...zap.Field) {
|
||||
callerFields := getCallerInfoForLog()
|
||||
fields = append(fields, callerFields...)
|
||||
loggers.Warn(message, fields...)
|
||||
}
|
||||
|
||||
func setPrefix(level Level) {
|
||||
_, file, line, ok := runtime.Caller(DefaultCallerDepth)
|
||||
if ok {
|
||||
logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
|
||||
} else {
|
||||
logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
|
||||
func getCallerInfoForLog() (callerFields []zap.Field) {
|
||||
|
||||
pc, file, line, ok := runtime.Caller(2) // 回溯两层,拿到写日志的调用方的函数信息
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
funcName := runtime.FuncForPC(pc).Name()
|
||||
funcName = path.Base(funcName) //Base函数返回路径的最后一个元素,只保留函数名
|
||||
|
||||
logger.SetPrefix(logPrefix)
|
||||
}
|
||||
|
||||
func NewOLoger() OLog {
|
||||
return &oLog{}
|
||||
callerFields = append(callerFields, zap.String("func", funcName), zap.String("file", file), zap.Int("line", line))
|
||||
return
|
||||
}
|
||||
|
||||
109
pkg/utils/loger/log_old.go
Normal file
109
pkg/utils/loger/log_old.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package loger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
file2 "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
)
|
||||
|
||||
//定义一个int的别名
|
||||
type Level int
|
||||
|
||||
type OLog interface {
|
||||
Debug(v ...interface{})
|
||||
Info(v ...interface{})
|
||||
Warn(v ...interface{})
|
||||
Error(v ...interface{})
|
||||
Fatal(v ...interface{})
|
||||
Path() string
|
||||
}
|
||||
|
||||
type oLog struct {
|
||||
}
|
||||
|
||||
var (
|
||||
F *os.File
|
||||
DefaultPrefix = ""
|
||||
DefaultCallerDepth = 2
|
||||
logger *log.Logger
|
||||
logPrefix = ""
|
||||
levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
|
||||
)
|
||||
|
||||
//iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。
|
||||
const (
|
||||
DEBUG Level = iota
|
||||
INFO
|
||||
WARN
|
||||
ERROR
|
||||
FATAL
|
||||
)
|
||||
|
||||
//日志初始化
|
||||
func LogSetupOld() {
|
||||
var err error
|
||||
filePath := fmt.Sprintf("%s", config.AppInfo.LogPath)
|
||||
fileName := fmt.Sprintf("%s.%s",
|
||||
config.AppInfo.LogSaveName,
|
||||
config.AppInfo.LogFileExt,
|
||||
)
|
||||
F, err = file2.MustOpen(fileName, filePath)
|
||||
if err != nil {
|
||||
log.Fatalf("logging.Setup err: %v", err)
|
||||
}
|
||||
|
||||
logger = log.New(F, DefaultPrefix, log.LstdFlags)
|
||||
|
||||
}
|
||||
func (o *oLog) Path() string {
|
||||
filePath := fmt.Sprintf("%s", config.AppInfo.LogPath)
|
||||
fileName := fmt.Sprintf("%s.%s",
|
||||
config.AppInfo.LogSaveName,
|
||||
config.AppInfo.LogFileExt,
|
||||
)
|
||||
return filePath + fileName
|
||||
}
|
||||
func (o *oLog) Debug(v ...interface{}) {
|
||||
setPrefix(DEBUG)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
func (o *oLog) Info(v ...interface{}) {
|
||||
setPrefix(INFO)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
func (o *oLog) Warn(v ...interface{}) {
|
||||
setPrefix(WARN)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
func (o *oLog) Error(v ...interface{}) {
|
||||
setPrefix(ERROR)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
func (o *oLog) Fatal(v ...interface{}) {
|
||||
setPrefix(FATAL)
|
||||
logger.Println(v)
|
||||
}
|
||||
|
||||
func setPrefix(level Level) {
|
||||
_, file, line, ok := runtime.Caller(DefaultCallerDepth)
|
||||
if ok {
|
||||
logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
|
||||
} else {
|
||||
logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
|
||||
}
|
||||
|
||||
logger.SetPrefix(logPrefix)
|
||||
}
|
||||
|
||||
func NewOLoger() OLog {
|
||||
return &oLog{}
|
||||
}
|
||||
@@ -1,24 +1,27 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-13 18:15:46
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-29 14:29:34
|
||||
* @FilePath: /CasaOS/pkg/utils/version/version.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package version
|
||||
|
||||
import (
|
||||
json2 "encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func IsNeedUpdate() (bool, model.Version) {
|
||||
var version model.Version
|
||||
v := httper.OasisGet(config.ServerInfo.ServerApi + "/v1/sys/version")
|
||||
data := gjson.Get(v, "data")
|
||||
json2.Unmarshal([]byte(data.String()), &version)
|
||||
func IsNeedUpdate(version model.Version) (bool, model.Version) {
|
||||
|
||||
v1 := strings.Split(version.Version, ".")
|
||||
|
||||
v2 := strings.Split(types.CURRENTVERSION, ".")
|
||||
|
||||
for len(v1) < len(v2) {
|
||||
@@ -30,54 +33,15 @@ func IsNeedUpdate() (bool, model.Version) {
|
||||
for i := 0; i < len(v1); i++ {
|
||||
a, _ := strconv.Atoi(v1[i])
|
||||
b, _ := strconv.Atoi(v2[i])
|
||||
if i == 0 && a > b {
|
||||
continue
|
||||
}
|
||||
if a > b {
|
||||
return true, version
|
||||
}
|
||||
if a < b {
|
||||
return false, version
|
||||
}
|
||||
}
|
||||
return false, version
|
||||
}
|
||||
|
||||
func IsClientNeedUpdate() (bool, model.Version) {
|
||||
var version model.Version
|
||||
v := httper.OasisGet(config.ServerInfo.ServerApi + "/v1/sys/client/version")
|
||||
data := gjson.Get(v, "data")
|
||||
json2.Unmarshal([]byte(data.String()), &version)
|
||||
|
||||
v1 := strings.Split(version.Version, ".")
|
||||
v2 := strings.Split(types.CURRENTVERSION, ".")
|
||||
|
||||
for len(v1) < len(v2) {
|
||||
v1 = append(v1, "0")
|
||||
}
|
||||
for len(v2) < len(v1) {
|
||||
v2 = append(v2, "0")
|
||||
}
|
||||
for i := 0; i < len(v1); i++ {
|
||||
a, _ := strconv.Atoi(v1[i])
|
||||
b, _ := strconv.Atoi(v2[i])
|
||||
if a > b {
|
||||
return true, version
|
||||
}
|
||||
}
|
||||
return false, version
|
||||
}
|
||||
|
||||
//a版本大于b版本
|
||||
func VersionCompared(a string, b string) bool {
|
||||
v1 := strings.Split(a, ".")
|
||||
v2 := strings.Split(b, ".")
|
||||
for len(v1) < len(v2) {
|
||||
v1 = append(v1, "0")
|
||||
}
|
||||
for len(v2) < len(v1) {
|
||||
v2 = append(v2, "0")
|
||||
}
|
||||
for i := 0; i < len(v1); i++ {
|
||||
a, _ := strconv.Atoi(v1[i])
|
||||
b, _ := strconv.Atoi(v2[i])
|
||||
if a > b {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
15
route/doc.go
15
route/doc.go
@@ -1,15 +0,0 @@
|
||||
//go:build doc
|
||||
// +build doc
|
||||
|
||||
package route
|
||||
|
||||
import (
|
||||
_ "github.com/IceWhaleTech/CasaOS/docs"
|
||||
ginSwagger "github.com/swaggo/gin-swagger"
|
||||
swaggerFiles "github.com/swaggo/gin-swagger/swaggerFiles"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// swagHandler = ginSwagger.WrapHandler(swaggerFiles.Handler)
|
||||
swagHandler = ginSwagger.WrapHandler(swaggerFiles.Handler)
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package route
|
||||
import (
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
"github.com/IceWhaleTech/CasaOS/model/system_app"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/env_helper"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/port"
|
||||
@@ -22,14 +25,14 @@ import (
|
||||
|
||||
func InitFunction() {
|
||||
go checkSystemApp()
|
||||
Update2_3()
|
||||
ShellInit()
|
||||
CheckSerialDiskMount()
|
||||
|
||||
CheckToken2_11()
|
||||
ImportApplications()
|
||||
ChangeAPIUrl()
|
||||
InitSystemApplication()
|
||||
|
||||
MoveUserToDB()
|
||||
}
|
||||
|
||||
var syncIsExistence = false
|
||||
@@ -79,14 +82,12 @@ func installSyncthing(appId string) {
|
||||
appInfo.Tip = env_helper.ReplaceStringDefaultENV(appInfo.Tip)
|
||||
}
|
||||
|
||||
appInfo.MaxMemory = service.MyService.ZiMa().GetMemInfo().Total >> 20
|
||||
appInfo.MaxMemory = service.MyService.System().GetMemInfo()["total"].(uint64) >> 20
|
||||
|
||||
id := uuid.NewV4().String()
|
||||
|
||||
installLog := model2.AppNotify{}
|
||||
|
||||
// step:下载镜像
|
||||
err := service.MyService.Docker().DockerPullImage(dockerImage+":"+dockerImageVersion, installLog)
|
||||
err := service.MyService.Docker().DockerPullImage(dockerImage+":"+dockerImageVersion, "", "")
|
||||
if err != nil {
|
||||
//pull image error
|
||||
fmt.Println("pull image error", err, dockerImage, dockerImageVersion)
|
||||
@@ -104,9 +105,10 @@ func installSyncthing(appId string) {
|
||||
m.Ports = appInfo.Ports
|
||||
m.Restart = "always"
|
||||
m.Volumes = appInfo.Volumes
|
||||
m.NetworkModel = appInfo.NetworkModel
|
||||
m.Label = id
|
||||
m.CustomId = id
|
||||
containerId, err := service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m, appInfo.NetworkModel)
|
||||
containerId, err := service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m)
|
||||
if err != nil {
|
||||
fmt.Println("container create error", err)
|
||||
// create container error
|
||||
@@ -142,14 +144,13 @@ func checkSystemApp() {
|
||||
}
|
||||
|
||||
path := ""
|
||||
for _, i := range info.HostConfig.Mounts {
|
||||
if i.Target == "/config" {
|
||||
for _, i := range info.Mounts {
|
||||
if i.Destination == "/config" {
|
||||
path = i.Source
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
content := file.ReadFullFile(path + "config.xml")
|
||||
content := file.ReadFullFile(filepath.Join(path, "config.xml"))
|
||||
syncConfig := &system_app.SyncConfig{}
|
||||
xml.Unmarshal(content, &syncConfig)
|
||||
config.SystemConfigInfo.SyncKey = syncConfig.Key
|
||||
@@ -197,10 +198,14 @@ func CheckSerialDiskMount() {
|
||||
}
|
||||
}
|
||||
service.MyService.Disk().RemoveLSBLKCache()
|
||||
command.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;AutoRemoveUnuseDir")
|
||||
command.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;AutoRemoveUnuseDir")
|
||||
}
|
||||
func Update2_3() {
|
||||
command.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/assist.sh")
|
||||
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() {
|
||||
@@ -210,16 +215,7 @@ func CheckToken2_11() {
|
||||
config.Cfg.Section("server").Key("Token").SetValue(token())
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
}
|
||||
if len(config.AppInfo.RootPath) == 0 {
|
||||
config.Cfg.Section("app").Key("RootPath").SetValue("/casaOS")
|
||||
config.AppInfo.RootPath = "/casaOS"
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
}
|
||||
// if len(config.ServerInfo.Handshake) == 0 {
|
||||
// config.Cfg.Section("app").Key("RootPath").SetValue("/casaOS")
|
||||
// config.AppInfo.RootPath = "/casaOS"
|
||||
// config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
// }
|
||||
|
||||
sysType := runtime.GOOS
|
||||
if len(config.FileSettingInfo.DownloadDir) == 0 {
|
||||
downloadPath := "/DATA/Downloads"
|
||||
@@ -246,7 +242,7 @@ func CheckToken2_11() {
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
}
|
||||
|
||||
if service.MyService.ZiMa().GetSysInfo().KernelArch == "aarch64" && config.ServerInfo.USBAutoMount != "True" && strings.Contains(service.MyService.ZiMa().GetDeviceTree(), "Raspberry Pi") {
|
||||
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")
|
||||
}
|
||||
@@ -277,22 +273,23 @@ func ChangeAPIUrl() {
|
||||
|
||||
}
|
||||
|
||||
// 0.3.1
|
||||
func InitSystemApplication() {
|
||||
list := service.MyService.App().GetApplicationList()
|
||||
if len(list) != 2 {
|
||||
application := model2.ApplicationModel{}
|
||||
application.Name = "Files"
|
||||
application.Icon = "/ui/img/Files.svg"
|
||||
application.Type = "system"
|
||||
application.Order = 0
|
||||
service.MyService.App().CreateApplication(application)
|
||||
//0.3.3
|
||||
//Transferring user data to the database
|
||||
func MoveUserToDB() {
|
||||
|
||||
application.Name = "CasaConnect"
|
||||
application.Icon = "/ui/img/CasaConnect.svg"
|
||||
application.Type = "system"
|
||||
application.Order = 0
|
||||
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")
|
||||
}
|
||||
|
||||
service.MyService.App().CreateApplication(application)
|
||||
}
|
||||
}
|
||||
|
||||
285
route/periodical.go
Normal file
285
route/periodical.go
Normal file
@@ -0,0 +1,285 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-07-01 15:11:36
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-07-01 15:16:00
|
||||
* @FilePath: /CasaOS/route/periodical.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-27 15:55:36
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-29 16:47:19
|
||||
* @FilePath: /CasaOS/route/periodical.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package route
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
)
|
||||
|
||||
func SendNetINfoBySocket() {
|
||||
netList := service.MyService.System().GetNetInfo()
|
||||
newNet := []model.IOCountersStat{}
|
||||
nets := service.MyService.System().GetNet(true)
|
||||
for _, n := range netList {
|
||||
for _, netCardName := range nets {
|
||||
if n.Name == netCardName {
|
||||
item := *(*model.IOCountersStat)(unsafe.Pointer(&n))
|
||||
item.State = strings.TrimSpace(service.MyService.System().GetNetState(n.Name))
|
||||
item.Time = time.Now().Unix()
|
||||
newNet = append(newNet, item)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
service.MyService.Notify().SendNetInfoBySocket(newNet)
|
||||
}
|
||||
|
||||
func SendCPUBySocket() {
|
||||
cpu := service.MyService.System().GetCpuPercent()
|
||||
num := service.MyService.System().GetCpuCoreNum()
|
||||
cpuData := make(map[string]interface{})
|
||||
cpuData["percent"] = cpu
|
||||
cpuData["num"] = num
|
||||
service.MyService.Notify().SendCPUInfoBySocket(cpuData)
|
||||
}
|
||||
|
||||
func SendMemBySocket() {
|
||||
service.MyService.Notify().SendMemInfoBySocket(service.MyService.System().GetMemInfo())
|
||||
}
|
||||
|
||||
func SendDiskBySocket() {
|
||||
list := service.MyService.Disk().LSBLK(true)
|
||||
|
||||
summary := model.Summary{}
|
||||
healthy := true
|
||||
findSystem := 0
|
||||
|
||||
for i := 0; i < len(list); i++ {
|
||||
if len(list[i].Children) > 0 && findSystem == 0 {
|
||||
|
||||
for j := 0; j < len(list[i].Children); j++ {
|
||||
|
||||
if len(list[i].Children[j].Children) > 0 {
|
||||
for _, v := range list[i].Children[j].Children {
|
||||
if v.MountPoint == "/" {
|
||||
s, _ := strconv.ParseUint(v.FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(v.FSUsed, 10, 64)
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
findSystem = 1
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if list[i].Children[j].MountPoint == "/" {
|
||||
s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(list[i].Children[j].FSUsed, 10, 64)
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
findSystem = 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if findSystem == 1 {
|
||||
findSystem += 1
|
||||
continue
|
||||
}
|
||||
if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {
|
||||
temp := service.MyService.Disk().SmartCTL(list[i].Path)
|
||||
if reflect.DeepEqual(temp, model.SmartctlA{}) {
|
||||
healthy = true
|
||||
} else {
|
||||
healthy = temp.SmartStatus.Passed
|
||||
}
|
||||
|
||||
//list[i].Temperature = temp.Temperature.Current
|
||||
|
||||
if len(list[i].Children) > 0 {
|
||||
for _, v := range list[i].Children {
|
||||
s, _ := strconv.ParseUint(v.FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(v.FSUsed, 10, 64)
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
summary.Health = healthy
|
||||
service.MyService.Notify().SendDiskInfoBySocket(summary)
|
||||
}
|
||||
|
||||
func SendUSBBySocket() {
|
||||
usbList := service.MyService.Disk().LSBLK(false)
|
||||
usb := []model.DriveUSB{}
|
||||
for _, v := range usbList {
|
||||
if v.Tran == "usb" {
|
||||
temp := model.DriveUSB{}
|
||||
temp.Model = v.Model
|
||||
temp.Name = v.Name
|
||||
temp.Size = v.Size
|
||||
mountTemp := true
|
||||
if len(v.Children) == 0 {
|
||||
mountTemp = false
|
||||
}
|
||||
for _, child := range v.Children {
|
||||
if len(child.MountPoint) > 0 {
|
||||
avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)
|
||||
temp.Avail += avail
|
||||
used, _ := strconv.ParseUint(child.FSUsed, 10, 64)
|
||||
temp.Used += used
|
||||
} else {
|
||||
mountTemp = false
|
||||
}
|
||||
}
|
||||
temp.Mount = mountTemp
|
||||
usb = append(usb, temp)
|
||||
}
|
||||
}
|
||||
service.MyService.Notify().SendUSBInfoBySocket(usb)
|
||||
}
|
||||
|
||||
func SendAllHardwareStatusBySocket() {
|
||||
|
||||
netList := service.MyService.System().GetNetInfo()
|
||||
newNet := []model.IOCountersStat{}
|
||||
nets := service.MyService.System().GetNet(true)
|
||||
for _, n := range netList {
|
||||
for _, netCardName := range nets {
|
||||
if n.Name == netCardName {
|
||||
item := *(*model.IOCountersStat)(unsafe.Pointer(&n))
|
||||
item.State = strings.TrimSpace(service.MyService.System().GetNetState(n.Name))
|
||||
item.Time = time.Now().Unix()
|
||||
newNet = append(newNet, item)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
cpu := service.MyService.System().GetCpuPercent()
|
||||
num := service.MyService.System().GetCpuCoreNum()
|
||||
cpuData := make(map[string]interface{})
|
||||
cpuData["percent"] = cpu
|
||||
cpuData["num"] = num
|
||||
|
||||
list := service.MyService.Disk().LSBLK(true)
|
||||
|
||||
summary := model.Summary{}
|
||||
healthy := true
|
||||
findSystem := 0
|
||||
|
||||
for i := 0; i < len(list); i++ {
|
||||
if len(list[i].Children) > 0 && findSystem == 0 {
|
||||
|
||||
for j := 0; j < len(list[i].Children); j++ {
|
||||
|
||||
if len(list[i].Children[j].Children) > 0 {
|
||||
for _, v := range list[i].Children[j].Children {
|
||||
if v.MountPoint == "/" {
|
||||
s, _ := strconv.ParseUint(v.FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(v.FSUsed, 10, 64)
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
findSystem = 1
|
||||
break
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if list[i].Children[j].MountPoint == "/" {
|
||||
s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(list[i].Children[j].FSUsed, 10, 64)
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
findSystem = 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if findSystem == 1 {
|
||||
findSystem += 1
|
||||
continue
|
||||
}
|
||||
if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {
|
||||
temp := service.MyService.Disk().SmartCTL(list[i].Path)
|
||||
if reflect.DeepEqual(temp, model.SmartctlA{}) {
|
||||
healthy = true
|
||||
} else {
|
||||
healthy = temp.SmartStatus.Passed
|
||||
}
|
||||
if len(list[i].Children) > 0 {
|
||||
for _, v := range list[i].Children {
|
||||
s, _ := strconv.ParseUint(v.FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(v.FSUsed, 10, 64)
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
summary.Health = healthy
|
||||
|
||||
usbList := service.MyService.Disk().LSBLK(false)
|
||||
usb := []model.DriveUSB{}
|
||||
for _, v := range usbList {
|
||||
if v.Tran == "usb" {
|
||||
temp := model.DriveUSB{}
|
||||
temp.Model = v.Model
|
||||
temp.Name = v.Name
|
||||
temp.Size = v.Size
|
||||
mountTemp := true
|
||||
if len(v.Children) == 0 {
|
||||
mountTemp = false
|
||||
}
|
||||
for _, child := range v.Children {
|
||||
if len(child.MountPoint) > 0 {
|
||||
avail, _ := strconv.ParseUint(child.FSAvail, 10, 64)
|
||||
temp.Avail += avail
|
||||
used, _ := strconv.ParseUint(child.FSUsed, 10, 64)
|
||||
temp.Used += used
|
||||
} else {
|
||||
mountTemp = false
|
||||
}
|
||||
}
|
||||
temp.Mount = mountTemp
|
||||
usb = append(usb, temp)
|
||||
}
|
||||
}
|
||||
memInfo := service.MyService.System().GetMemInfo()
|
||||
|
||||
service.MyService.Notify().SendAllHardwareStatusBySocket(summary, usb, memInfo, cpuData, newNet)
|
||||
|
||||
}
|
||||
152
route/route.go
152
route/route.go
@@ -8,11 +8,11 @@ import (
|
||||
jwt2 "github.com/IceWhaleTech/CasaOS/pkg/utils/jwt"
|
||||
v1 "github.com/IceWhaleTech/CasaOS/route/v1"
|
||||
"github.com/IceWhaleTech/CasaOS/web"
|
||||
|
||||
"github.com/gin-contrib/gzip"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var swagHandler gin.HandlerFunc
|
||||
var OnlineDemo bool = false
|
||||
|
||||
func InitRouter() *gin.Engine {
|
||||
@@ -20,84 +20,67 @@ func InitRouter() *gin.Engine {
|
||||
r := gin.Default()
|
||||
|
||||
r.Use(middleware.Cors())
|
||||
r.Use(middleware.WriteLog())
|
||||
r.Use(gzip.Gzip(gzip.DefaultCompression))
|
||||
gin.SetMode(config.ServerInfo.RunMode)
|
||||
|
||||
r.StaticFS("/ui", http.FS(web.Static))
|
||||
r.GET("/", WebUIHome)
|
||||
// r.StaticFS("/assets", http.Dir("./static/assets"))
|
||||
// r.StaticFile("/favicon.ico", "./static/favicon.ico")
|
||||
//r.GET("/", func(c *gin.Context) {
|
||||
// c.Redirect(http.StatusMovedPermanently, "ui/")
|
||||
//})
|
||||
if swagHandler != nil {
|
||||
r.GET("/swagger/*any", swagHandler)
|
||||
}
|
||||
|
||||
r.POST("/v1/user/login", v1.Login)
|
||||
r.POST("/v1/user/register/:key", v1.PostUserRegister)
|
||||
r.POST("/v1/user/login", v1.PostUserLogin) //
|
||||
r.GET("/v1/user/all/name", v1.GetUserAllUserName)
|
||||
|
||||
r.GET("/v1/sys/init/check", v1.GetSystemInitCheck)
|
||||
r.GET("/v1/guide/check", v1.GetGuideCheck)
|
||||
|
||||
r.GET("/v1/debug", v1.GetSystemConfigDebug)
|
||||
//set user
|
||||
r.POST("/v1/user/setusernamepwd", v1.Set_Name_Pwd)
|
||||
//get user info
|
||||
r.GET("/v1/user/info", v1.GetUserInfo)
|
||||
r.GET("/v1/user/info/:id", v1.GetUserInfo)
|
||||
r.GET("/v1/user/avatar/:id", v1.GetUserAvatar)
|
||||
r.GET("/v1/user/image", v1.GetUserImage)
|
||||
|
||||
//get user info
|
||||
r.GET("/v1/person/shareid", v1.GetPersonShareId)
|
||||
r.GET("/v1/sys/socket/port", v1.GetSystemSocketPort)
|
||||
//r.POST("/v1/user/refresh/token", v1.PostUserRefreshToken)
|
||||
v1Group := r.Group("/v1")
|
||||
|
||||
v1Group.Use(jwt2.JWT(swagHandler))
|
||||
v1Group.Use(jwt2.JWT())
|
||||
{
|
||||
v1UserGroup := v1Group.Group("/user")
|
||||
v1UserGroup.Use()
|
||||
{
|
||||
|
||||
//chang head
|
||||
v1UserGroup.POST("/head", v1.PostUserHead)
|
||||
//****************** New version needs to be modified start ******************
|
||||
//chang user name
|
||||
v1UserGroup.PUT("/username", v1.PutUserName)
|
||||
//chang pwd
|
||||
v1UserGroup.PUT("/password", v1.PutUserPwd)
|
||||
//edit user info
|
||||
v1UserGroup.POST("/info", v1.PostUserChangeInfo)
|
||||
v1UserGroup.PUT("/nick", v1.PutUserChangeNick)
|
||||
v1UserGroup.PUT("/desc", v1.PutUserChangeDesc)
|
||||
v1UserGroup.PUT("/nick", v1.PutUserNick)
|
||||
v1UserGroup.PUT("/desc", v1.PutUserDesc)
|
||||
v1UserGroup.GET("/info", v1.GetUserInfoByUserName)
|
||||
v1UserGroup.GET("/custom/:id/:key", v1.GetUserCustomConf)
|
||||
v1UserGroup.POST("/custom/:id/:key", v1.PostUserCustomConf)
|
||||
v1UserGroup.DELETE("/custom/:id/:key", v1.DeleteUserCustomConf)
|
||||
v1UserGroup.POST("/upload/image/:id/:key", v1.PostUserUploadImage)
|
||||
v1UserGroup.POST("/file/image/:id/:key", v1.PostUserFileImage)
|
||||
v1UserGroup.DELETE("/image/:id", v1.DeleteUserImage)
|
||||
//****************** New version needs to be modified end ******************
|
||||
|
||||
//****************** soon to be removed start ******************
|
||||
v1UserGroup.POST("/person/info", v1.PostUserPersonInfo)
|
||||
|
||||
v1UserGroup.GET("/shareid", v1.GetUserShareID)
|
||||
//****************** soon to be removed end ******************
|
||||
|
||||
}
|
||||
//v1UserGroup.GET("/info", v1.GetUserInfo)
|
||||
|
||||
v1ZiMaGroup := v1Group.Group("/zima")
|
||||
v1ZiMaGroup.Use()
|
||||
{
|
||||
//获取cpu信息
|
||||
v1ZiMaGroup.GET("/getcpuinfo", v1.CupInfo)
|
||||
//获取内存信息
|
||||
v1ZiMaGroup.GET("/getmeminfo", v1.MemInfo)
|
||||
//获取硬盘信息
|
||||
v1ZiMaGroup.GET("/getdiskinfo", v1.DiskInfo)
|
||||
v1UserGroup.PUT("/avatar", v1.PutUserAvatar)
|
||||
v1UserGroup.GET("/avatar", v1.GetUserAvatar)
|
||||
v1UserGroup.DELETE("/delete/:id", v1.DeleteUser)
|
||||
|
||||
//获取网络信息
|
||||
v1ZiMaGroup.GET("/getnetinfo", v1.NetInfo)
|
||||
|
||||
//获取系统信息
|
||||
v1ZiMaGroup.GET("/sysinfo", v1.SysInfo)
|
||||
}
|
||||
v1DDNSGroup := v1Group.Group("/ddns")
|
||||
v1DDNSGroup.Use()
|
||||
{
|
||||
//获取ddns列表
|
||||
v1DDNSGroup.GET("/getlist", v1.DDNSGetDomainList)
|
||||
//测试连接性
|
||||
v1DDNSGroup.GET("/ping/:api_host", v1.DDNSPing)
|
||||
//获取ip
|
||||
v1DDNSGroup.GET("/ip", v1.DDNSGetIP)
|
||||
//设置ddns
|
||||
v1DDNSGroup.POST("/set", v1.DDNSAddConfig)
|
||||
//获取ddns
|
||||
v1DDNSGroup.GET("/list", v1.DDNSConfigList)
|
||||
//获取ddns
|
||||
v1DDNSGroup.DELETE("/delete/:id", v1.DDNSDelete)
|
||||
}
|
||||
v1AppGroup := v1Group.Group("/app")
|
||||
v1AppGroup.Use()
|
||||
@@ -114,12 +97,10 @@ func InitRouter() *gin.Engine {
|
||||
v1AppGroup.GET("/port", v1.GetPort)
|
||||
//检查端口
|
||||
v1AppGroup.GET("/check/:port", v1.PortCheck)
|
||||
//分类
|
||||
|
||||
v1AppGroup.GET("/category", v1.CategoryList)
|
||||
//容器相关
|
||||
|
||||
v1AppGroup.GET("/terminal/:id", v1.DockerTerminal)
|
||||
v1AppGroup.GET("/order", v1.GetAppOrder)
|
||||
v1AppGroup.POST("/order", v1.PostAppOrder)
|
||||
//app容器详情
|
||||
v1AppGroup.GET("/info/:id", v1.ContainerInfo)
|
||||
//app容器日志
|
||||
@@ -127,11 +108,9 @@ func InitRouter() *gin.Engine {
|
||||
//暂停或启动容器
|
||||
v1AppGroup.PUT("/state/:id", v1.ChangAppState)
|
||||
//安装app
|
||||
v1AppGroup.POST("/install/:id", v1.InstallApp)
|
||||
v1AppGroup.POST("/install", v1.InstallApp)
|
||||
//卸载app
|
||||
v1AppGroup.DELETE("/uninstall/:id", v1.UnInstallApp)
|
||||
//获取安装进度
|
||||
v1AppGroup.GET("/speed/:id", v1.GetInstallSpeed)
|
||||
//获取进度
|
||||
v1AppGroup.GET("/state/:id", v1.GetContainerState)
|
||||
//更新容器配置
|
||||
@@ -147,23 +126,25 @@ func InitRouter() *gin.Engine {
|
||||
v1SysGroup := v1Group.Group("/sys")
|
||||
v1SysGroup.Use()
|
||||
{
|
||||
v1SysGroup.GET("/check", v1.CheckVersion)
|
||||
v1SysGroup.GET("/version/check", v1.GetSystemCheckVersion)
|
||||
v1SysGroup.GET("/hardware/info", v1.GetSystemHardwareInfo)
|
||||
v1SysGroup.GET("/client/version", v1.GetClientVersion)
|
||||
v1SysGroup.POST("/update", v1.SystemUpdate)
|
||||
v1SysGroup.GET("/wsssh", v1.WsSsh)
|
||||
v1SysGroup.GET("/config", v1.GetSystemConfig)
|
||||
//v1SysGroup.POST("/config", v1.PostSetSystemConfig)
|
||||
v1SysGroup.GET("/error/logs", v1.GetCasaOSErrorLogs)
|
||||
v1SysGroup.POST("/config", v1.PostSetSystemConfig)
|
||||
v1SysGroup.GET("/widget/config", v1.GetWidgetConfig)
|
||||
v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig)
|
||||
v1SysGroup.GET("/port", v1.GetCasaOSPort)
|
||||
v1SysGroup.PUT("/port", v1.PutCasaOSPort)
|
||||
v1SysGroup.POST("/kill", v1.PostKillCasaOS)
|
||||
v1SysGroup.GET("/info", v1.Info)
|
||||
v1SysGroup.PUT("/usb/off", v1.PutSystemOffUSBAutoMount)
|
||||
v1SysGroup.PUT("/usb/on", v1.PutSystemOnUSBAutoMount)
|
||||
v1SysGroup.GET("/usb", v1.GetSystemUSBAutoMount)
|
||||
v1SysGroup.POST("/stop", v1.PostKillCasaOS)
|
||||
v1SysGroup.GET("/utilization", v1.GetSystemUtilization)
|
||||
v1SysGroup.PUT("/usb/:status", v1.PutSystemUSBAutoMount)
|
||||
v1SysGroup.GET("/usb/status", v1.GetSystemUSBAutoMount)
|
||||
v1SysGroup.GET("/cpu", v1.GetSystemCupInfo)
|
||||
v1SysGroup.GET("/mem", v1.GetSystemMemInfo)
|
||||
v1SysGroup.GET("/disk", v1.GetSystemDiskInfo)
|
||||
v1SysGroup.GET("/network", v1.GetSystemNetInfo)
|
||||
}
|
||||
v1FileGroup := v1Group.Group("/file")
|
||||
v1FileGroup.Use()
|
||||
@@ -178,12 +159,12 @@ func InitRouter() *gin.Engine {
|
||||
v1FileGroup.POST("/create", v1.PostCreateFile)
|
||||
|
||||
v1FileGroup.GET("/download", v1.GetDownloadFile)
|
||||
v1FileGroup.GET("/new/download", v1.GetFileDownloadNew)
|
||||
v1FileGroup.GET("/download/*path", v1.GetDownloadSingleFile)
|
||||
v1FileGroup.POST("/operate", v1.PostOperateFileOrDir)
|
||||
v1FileGroup.DELETE("/delete", v1.DeleteFile)
|
||||
v1FileGroup.PUT("/update", v1.PutFileContent)
|
||||
v1FileGroup.GET("/image", v1.GetFileImage)
|
||||
|
||||
v1FileGroup.DELETE("/operate/:id", v1.DeleteOperateFileOrDir)
|
||||
//v1FileGroup.GET("/download", v1.UserFileDownloadCommonService)
|
||||
}
|
||||
v1DiskGroup := v1Group.Group("/disk")
|
||||
@@ -197,10 +178,10 @@ func InitRouter() *gin.Engine {
|
||||
v1DiskGroup.GET("/info", v1.GetDiskInfo)
|
||||
|
||||
//format storage
|
||||
v1DiskGroup.POST("/format", v1.FormatDisk)
|
||||
v1DiskGroup.POST("/format", v1.PostDiskFormat)
|
||||
|
||||
// add storage
|
||||
v1DiskGroup.POST("/storage", v1.AddPartition)
|
||||
v1DiskGroup.POST("/storage", v1.PostDiskAddPartition)
|
||||
|
||||
//mount SATA disk
|
||||
v1DiskGroup.POST("/mount", v1.PostMountDisk)
|
||||
@@ -216,32 +197,6 @@ func InitRouter() *gin.Engine {
|
||||
v1DiskGroup.GET("/usb", v1.GetUSBList)
|
||||
|
||||
}
|
||||
v1ShareGroup := v1Group.Group("/share")
|
||||
v1ShareGroup.Use()
|
||||
{
|
||||
v1ShareGroup.POST("/add", v1.PostShareDirAdd)
|
||||
v1ShareGroup.DELETE("/del/:id", v1.DeleteShareDirDel)
|
||||
v1ShareGroup.GET("/list", v1.GetShareDirList)
|
||||
v1ShareGroup.GET("/info/:id", v1.GetShareDirInfo)
|
||||
v1ShareGroup.PUT("/update/:id", v1.PutShareDirEdit)
|
||||
}
|
||||
v1TaskGroup := v1Group.Group("/task")
|
||||
v1TaskGroup.Use()
|
||||
{
|
||||
v1TaskGroup.GET("/list", v1.GetTaskList)
|
||||
v1TaskGroup.PUT("/update", v1.PutTaskUpdate)
|
||||
v1TaskGroup.POST("/add", v1.PostTaskAdd)
|
||||
v1TaskGroup.PUT("/completion/:id", v1.PutTaskMarkerCompletion)
|
||||
|
||||
}
|
||||
|
||||
v1NotifyGroup := v1Group.Group("/notify")
|
||||
v1NotifyGroup.Use()
|
||||
{
|
||||
v1NotifyGroup.GET("/ws", v1.NotifyWS)
|
||||
v1NotifyGroup.PUT("/read/:id", v1.PutNotifyRead)
|
||||
}
|
||||
|
||||
v1PersonGroup := v1Group.Group("/person")
|
||||
v1PersonGroup.Use()
|
||||
{
|
||||
@@ -268,14 +223,7 @@ func InitRouter() *gin.Engine {
|
||||
v1PersonGroup.GET("/image/thumbnail/:shareid", v1.GetPersonImageThumbnail)
|
||||
|
||||
}
|
||||
v1AnalyseGroup := v1Group.Group("/analyse")
|
||||
v1AnalyseGroup.Use()
|
||||
{
|
||||
v1AnalyseGroup.POST("/app", v1.PostAppAnalyse)
|
||||
}
|
||||
v1Group.GET("/sync/config", v1.GetSyncConfig)
|
||||
v1Group.Any("/syncthing/*url", v1.SyncToSyncthing)
|
||||
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
60
route/socket.go
Normal file
60
route/socket.go
Normal file
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-23 17:18:56
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-09 21:48:10
|
||||
* @FilePath: /CasaOS/route/socket.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package route
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model/notify"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/port"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
f "github.com/ambelovsky/gosf"
|
||||
)
|
||||
|
||||
func SocketInit(msg chan notify.Message) {
|
||||
|
||||
// set socket port
|
||||
socketPort := 0
|
||||
if len(config.ServerInfo.SocketPort) == 0 {
|
||||
socketPort, _ = port.GetAvailablePort("tcp")
|
||||
config.ServerInfo.SocketPort = strconv.Itoa(socketPort)
|
||||
config.Cfg.Section("server").Key("SocketPort").SetValue(strconv.Itoa(socketPort))
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
} else {
|
||||
socketPort, _ = strconv.Atoi(config.ServerInfo.SocketPort)
|
||||
if !port.IsPortAvailable(socketPort, "tcp") {
|
||||
socketPort, _ := port.GetAvailablePort("tcp")
|
||||
config.ServerInfo.SocketPort = strconv.Itoa(socketPort)
|
||||
config.Cfg.Section("server").Key("SocketPort").SetValue(strconv.Itoa(socketPort))
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
}
|
||||
}
|
||||
|
||||
f.OnConnect(func(c *f.Client, request *f.Request) {
|
||||
service.ClientCount += 1
|
||||
})
|
||||
f.OnDisconnect(func(c *f.Client, request *f.Request) {
|
||||
service.ClientCount -= 1
|
||||
})
|
||||
go func(msg chan notify.Message) {
|
||||
for v := range msg {
|
||||
f.Broadcast("", v.Path, &v.Msg)
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
}
|
||||
|
||||
}(msg)
|
||||
|
||||
f.Startup(map[string]interface{}{
|
||||
"port": socketPort})
|
||||
|
||||
}
|
||||
13
route/ui.go
13
route/ui.go
@@ -1,9 +1,20 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-06-23 17:27:43
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-23 17:27:48
|
||||
* @FilePath: /CasaOS/route/ui.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package route
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/web"
|
||||
"github.com/gin-gonic/gin"
|
||||
"html/template"
|
||||
)
|
||||
|
||||
func WebUIHome(c *gin.Context) {
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// @Summary post app analyse
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Tags analyse
|
||||
// @Param name formData string true "app name"
|
||||
// @Param type formData string true "action" Enums(open,delete)
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /analyse/app [post]
|
||||
func PostAppAnalyse(c *gin.Context) {
|
||||
if config.SystemConfigInfo.Analyse == "False" {
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
return
|
||||
}
|
||||
name := c.PostForm("name")
|
||||
t := c.PostForm("type")
|
||||
language := c.GetHeader("Language")
|
||||
|
||||
if len(name) == 0 || len(t) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
service.MyService.Casa().PushAppAnalyse(config.ServerInfo.Token, t, name, language)
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
}
|
||||
@@ -7,8 +7,9 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
|
||||
port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -35,8 +36,11 @@ func AppList(c *gin.Context) {
|
||||
t := c.DefaultQuery("type", "rank")
|
||||
categoryId := c.DefaultQuery("category_id", "0")
|
||||
key := c.DefaultQuery("key", "")
|
||||
language := c.GetHeader("Language")
|
||||
recommend, list, community := service.MyService.Casa().GetServerList(index, size, t, categoryId, key, language)
|
||||
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)})
|
||||
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 {
|
||||
@@ -56,11 +60,11 @@ func AppList(c *gin.Context) {
|
||||
// }
|
||||
// }
|
||||
data := make(map[string]interface{}, 3)
|
||||
data["recommend"] = recommend
|
||||
data["list"] = list
|
||||
data["community"] = community
|
||||
data["recommend"] = collection.Recommend
|
||||
data["list"] = collection.List
|
||||
data["community"] = collection.Community
|
||||
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary 获取一个可用端口
|
||||
@@ -79,7 +83,7 @@ func GetPort(c *gin.Context) {
|
||||
p, _ = port2.GetAvailablePort(t)
|
||||
ok = !port2.IsPortAvailable(p, t)
|
||||
}
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: p})
|
||||
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: p})
|
||||
}
|
||||
|
||||
// @Summary 检查端口是否可用
|
||||
@@ -94,7 +98,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: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: port2.IsPortAvailable(p, t)})
|
||||
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: port2.IsPortAvailable(p, t)})
|
||||
}
|
||||
|
||||
// @Summary 我的应用列表
|
||||
@@ -112,12 +116,11 @@ func MyAppList(c *gin.Context) {
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("size", "0"))
|
||||
position, _ := strconv.ParseBool(c.DefaultQuery("position", "true"))
|
||||
list, unTranslation := service.MyService.App().GetMyList(index, size, position)
|
||||
|
||||
data := make(map[string]interface{}, 2)
|
||||
data["list"] = list
|
||||
data["local"] = unTranslation
|
||||
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary my app hardware usage list
|
||||
@@ -129,7 +132,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: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
|
||||
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
// @Summary 应用详情
|
||||
@@ -209,9 +212,9 @@ func AppInfo(c *gin.Context) {
|
||||
// sort.VolSort(volOrder).Sort(info.Volumes.([]model.PathMap))
|
||||
// sort.DevSort(devOrder).Sort(info.Devices)
|
||||
|
||||
info.MaxMemory = service.MyService.ZiMa().GetMemInfo().Total >> 20
|
||||
info.MaxMemory = (service.MyService.System().GetMemInfo()["total"]).(uint64) >> 20
|
||||
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: info})
|
||||
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: info})
|
||||
}
|
||||
|
||||
// @Summary 获取远程分类列表
|
||||
@@ -228,10 +231,10 @@ func CategoryList(c *gin.Context) {
|
||||
count += category.Count
|
||||
}
|
||||
|
||||
rear := append([]model.ServerCategoryList{}, list[0:]...)
|
||||
list = append(list[:0], model.ServerCategoryList{Count: count, Name: "All", Font: "apps"})
|
||||
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: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
|
||||
c.JSON(http.StatusOK, &model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
// @Summary 分享该应用配置
|
||||
|
||||
174
route/v1/ddns.go
174
route/v1/ddns.go
@@ -1,174 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/forease/gotld"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// @Summary 获取可以设置的ddns列表
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags ddns
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /ddns/getlist [get]
|
||||
func DDNSGetDomainList(c *gin.Context) {
|
||||
|
||||
host, domain, tld := gotld.GetSubdomain("bbb.aaa.liru-05.com.cn", 3)
|
||||
fmt.Println(strings.Replace(host, "."+domain, "", 1))
|
||||
fmt.Println(domain)
|
||||
fmt.Println(tld)
|
||||
|
||||
data := make(map[string]interface{}, 2)
|
||||
t, api := service.MyService.DDNS().GetType("godaddy")
|
||||
data["godaddy"] = &model.GoDaddyModel{Type: t, ApiHost: api}
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
Data: data,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// @Summary 添加新的ddns(按给定模型返回内容)
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Tags ddns
|
||||
// @Param type formData string true "类型"
|
||||
// @Param host formData string true "host"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /ddns/set [post]
|
||||
func DDNSAddConfig(c *gin.Context) {
|
||||
t, _ := strconv.Atoi(c.PostForm("type"))
|
||||
host := c.PostForm("host")
|
||||
_, domain, _ := gotld.GetSubdomain("host", 3)
|
||||
sub := strings.ReplaceAll(host, "."+domain, "")
|
||||
|
||||
if service.MyService.DDNS().IsExis(t, domain, sub) {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.ERROR,
|
||||
Message: "Repeat add",
|
||||
})
|
||||
return
|
||||
}
|
||||
var m model2.DDNSUpdateDBModel
|
||||
c.Bind(&m)
|
||||
if err := service.MyService.DDNS().SaveConfig(m); err != nil {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.ERROR,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.ERROR),
|
||||
Data: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary 获取ip,仅做展示使用
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags ddns
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /ddns/ip [get]
|
||||
func DDNSGetIP(c *gin.Context) {
|
||||
ipv4, ipv6 := service.MyService.DDNS().GetExternalIP()
|
||||
var ipjson = make(map[string]string, 2)
|
||||
ipjson["ipv4"] = ipv4
|
||||
ipjson["ipv6"] = ipv6
|
||||
c.JSON(http.StatusOK, &model.Result{
|
||||
Success: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
Data: ipjson,
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary 测试网址是否可以ping通
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags ddns
|
||||
// @Param api_host path int true "api地址"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /ddns/ping/{api_host} [get]
|
||||
func DDNSPing(c *gin.Context) {
|
||||
url := c.Param("api_host")
|
||||
url = strings.ReplaceAll(url, "https://", "")
|
||||
url = strings.ReplaceAll(url, "http://", "")
|
||||
cmd := exec.Command("ping", url, "-c", "1", "-W", "5")
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, &model.Result{
|
||||
Success: oasis_err2.ERROR,
|
||||
Message: err.Error(),
|
||||
Data: false,
|
||||
})
|
||||
} else {
|
||||
c.JSON(http.StatusOK, &model.Result{
|
||||
Success: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
Data: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// @Summary 获取已设置的列表
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags ddns
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /ddns/list [get]
|
||||
func DDNSConfigList(c *gin.Context) {
|
||||
j := service.MyService.DDNS().GetConfigList()
|
||||
ip4 := ip_helper2.GetExternalIPV4()
|
||||
ip6 := ip_helper2.GetExternalIPV6()
|
||||
for i := 0; i < len(*j); i++ {
|
||||
(*j)[i].IPV6 = ip6
|
||||
(*j)[i].IPV4 = ip4
|
||||
cmd := exec.Command("ping", (*j)[i].Host+"."+(*j)[i].Domain, "-c", "1", "-W", "3")
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
(*j)[i].State = false
|
||||
} else {
|
||||
(*j)[i].State = true
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: j})
|
||||
}
|
||||
|
||||
// @Summary 删除ddns
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags ddns
|
||||
// @Param id path int true "ID"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /ddns/delete/{id} [delete]
|
||||
func DDNSDelete(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
isok := service.MyService.DDNS().DeleteConfig(uint(id))
|
||||
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: isok})
|
||||
}
|
||||
@@ -10,8 +10,8 @@ import (
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -111,7 +111,7 @@ func GetDiskList(c *gin.Context) {
|
||||
continue
|
||||
}
|
||||
|
||||
if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" {
|
||||
if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {
|
||||
temp := service.MyService.Disk().SmartCTL(list[i].Path)
|
||||
if reflect.DeepEqual(temp, model.SmartctlA{}) {
|
||||
temp.SmartStatus.Passed = true
|
||||
@@ -154,7 +154,7 @@ func GetDiskList(c *gin.Context) {
|
||||
data["storage"] = storage
|
||||
data["avail"] = avail
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary get disk list
|
||||
@@ -171,7 +171,7 @@ func GetPlugInDisks(c *gin.Context) {
|
||||
for _, item := range list {
|
||||
result = append(result, service.MyService.Disk().GetDiskInfoByPath(item.Path))
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: result})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: result})
|
||||
}
|
||||
|
||||
// @Summary disk detail
|
||||
@@ -185,10 +185,10 @@ func GetPlugInDisks(c *gin.Context) {
|
||||
func GetDiskInfo(c *gin.Context) {
|
||||
path := c.Query("path")
|
||||
if len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
}
|
||||
m := service.MyService.Disk().GetDiskInfo(path)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: m})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m})
|
||||
}
|
||||
|
||||
// @Summary format storage
|
||||
@@ -201,37 +201,37 @@ func GetDiskInfo(c *gin.Context) {
|
||||
// @Param volume formData string true "mount point"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /disk/format [post]
|
||||
func FormatDisk(c *gin.Context) {
|
||||
func PostDiskFormat(c *gin.Context) {
|
||||
path := c.PostForm("path")
|
||||
t := "ext4"
|
||||
pwd := c.PostForm("pwd")
|
||||
volume := c.PostForm("volume")
|
||||
|
||||
if pwd != config.UserInfo.PWD {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.PWD_INVALID, Message: oasis_err.GetMsg(oasis_err.PWD_INVALID)})
|
||||
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: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
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: oasis_err.DISK_BUSYING, Message: oasis_err.GetMsg(oasis_err.DISK_BUSYING)})
|
||||
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: oasis_err.FORMAT_ERROR, Message: oasis_err.GetMsg(oasis_err.FORMAT_ERROR)})
|
||||
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)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary 获取支持的格式
|
||||
@@ -243,7 +243,7 @@ func FormatDisk(c *gin.Context) {
|
||||
// @Router /disk/type [get]
|
||||
func FormatDiskType(c *gin.Context) {
|
||||
var strArr = [4]string{"fat32", "ntfs", "ext4", "exfat"}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: strArr})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: strArr})
|
||||
|
||||
}
|
||||
|
||||
@@ -259,12 +259,12 @@ func RemovePartition(c *gin.Context) {
|
||||
path := c.PostForm("path")
|
||||
|
||||
if len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, 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: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary add storage
|
||||
@@ -278,28 +278,30 @@ func RemovePartition(c *gin.Context) {
|
||||
// @Param format formData bool true "need format(true)"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /disk/storage [post]
|
||||
func AddPartition(c *gin.Context) {
|
||||
func PostDiskAddPartition(c *gin.Context) {
|
||||
|
||||
name := c.PostForm("name")
|
||||
path := c.PostForm("path")
|
||||
format, _ := strconv.ParseBool(c.PostForm("format"))
|
||||
|
||||
if len(name) == 0 || len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
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: oasis_err.DISK_BUSYING, Message: oasis_err.GetMsg(oasis_err.DISK_BUSYING)})
|
||||
c.JSON(http.StatusOK, 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: oasis_err.NAME_NOT_AVAILABLE, Message: oasis_err.GetMsg(oasis_err.NAME_NOT_AVAILABLE)})
|
||||
c.JSON(http.StatusOK, 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: oasis_err.DISK_NEEDS_FORMAT, Message: oasis_err.GetMsg(oasis_err.DISK_NEEDS_FORMAT)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_NEEDS_FORMAT, Message: common_err.GetMsg(common_err.DISK_NEEDS_FORMAT)})
|
||||
delete(diskMap, path)
|
||||
return
|
||||
}
|
||||
@@ -319,7 +321,7 @@ func AddPartition(c *gin.Context) {
|
||||
}
|
||||
currentDisk = service.MyService.Disk().GetDiskInfo(path)
|
||||
if len(currentDisk.Children) != 1 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.DISK_NEEDS_FORMAT, Message: oasis_err.GetMsg(oasis_err.DISK_NEEDS_FORMAT)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_NEEDS_FORMAT, Message: common_err.GetMsg(common_err.DISK_NEEDS_FORMAT)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -338,7 +340,7 @@ func AddPartition(c *gin.Context) {
|
||||
service.MyService.Disk().RemoveLSBLKCache()
|
||||
|
||||
delete(diskMap, path)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary add mount point
|
||||
@@ -378,7 +380,7 @@ func PostMountDisk(c *gin.Context) {
|
||||
m.UUID = serial
|
||||
m.State = 0
|
||||
//service.MyService.Disk().SaveMountPoint(m)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary remove mount point
|
||||
@@ -398,16 +400,16 @@ func PostDiskUmount(c *gin.Context) {
|
||||
pwd := c.PostForm("pwd")
|
||||
|
||||
if len(path) == 0 || len(mountPoint) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if pwd != config.UserInfo.PWD {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.PWD_INVALID, Message: oasis_err.GetMsg(oasis_err.PWD_INVALID)})
|
||||
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: oasis_err.DISK_BUSYING, Message: oasis_err.GetMsg(oasis_err.DISK_BUSYING)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.DISK_BUSYING, Message: common_err.GetMsg(common_err.DISK_BUSYING)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -415,7 +417,7 @@ func PostDiskUmount(c *gin.Context) {
|
||||
//delete data
|
||||
service.MyService.Disk().DeleteMountPoint(path, mountPoint)
|
||||
service.MyService.Disk().RemoveLSBLKCache()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary confirm delete disk
|
||||
@@ -429,7 +431,7 @@ func PostDiskUmount(c *gin.Context) {
|
||||
func DeleteDisk(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
service.MyService.Disk().DeleteMount(id)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary check mount point
|
||||
@@ -453,12 +455,12 @@ func GetDiskCheck(c *gin.Context) {
|
||||
for _, v := range dbList {
|
||||
if _, ok := mapList[v.UUID]; !ok {
|
||||
//disk undefind
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.ERROR, Message: oasis_err.GetMsg(oasis_err.ERROR), Data: "disk undefind"})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: "disk undefind"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary check mount point
|
||||
@@ -493,5 +495,5 @@ func GetUSBList(c *gin.Context) {
|
||||
data = append(data, temp)
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
@@ -2,22 +2,19 @@ package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
json2 "encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/model/notify"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/docker"
|
||||
upnp2 "github.com/IceWhaleTech/CasaOS/pkg/upnp"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/random"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
@@ -44,14 +41,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: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.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: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
// 关闭I/O流
|
||||
@@ -117,7 +114,7 @@ func WsSsh(c *gin.Context) {
|
||||
func SpeedPush(c *gin.Context) {
|
||||
//token := c.Query("token")
|
||||
//if len(token) == 0 || token != config.UserInfo.Token {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR_AUTH_TOKEN, Message: oasis_err2.GetMsg(oasis_err2.ERROR_AUTH_TOKEN)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR_AUTH_TOKEN, Message: common_err.GetMsg(common_err.ERROR_AUTH_TOKEN)})
|
||||
// return
|
||||
//}
|
||||
|
||||
@@ -143,10 +140,8 @@ func SpeedPush(c *gin.Context) {
|
||||
// @Param env formData string false "环境变量"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /app/install/{id} [post]
|
||||
// @Router /app/install [post]
|
||||
func InstallApp(c *gin.Context) {
|
||||
appId := c.Param("id")
|
||||
language := c.GetHeader("Language")
|
||||
var appInfo model.ServerAppList
|
||||
m := model.CustomizationPostData{}
|
||||
c.BindJSON(&m)
|
||||
@@ -156,7 +151,9 @@ func InstallApp(c *gin.Context) {
|
||||
var dockerImageVersion string
|
||||
|
||||
//check app name is exist
|
||||
|
||||
if len(m.Protocol) == 0 {
|
||||
m.Protocol = "http"
|
||||
}
|
||||
if m.Origin != "custom" {
|
||||
oldName := m.Label
|
||||
for i := 0; true; i++ {
|
||||
@@ -169,18 +166,18 @@ func InstallApp(c *gin.Context) {
|
||||
}
|
||||
} else {
|
||||
if _, err := service.MyService.Docker().DockerListByName(m.Label); err == nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR_APP_NAME_EXIST, Message: oasis_err2.GetMsg(oasis_err2.ERROR_APP_NAME_EXIST)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR_APP_NAME_EXIST, Message: common_err.GetMsg(common_err.ERROR_APP_NAME_EXIST)})
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//检查端口
|
||||
//check port
|
||||
if len(m.PortMap) > 0 && m.PortMap != "0" {
|
||||
//c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
//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: oasis_err2.ERROR, Message: "Duplicate port:" + m.PortMap})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + m.PortMap})
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -196,55 +193,39 @@ func InstallApp(c *gin.Context) {
|
||||
dockerImage = m.Image
|
||||
dockerImageVersion = "latest"
|
||||
}
|
||||
if m.Origin != "custom" {
|
||||
appInfo = service.MyService.Casa().GetServerAppInfo(appId, "", language)
|
||||
|
||||
} else {
|
||||
|
||||
appInfo.Title = m.Label
|
||||
appInfo.Description = m.Description
|
||||
appInfo.Icon = m.Icon
|
||||
appInfo.ScreenshotLink = model.Strings{}
|
||||
appInfo.NetworkModel = m.NetworkModel
|
||||
appInfo.Tags = model.Strings{}
|
||||
appInfo.Tagline = ""
|
||||
appInfo.Index = m.Index
|
||||
|
||||
}
|
||||
|
||||
for _, u := range m.Ports {
|
||||
|
||||
if u.Protocol == "udp" {
|
||||
t, _ := strconv.Atoi(u.CommendPort)
|
||||
if !port2.IsPortAvailable(t, "udp") {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.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: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.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: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
return
|
||||
}
|
||||
te, _ := strconv.Atoi(u.CommendPort)
|
||||
if !port2.IsPortAvailable(te, "tcp") {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if m.Origin == "custom" {
|
||||
for _, device := range m.Devices {
|
||||
if file.CheckNotExist(device.Path) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.DEVICE_NOT_EXIST, Message: device.Path + "," + oasis_err2.GetMsg(oasis_err2.DEVICE_NOT_EXIST)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.DEVICE_NOT_EXIST, Message: device.Path + "," + common_err.GetMsg(common_err.DEVICE_NOT_EXIST)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -272,16 +253,16 @@ func InstallApp(c *gin.Context) {
|
||||
m.CustomId = id
|
||||
var relyMap = make(map[string]string)
|
||||
go func() {
|
||||
installLog := model2.AppNotify{}
|
||||
installLog.State = 0
|
||||
installLog.CustomId = m.Label
|
||||
installLog.Message = "installing rely"
|
||||
installLog.Class = types.NOTIFY_APP
|
||||
installLog.Type = types.NOTIFY_TYPE_UNIMPORTANT
|
||||
installLog.CreatedAt = strconv.FormatInt(time.Now().Unix(), 10)
|
||||
installLog.UpdatedAt = strconv.FormatInt(time.Now().Unix(), 10)
|
||||
installLog.Id = uuid.NewV4().String()
|
||||
service.MyService.Notify().AddLog(installLog)
|
||||
// installLog := model2.AppNotify{}
|
||||
// installLog.State = 0
|
||||
// installLog.CustomId = m.Label
|
||||
// installLog.Message = "installing rely"
|
||||
// installLog.Class = types.NOTIFY_APP
|
||||
// installLog.Type = types.NOTIFY_TYPE_UNIMPORTANT
|
||||
// installLog.CreatedAt = strconv.FormatInt(time.Now().Unix(), 10)
|
||||
// installLog.UpdatedAt = strconv.FormatInt(time.Now().Unix(), 10)
|
||||
// installLog.Id = uuid.NewV4().String()
|
||||
// service.MyService.Notify().AddLog(installLog)
|
||||
if m.Origin != "custom" {
|
||||
for _, plugin := range appInfo.Plugins {
|
||||
if plugin == "mysql" {
|
||||
@@ -314,24 +295,26 @@ func InstallApp(c *gin.Context) {
|
||||
|
||||
} else {
|
||||
docker_base.MysqlDelete(mysqlContainerId)
|
||||
installLog.State = 0
|
||||
installLog.Message = err.Error()
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
// installLog.State = 0
|
||||
// installLog.Message = err.Error()
|
||||
// service.MyService.Notify().UpdateLog(installLog)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
installLog.Message = "pulling"
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
|
||||
// step:下载镜像
|
||||
err := service.MyService.Docker().DockerPullImage(dockerImage+":"+dockerImageVersion, installLog)
|
||||
err := service.MyService.Docker().DockerPullImage(dockerImage+":"+dockerImageVersion, m.Icon, m.Label)
|
||||
if err != nil {
|
||||
installLog.State = 0
|
||||
installLog.Message = err.Error()
|
||||
installLog.Type = types.NOTIFY_TYPE_ERROR
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
notify := notify.Application{}
|
||||
notify.Icon = m.Icon
|
||||
notify.Name = m.Label
|
||||
notify.State = "PULLING"
|
||||
notify.Type = "INSTALL"
|
||||
notify.Success = false
|
||||
notify.Finished = false
|
||||
notify.Message = err.Error()
|
||||
service.MyService.Notify().SendInstallAppBySocket(notify)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -339,35 +322,28 @@ func InstallApp(c *gin.Context) {
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
//if {
|
||||
|
||||
//}
|
||||
|
||||
//step:创建容器
|
||||
// networkName, err := service.MyService.Docker().GetNetWorkNameByNetWorkID(appInfo.NetworkModel)
|
||||
// if err != nil {
|
||||
// //service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":80}", 100)
|
||||
// installLog.State = 0
|
||||
// installLog.Speed = 75
|
||||
// installLog.Type = types.NOTIFY_TYPE_ERROR
|
||||
// installLog.Message = err.Error()
|
||||
// service.MyService.Notify().UpdateLog(installLog)
|
||||
// return
|
||||
// }
|
||||
containerId, err := service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m, appInfo.NetworkModel)
|
||||
installLog.Name = appInfo.Title
|
||||
installLog.Icon = appInfo.Icon
|
||||
_, err = service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m)
|
||||
if err != nil {
|
||||
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":80}", 100)
|
||||
installLog.State = 0
|
||||
installLog.Type = types.NOTIFY_TYPE_ERROR
|
||||
installLog.Message = err.Error()
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
notify := notify.Application{}
|
||||
notify.Icon = m.Icon
|
||||
notify.Name = m.Label
|
||||
notify.State = "STARTING"
|
||||
notify.Type = "INSTALL"
|
||||
notify.Success = false
|
||||
notify.Finished = false
|
||||
notify.Message = err.Error()
|
||||
service.MyService.Notify().SendInstallAppBySocket(notify)
|
||||
return
|
||||
} else {
|
||||
//service.MyService.Redis().Set(id, "{\"id\":\""+id+"\",\"state\":true,\"message\":\"starting\",\"speed\":80}", 100)
|
||||
installLog.Message = "starting"
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
notify := notify.Application{}
|
||||
notify.Icon = m.Icon
|
||||
notify.Name = m.Label
|
||||
notify.State = "STARTING"
|
||||
notify.Type = "INSTALL"
|
||||
notify.Success = true
|
||||
notify.Finished = false
|
||||
service.MyService.Notify().SendInstallAppBySocket(notify)
|
||||
}
|
||||
|
||||
// echo -e "hellow\nworld" >>
|
||||
@@ -376,143 +352,60 @@ func InstallApp(c *gin.Context) {
|
||||
err = service.MyService.Docker().DockerContainerStart(m.Label)
|
||||
if err != nil {
|
||||
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":90}", 100)
|
||||
installLog.State = 0
|
||||
installLog.Type = types.NOTIFY_TYPE_ERROR
|
||||
installLog.Message = err.Error()
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
notify := notify.Application{}
|
||||
notify.Icon = m.Icon
|
||||
notify.Name = m.Label
|
||||
notify.State = "STARTING"
|
||||
notify.Type = "INSTALL"
|
||||
notify.Success = false
|
||||
notify.Finished = false
|
||||
notify.Message = err.Error()
|
||||
service.MyService.Notify().SendInstallAppBySocket(notify)
|
||||
return
|
||||
} else {
|
||||
//service.MyService.Redis().Set(id, "{\"id\":\""+id+"\",\"state\":true,\"message\":\"setting upnp\",\"speed\":90}", 100)
|
||||
if m.Origin != CUSTOM {
|
||||
installLog.Message = "setting upnp"
|
||||
} else {
|
||||
installLog.Message = "nearing completion"
|
||||
}
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
}
|
||||
|
||||
if m.Origin != CUSTOM {
|
||||
//step:启动upnp
|
||||
if m.EnableUPNP {
|
||||
upnp, err := upnp2.Gateway()
|
||||
if err == nil {
|
||||
for _, p := range m.Ports {
|
||||
if p.Protocol == "udp" {
|
||||
upnp.CtrlUrl = upnp2.GetCtrlUrl(upnp.GatewayHost, upnp.DeviceDescUrl)
|
||||
upnp.LocalHost = ip_helper2.GetLoclIp()
|
||||
tComment, _ := strconv.Atoi(p.CommendPort)
|
||||
upnp.AddPortMapping(tComment, tComment, "UDP")
|
||||
time.Sleep(time.Millisecond * 200)
|
||||
} else if p.Protocol == "tcp" {
|
||||
upnp.CtrlUrl = upnp2.GetCtrlUrl(upnp.GatewayHost, upnp.DeviceDescUrl)
|
||||
upnp.LocalHost = ip_helper2.GetLoclIp()
|
||||
tComment, _ := strconv.Atoi(p.CommendPort)
|
||||
upnp.AddPortMapping(tComment, tComment, "TCP")
|
||||
time.Sleep(time.Millisecond * 200)
|
||||
} else if p.Protocol == "both" {
|
||||
|
||||
upnp.CtrlUrl = upnp2.GetCtrlUrl(upnp.GatewayHost, upnp.DeviceDescUrl)
|
||||
upnp.LocalHost = ip_helper2.GetLoclIp()
|
||||
tComment, _ := strconv.Atoi(p.CommendPort)
|
||||
upnp.AddPortMapping(tComment, tComment, "UDP")
|
||||
time.Sleep(time.Millisecond * 200)
|
||||
|
||||
upnp.AddPortMapping(tComment, tComment, "TCP")
|
||||
time.Sleep(time.Millisecond * 200)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
if err != nil {
|
||||
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":95}", 100)
|
||||
installLog.State = 0
|
||||
installLog.Type = types.NOTIFY_TYPE_ERROR
|
||||
installLog.Message = err.Error()
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
} else {
|
||||
//service.MyService.Redis().Set(id, "{\"id\":\""+id+"\",\"state\":true,\"message\":\"checking\",\"speed\":95}", 100)
|
||||
installLog.Message = "checking"
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
}
|
||||
}
|
||||
// if m.Origin != CUSTOM {
|
||||
// installLog.Message = "setting upnp"
|
||||
// } else {
|
||||
// installLog.Message = "nearing completion"
|
||||
// }
|
||||
// service.MyService.Notify().UpdateLog(installLog)
|
||||
}
|
||||
|
||||
//step: 启动成功 检查容器状态确认启动成功
|
||||
container, err := service.MyService.Docker().DockerContainerInfo(m.Label)
|
||||
if err != nil && container.ContainerJSONBase.State.Running {
|
||||
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":100}", 100)
|
||||
installLog.State = 0
|
||||
installLog.Type = types.NOTIFY_TYPE_ERROR
|
||||
installLog.Message = err.Error()
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
notify := notify.Application{}
|
||||
notify.Icon = m.Icon
|
||||
notify.Name = m.Label
|
||||
notify.State = "INSTALLED"
|
||||
notify.Type = "INSTALL"
|
||||
notify.Success = false
|
||||
notify.Finished = true
|
||||
notify.Message = err.Error()
|
||||
service.MyService.Notify().SendInstallAppBySocket(notify)
|
||||
return
|
||||
} else {
|
||||
//service.MyService.Redis().Set(id, "{\"id\":\""+id+"\",\"state\":true,\"message\":\"installed\",\"speed\":100}", 100)
|
||||
installLog.Message = "installed"
|
||||
service.MyService.Notify().UpdateLog(installLog)
|
||||
notify := notify.Application{}
|
||||
notify.Icon = m.Icon
|
||||
notify.Name = m.Label
|
||||
notify.State = "INSTALLED"
|
||||
notify.Type = "INSTALL"
|
||||
notify.Success = true
|
||||
notify.Finished = true
|
||||
service.MyService.Notify().SendInstallAppBySocket(notify)
|
||||
}
|
||||
|
||||
rely := model.MapStrings{}
|
||||
|
||||
copier.Copy(&rely, &relyMap)
|
||||
// if m.Origin != "custom" {
|
||||
// for i := 0; i < len(m.Volumes); i++ {
|
||||
// m.Volumes[i].Path = docker.GetDir(id, m.Volumes[i].Path)
|
||||
// }
|
||||
// }
|
||||
|
||||
portsStr, _ := json2.Marshal(m.Ports)
|
||||
envsStr, _ := json2.Marshal(m.Envs)
|
||||
volumesStr, _ := json2.Marshal(m.Volumes)
|
||||
devicesStr, _ := json2.Marshal(m.Devices)
|
||||
cmd, _ := json2.Marshal(m.Cmd)
|
||||
capAdd, _ := json.Marshal(m.CapAdd)
|
||||
//step: 保存数据到数据库
|
||||
md := model2.AppListDBModel{
|
||||
CustomId: "",
|
||||
Title: appInfo.Title,
|
||||
//ScreenshotLink: appInfo.ScreenshotLink,
|
||||
Slogan: appInfo.Tagline,
|
||||
Description: appInfo.Description,
|
||||
//Tags: appInfo.Tags,
|
||||
Icon: appInfo.Icon,
|
||||
Version: dockerImageVersion,
|
||||
ContainerId: containerId,
|
||||
Image: dockerImage,
|
||||
Index: appInfo.Index,
|
||||
//Port: m.Port,
|
||||
PortMap: m.PortMap,
|
||||
Label: m.Label,
|
||||
EnableUPNP: m.EnableUPNP,
|
||||
Ports: string(portsStr),
|
||||
Envs: string(envsStr),
|
||||
Volumes: string(volumesStr),
|
||||
Position: m.Position,
|
||||
NetModel: appInfo.NetworkModel,
|
||||
Restart: m.Restart,
|
||||
CpuShares: m.CpuShares,
|
||||
Memory: m.Memory,
|
||||
Devices: string(devicesStr),
|
||||
//Rely: rely,
|
||||
Origin: m.Origin,
|
||||
CreatedAt: strconv.FormatInt(time.Now().Unix(), 10),
|
||||
UpdatedAt: strconv.FormatInt(time.Now().Unix(), 10),
|
||||
Cmd: string(cmd),
|
||||
CapAdd: string(capAdd),
|
||||
HostName: m.HostName,
|
||||
Privileged: m.Privileged,
|
||||
}
|
||||
//if appInfo.NetworkModel == "host" {
|
||||
// m.PortMap = m.Port
|
||||
//}
|
||||
fmt.Println(md)
|
||||
//service.MyService.App().SaveContainer(md)
|
||||
config.CasaOSGlobalVariables.AppChange = true
|
||||
|
||||
}()
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: m.Label})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m.Label})
|
||||
|
||||
}
|
||||
|
||||
@@ -536,7 +429,7 @@ func InstallApp(c *gin.Context) {
|
||||
// c.BindJSON(&m)
|
||||
// //检查端口
|
||||
// if len(m.PortMap) == 0 || m.PortMap == "0" {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
// return
|
||||
// }
|
||||
// if len(m.Port) == 0 || m.Port == "0" {
|
||||
@@ -545,14 +438,14 @@ func InstallApp(c *gin.Context) {
|
||||
//
|
||||
// portMap, _ := strconv.Atoi(m.PortMap)
|
||||
// if !port2.IsPortAvailable(portMap, "tcp") {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + m.PortMap})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + m.PortMap})
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// for _, u := range m.Udp {
|
||||
// t, _ := strconv.Atoi(u.CommendPort)
|
||||
// if !port2.IsPortAvailable(t, "udp") {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
@@ -560,7 +453,7 @@ func InstallApp(c *gin.Context) {
|
||||
// for _, t := range m.Tcp {
|
||||
// te, _ := strconv.Atoi(t.CommendPort)
|
||||
// if !port2.IsPortAvailable(te, "tcp") {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + t.CommendPort})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + t.CommendPort})
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
@@ -577,7 +470,7 @@ func InstallApp(c *gin.Context) {
|
||||
//
|
||||
// err := service.MyService.Docker().DockerPullImage(m.Image)
|
||||
// if err != nil {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PULL_IMAGE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PULL_IMAGE_ERROR)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.PULL_IMAGE_ERROR, Message: common_err.GetMsg(common_err.PULL_IMAGE_ERROR)})
|
||||
// }
|
||||
//
|
||||
// id := uuid.NewV4().String()
|
||||
@@ -694,7 +587,7 @@ func InstallApp(c *gin.Context) {
|
||||
//
|
||||
// }()
|
||||
//
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: id})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: id})
|
||||
//
|
||||
//}
|
||||
|
||||
@@ -710,43 +603,39 @@ func UnInstallApp(c *gin.Context) {
|
||||
appId := c.Param("id")
|
||||
|
||||
if len(appId) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, 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: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
//step:停止容器
|
||||
err = service.MyService.Docker().DockerContainerStop(appId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.UNINSTALL_APP_ERROR, Message: oasis_err2.GetMsg(oasis_err2.UNINSTALL_APP_ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.UNINSTALL_APP_ERROR, Message: common_err.GetMsg(common_err.UNINSTALL_APP_ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
//step:删除容器
|
||||
err = service.MyService.Docker().DockerContainerRemove(appId, false)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.UNINSTALL_APP_ERROR, Message: oasis_err2.GetMsg(oasis_err2.UNINSTALL_APP_ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.UNINSTALL_APP_ERROR, Message: common_err.GetMsg(common_err.UNINSTALL_APP_ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
//存在镜像正在使用的情况
|
||||
// step:删除镜像
|
||||
service.MyService.Docker().DockerImageRemove(info.Image)
|
||||
// step:remove image
|
||||
service.MyService.Docker().DockerImageRemove(info.Config.Image)
|
||||
|
||||
//step: 删除本地数据
|
||||
//service.MyService.App().RemoveContainerById(appId)
|
||||
if info.Config.Labels["origin"] != "custom" {
|
||||
fmt.Println(info.HostConfig.Mounts)
|
||||
//step: 删除文件夹
|
||||
for _, v := range info.HostConfig.Mounts {
|
||||
for _, v := range info.Mounts {
|
||||
if strings.Contains(v.Source, info.Name) {
|
||||
service.MyService.App().DelAppConfigDir(v.Source)
|
||||
path := filepath.Join(strings.Split(v.Source, info.Name)[0], info.Name)
|
||||
service.MyService.App().DelAppConfigDir(path)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -791,14 +680,15 @@ func UnInstallApp(c *gin.Context) {
|
||||
//}
|
||||
}
|
||||
config.CasaOSGlobalVariables.AppChange = true
|
||||
unInstallLog := model2.AppNotify{}
|
||||
unInstallLog.State = 0
|
||||
unInstallLog.CustomId = appId
|
||||
unInstallLog.Message = "uninstalled"
|
||||
unInstallLog.Id = uuid.NewV4().String()
|
||||
service.MyService.Notify().UpdateLog(unInstallLog)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
notify := notify.Application{}
|
||||
notify.Icon = info.Config.Labels["icon"]
|
||||
notify.Name = strings.ReplaceAll(info.Name, "/", "")
|
||||
notify.State = "FINISHED"
|
||||
notify.Type = "UNINSTALL"
|
||||
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)})
|
||||
|
||||
}
|
||||
|
||||
@@ -824,15 +714,15 @@ func ChangAppState(c *gin.Context) {
|
||||
err = service.MyService.Docker().DockerContainerStart(appId)
|
||||
}
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
info, err := service.MyService.App().GetContainerInfo(appId)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: info.State})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: info.State})
|
||||
}
|
||||
|
||||
// @Summary 查看容器日志
|
||||
@@ -846,21 +736,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: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: log})
|
||||
}
|
||||
|
||||
// @Summary 获取安装进度
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags app
|
||||
// @Param id path string true "容器id"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /app/speed/{id} [get]
|
||||
func GetInstallSpeed(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
b := service.MyService.Notify().GetLog(id)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: b})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: log})
|
||||
}
|
||||
|
||||
// @Summary 获取容器状态
|
||||
@@ -877,7 +753,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: oasis_err2.ERROR, Message: e.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: e.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -890,7 +766,7 @@ func GetContainerState(c *gin.Context) {
|
||||
data["app"] = appInfo
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary 更新设置
|
||||
@@ -913,7 +789,7 @@ func UpdateSetting(c *gin.Context) {
|
||||
c.BindJSON(&m)
|
||||
|
||||
if len(id) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
//var cpd model.CustomizationPostData
|
||||
@@ -925,7 +801,7 @@ func UpdateSetting(c *gin.Context) {
|
||||
|
||||
// //check app name is exist
|
||||
// if _, err := service.MyService.Docker().DockerListByName(m.Label); err == nil {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR_APP_NAME_EXIST, Message: oasis_err2.GetMsg(oasis_err2.ERROR_APP_NAME_EXIST)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR_APP_NAME_EXIST, Message: common_err.GetMsg(common_err.ERROR_APP_NAME_EXIST)})
|
||||
// return
|
||||
// }
|
||||
|
||||
@@ -933,7 +809,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: oasis_err2.ERROR, Message: "Duplicate port:" + m.PortMap})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + m.PortMap})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -943,28 +819,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: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.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: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.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: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.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: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: "Duplicate port:" + u.CommendPort})
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -973,11 +849,11 @@ func UpdateSetting(c *gin.Context) {
|
||||
service.MyService.Docker().DockerContainerUpdateName(id, id)
|
||||
//service.MyService.Docker().DockerContainerRemove(id, true)
|
||||
|
||||
containerId, err := service.MyService.Docker().DockerContainerCreate(m.Image, m, m.NetworkModel)
|
||||
containerId, err := service.MyService.Docker().DockerContainerCreate(m.Image, m)
|
||||
if err != nil {
|
||||
service.MyService.Docker().DockerContainerUpdateName(m.Label, id)
|
||||
service.MyService.Docker().DockerContainerStart(id)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)})
|
||||
return
|
||||
}
|
||||
// echo -e "hellow\nworld" >>
|
||||
@@ -986,7 +862,7 @@ func UpdateSetting(c *gin.Context) {
|
||||
err = service.MyService.Docker().DockerContainerStart(containerId)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)})
|
||||
return
|
||||
}
|
||||
service.MyService.Docker().DockerContainerRemove(id, true)
|
||||
@@ -1057,7 +933,7 @@ func UpdateSetting(c *gin.Context) {
|
||||
|
||||
//service.MyService.App().UpdateApp(appInfo)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary update app version
|
||||
@@ -1072,20 +948,20 @@ func PutAppUpdate(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
|
||||
if len(id) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, 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: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
|
||||
}
|
||||
imageLatest := strings.Split(inspect.Config.Image, ":")[0] + ":latest"
|
||||
err = service.MyService.Docker().DockerPullImage(imageLatest, model2.AppNotify{})
|
||||
err = service.MyService.Docker().DockerPullImage(imageLatest, "", "")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
|
||||
}
|
||||
@@ -1098,7 +974,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: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1106,43 +982,13 @@ func PutAppUpdate(c *gin.Context) {
|
||||
err = service.MyService.Docker().DockerContainerStart(containerId)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)})
|
||||
return
|
||||
}
|
||||
service.MyService.Docker().DockerContainerRemove(id, true)
|
||||
delete(service.NewVersionApp, id)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary get app index
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags app
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /app/order [get]
|
||||
func GetAppOrder(c *gin.Context) {
|
||||
data := service.MyService.System().GetAppOrderFile()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: json.RawMessage(data)})
|
||||
}
|
||||
|
||||
// @Summary update app index
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags app
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /app/order [post]
|
||||
func PostAppOrder(c *gin.Context) {
|
||||
data := c.PostForm("data")
|
||||
service.MyService.System().UpAppOrderFile(data)
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Data: json.RawMessage(data),
|
||||
})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary 获取容器详情
|
||||
@@ -1158,7 +1004,7 @@ func ContainerInfo(c *gin.Context) {
|
||||
appInfo := service.MyService.App().GetAppDBInfo(appId)
|
||||
containerInfo, _ := service.MyService.Docker().DockerContainerStats(appId)
|
||||
var cpuModel = "arm"
|
||||
if cpu := service.MyService.ZiMa().GetCpuInfo(); len(cpu) > 0 {
|
||||
if cpu := service.MyService.System().GetCpuInfo(); len(cpu) > 0 {
|
||||
if strings.Count(strings.ToLower(strings.TrimSpace(cpu[0].ModelName)), "intel") > 0 {
|
||||
cpuModel = "intel"
|
||||
} else if strings.Count(strings.ToLower(strings.TrimSpace(cpu[0].ModelName)), "amd") > 0 {
|
||||
@@ -1169,7 +1015,7 @@ func ContainerInfo(c *gin.Context) {
|
||||
info, err := service.MyService.Docker().DockerContainerInfo(appId)
|
||||
if err != nil {
|
||||
//todo 需要自定义错误
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
con := struct {
|
||||
@@ -1182,10 +1028,10 @@ func ContainerInfo(c *gin.Context) {
|
||||
data := make(map[string]interface{}, 5)
|
||||
data["app"] = appInfo
|
||||
data["cpu"] = cpuModel
|
||||
data["memory"] = service.MyService.ZiMa().GetMemInfo().Total
|
||||
data["memory"] = service.MyService.System().GetMemInfo()["total"]
|
||||
data["container"] = json2.RawMessage(containerInfo)
|
||||
data["info"] = con
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary 获取安装所需要的数据
|
||||
@@ -1205,8 +1051,8 @@ func GetDockerInstallConfig(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
data["networks"] = list
|
||||
data["memory"] = service.MyService.ZiMa().GetMemInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
data["memory"] = service.MyService.System().GetMemInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary 获取依赖数据
|
||||
@@ -1220,7 +1066,7 @@ func GetDockerInstallConfig(c *gin.Context) {
|
||||
func ContainerRelyInfo(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
appInfo := service.MyService.Rely().GetInfo(id)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: appInfo})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: appInfo})
|
||||
}
|
||||
|
||||
// @Summary 获取可更新数据
|
||||
@@ -1236,8 +1082,8 @@ func ContainerUpdateInfo(c *gin.Context) {
|
||||
//appInfo := service.MyService.App().GetAppDBInfo(appId)
|
||||
info, err := service.MyService.Docker().DockerContainerInfo(appId)
|
||||
if err != nil {
|
||||
//todo 需要自定义错误
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: err.Error()})
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
var port model.PortArray
|
||||
@@ -1256,13 +1102,31 @@ func ContainerUpdateInfo(c *gin.Context) {
|
||||
var envs model.EnvArray
|
||||
// json2.Unmarshal([]byte(appInfo.Envs), &envs)
|
||||
|
||||
for _, v := range info.Config.Env {
|
||||
|
||||
temp := model.Env{
|
||||
Name: strings.Split(v, "=")[0],
|
||||
Value: strings.Split(v, "=")[1],
|
||||
showENV := info.Config.Labels["show_env"]
|
||||
showENVList := strings.Split(showENV, ",")
|
||||
showENVMap := make(map[string]string)
|
||||
if len(showENVList) > 1 {
|
||||
for _, name := range showENVList {
|
||||
showENVMap[name] = "1"
|
||||
}
|
||||
envs = append(envs, temp)
|
||||
}
|
||||
for _, v := range info.Config.Env {
|
||||
if len(showENVList) > 1 {
|
||||
if _, ok := showENVMap[strings.Split(v, "=")[0]]; ok {
|
||||
temp := model.Env{
|
||||
Name: strings.Split(v, "=")[0],
|
||||
Value: strings.Split(v, "=")[1],
|
||||
}
|
||||
envs = append(envs, temp)
|
||||
}
|
||||
} else {
|
||||
temp := model.Env{
|
||||
Name: strings.Split(v, "=")[0],
|
||||
Value: strings.Split(v, "=")[1],
|
||||
}
|
||||
envs = append(envs, temp)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var vol model.PathArray
|
||||
@@ -1309,6 +1173,7 @@ func ContainerUpdateInfo(c *gin.Context) {
|
||||
m.Index = info.Config.Labels["index"]
|
||||
m.Position = false
|
||||
m.CustomId = info.Config.Labels["custom_id"]
|
||||
m.Host = info.Config.Labels["host"]
|
||||
if len(m.CustomId) == 0 {
|
||||
m.CustomId = uuid.NewV4().String()
|
||||
}
|
||||
@@ -1317,7 +1182,12 @@ func ContainerUpdateInfo(c *gin.Context) {
|
||||
m.HostName = info.Config.Hostname
|
||||
m.Privileged = info.HostConfig.Privileged
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: m})
|
||||
m.Protocol = info.Config.Labels["protocol"]
|
||||
if m.Protocol == "" {
|
||||
m.Protocol = "http"
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m})
|
||||
}
|
||||
|
||||
////准备安装(暂时不需要)
|
||||
@@ -1368,5 +1238,5 @@ func ContainerUpdateInfo(c *gin.Context) {
|
||||
// }
|
||||
// data["udp"] = inarr
|
||||
// }
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
//}
|
||||
|
||||
453
route/v1/file.go
453
route/v1/file.go
@@ -6,20 +6,24 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
url2 "net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/spf13/afero"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
)
|
||||
|
||||
func downloadReadFile(c *gin.Context) {
|
||||
@@ -48,24 +52,6 @@ func downloadReadFile(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func downloadWriteFile(c *gin.Context) {
|
||||
//写文件
|
||||
var filename = "./output1.csv"
|
||||
|
||||
file, err := os.Create(filename) //创建文件
|
||||
if err != nil {
|
||||
c.String(400, err.Error())
|
||||
return
|
||||
}
|
||||
buf := bufio.NewWriter(file) //创建新的 Writer 对象
|
||||
buf.WriteString("test")
|
||||
buf.Flush()
|
||||
defer file.Close()
|
||||
|
||||
//返回文件流
|
||||
c.File(filename)
|
||||
}
|
||||
|
||||
// @Summary 读取文件
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
@@ -78,15 +64,15 @@ func GetFilerContent(c *gin.Context) {
|
||||
filePath := c.Query("path")
|
||||
if len(filePath) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.INVALID_PARAMS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS),
|
||||
Success: common_err.INVALID_PARAMS,
|
||||
Message: common_err.GetMsg(common_err.INVALID_PARAMS),
|
||||
})
|
||||
return
|
||||
}
|
||||
if !file.Exists(filePath) {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.FILE_DOES_NOT_EXIST,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST),
|
||||
Success: common_err.FILE_DOES_NOT_EXIST,
|
||||
Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -94,8 +80,8 @@ func GetFilerContent(c *gin.Context) {
|
||||
info, err := ioutil.ReadFile(filePath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.FILE_READ_ERROR,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.FILE_READ_ERROR),
|
||||
Success: common_err.FILE_READ_ERROR,
|
||||
Message: common_err.GetMsg(common_err.FILE_READ_ERROR),
|
||||
Data: err.Error(),
|
||||
})
|
||||
return
|
||||
@@ -104,8 +90,8 @@ func GetFilerContent(c *gin.Context) {
|
||||
|
||||
//返回结果
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: result,
|
||||
})
|
||||
}
|
||||
@@ -114,15 +100,15 @@ func GetLocalFile(c *gin.Context) {
|
||||
path := c.Query("path")
|
||||
if len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.INVALID_PARAMS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS),
|
||||
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: oasis_err2.FILE_DOES_NOT_EXIST,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST),
|
||||
Success: common_err.FILE_DOES_NOT_EXIST,
|
||||
Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -135,82 +121,106 @@ func GetLocalFile(c *gin.Context) {
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path query string true "path of file"
|
||||
// @Param t query string false "Compression format" Enums(zip,tar,targz)
|
||||
// @Param files query string true "file list eg: filename1,filename2,filename3 "
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/download [get]
|
||||
func GetDownloadFile(c *gin.Context) {
|
||||
filePath := c.Query("path")
|
||||
if len(filePath) == 0 {
|
||||
|
||||
t := c.Query("t")
|
||||
|
||||
files := c.Query("files")
|
||||
|
||||
if len(files) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.INVALID_PARAMS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS),
|
||||
Success: common_err.INVALID_PARAMS,
|
||||
Message: common_err.GetMsg(common_err.INVALID_PARAMS),
|
||||
})
|
||||
return
|
||||
}
|
||||
if !file.Exists(filePath) {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.FILE_DOES_NOT_EXIST,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST),
|
||||
})
|
||||
return
|
||||
list := strings.Split(files, ",")
|
||||
for _, v := range list {
|
||||
if !file.Exists(v) {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: common_err.FILE_DOES_NOT_EXIST,
|
||||
Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
//打开文件
|
||||
fileTmp, _ := os.Open(filePath)
|
||||
defer fileTmp.Close()
|
||||
//获取文件的名称
|
||||
fileName := path.Base(filePath)
|
||||
c.Header("Content-Type", "application/octet-stream")
|
||||
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
|
||||
c.Header("Content-Transfer-Encoding", "binary")
|
||||
c.Header("Cache-Control", "no-cache")
|
||||
// handles only single files not folders and multiple files
|
||||
if len(list) == 1 {
|
||||
|
||||
filePath := list[0]
|
||||
info, err := os.Stat(filePath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: common_err.FILE_DOES_NOT_EXIST,
|
||||
Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
|
||||
})
|
||||
return
|
||||
}
|
||||
if !info.IsDir() {
|
||||
|
||||
//打开文件
|
||||
fileTmp, _ := os.Open(filePath)
|
||||
defer fileTmp.Close()
|
||||
|
||||
//获取文件的名称
|
||||
fileName := path.Base(filePath)
|
||||
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
|
||||
c.File(filePath)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
extension, ar, err := file.GetCompressionAlgorithm(t)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: common_err.INVALID_PARAMS,
|
||||
Message: common_err.GetMsg(common_err.INVALID_PARAMS),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
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),
|
||||
Data: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
defer ar.Close()
|
||||
commonDir := file.CommonPrefix(filepath.Separator, list...)
|
||||
|
||||
currentPath := filepath.Base(commonDir)
|
||||
|
||||
name := "_" + currentPath
|
||||
name += extension
|
||||
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(name))
|
||||
for _, fname := range list {
|
||||
err = file.AddFile(ar, fname, commonDir)
|
||||
if err != nil {
|
||||
log.Printf("Failed to archive %s: %v", fname, err)
|
||||
}
|
||||
}
|
||||
|
||||
c.File(filePath)
|
||||
}
|
||||
|
||||
// @Summary download
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path query string true "path of file"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/new/download [get]
|
||||
func GetFileDownloadNew(c *gin.Context) {
|
||||
filePath := c.Query("path")
|
||||
if len(filePath) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.INVALID_PARAMS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS),
|
||||
})
|
||||
return
|
||||
}
|
||||
if !file.Exists(filePath) {
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err2.FILE_DOES_NOT_EXIST,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST),
|
||||
})
|
||||
return
|
||||
}
|
||||
//打开文件
|
||||
fileStat, _ := os.Stat(filePath)
|
||||
var AppFs = afero.NewOsFs()
|
||||
fileT, _ := AppFs.Open(filePath)
|
||||
//fileTmp, _ := os.Open(filePath)
|
||||
//defer fileTmp.Close()
|
||||
//获取文件的名称
|
||||
//fileName := path.Base(filePath)
|
||||
func GetDownloadSingleFile(c *gin.Context) {
|
||||
filePath := c.Param("path")
|
||||
fileTmp, _ := os.Open(filePath)
|
||||
defer fileTmp.Close()
|
||||
|
||||
//c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
|
||||
//在线
|
||||
fileName := path.Base(filePath)
|
||||
//c.Header("Content-Disposition", "inline")
|
||||
// extraHeaders := map[string]string{
|
||||
// "Content-Disposition": `attachment; filename="` + url2.PathEscape(fileName) + `"`,
|
||||
// }
|
||||
|
||||
//c.Header("Cache-Control", "private")
|
||||
//c.Header("Content-Type", "application/octet-stream")
|
||||
|
||||
http.ServeContent(c.Writer, c.Request, fileStat.Name(), fileStat.ModTime(), fileT)
|
||||
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
|
||||
c.File(filePath)
|
||||
}
|
||||
|
||||
// @Summary 获取目录列表
|
||||
@@ -223,7 +233,7 @@ func GetFileDownloadNew(c *gin.Context) {
|
||||
// @Router /file/dirpath [get]
|
||||
func DirPath(c *gin.Context) {
|
||||
path := c.DefaultQuery("path", "")
|
||||
info := service.MyService.ZiMa().GetDirPath(path)
|
||||
info := service.MyService.System().GetDirPath(path)
|
||||
if path == "/DATA/AppData" {
|
||||
list := service.MyService.Docker().DockerContainerList()
|
||||
apps := make(map[string]string, len(list))
|
||||
@@ -264,7 +274,30 @@ func DirPath(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: info})
|
||||
//Hide the files or folders in operation
|
||||
fileQueue := make(map[string]string)
|
||||
if len(service.OpStrArr) > 0 {
|
||||
for _, v := range service.OpStrArr {
|
||||
v, ok := service.FileQueue.Load(v)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
vt := v.(model.FileOperate)
|
||||
for _, i := range vt.Item {
|
||||
lastPath := i.From[strings.LastIndex(i.From, "/")+1:]
|
||||
fileQueue[vt.To+"/"+lastPath] = i.From
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pathList := []model.Path{}
|
||||
for i := 0; i < len(info); i++ {
|
||||
if _, ok := fileQueue[info[i].Path]; !ok {
|
||||
pathList = append(pathList, info[i])
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: pathList})
|
||||
}
|
||||
|
||||
// @Summary rename file or dir
|
||||
@@ -272,62 +305,78 @@ func DirPath(c *gin.Context) {
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param oldpath formData string true "path of old"
|
||||
// @Param newpath formData string true "path of new"
|
||||
// @Param oldpath body string true "path of old"
|
||||
// @Param newpath body string true "path of new"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/rename [put]
|
||||
func RenamePath(c *gin.Context) {
|
||||
op := c.PostForm("oldpath")
|
||||
np := c.PostForm("newpath")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
op := json["oldpath"]
|
||||
np := json["newpath"]
|
||||
if len(op) == 0 || len(np) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
success, err := service.MyService.ZiMa().RenameFile(op, np)
|
||||
c.JSON(http.StatusOK, model.Result{Success: success, Message: oasis_err2.GetMsg(success), Data: err})
|
||||
success, err := service.MyService.System().RenameFile(op, np)
|
||||
c.JSON(http.StatusOK, model.Result{Success: success, Message: common_err.GetMsg(success), Data: err})
|
||||
}
|
||||
|
||||
// @Summary create folder
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path formData string true "path of folder"
|
||||
// @Param path body string true "path of folder"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/mkdir [post]
|
||||
func MkdirAll(c *gin.Context) {
|
||||
path := c.PostForm("path")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
path := json["path"]
|
||||
var code int
|
||||
if len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
code, _ = service.MyService.ZiMa().MkdirAll(path)
|
||||
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)})
|
||||
// decodedPath, err := url.QueryUnescape(path)
|
||||
// if err != nil {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
// return
|
||||
// }
|
||||
code, _ = service.MyService.System().MkdirAll(path)
|
||||
c.JSON(http.StatusOK, model.Result{Success: code, Message: common_err.GetMsg(code)})
|
||||
}
|
||||
|
||||
// @Summary create file
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path formData string false "路径"
|
||||
// @Param path body string true "path of folder (path need to url encode)"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/create [post]
|
||||
func PostCreateFile(c *gin.Context) {
|
||||
path := c.PostForm("path")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
path := json["path"]
|
||||
var code int
|
||||
if len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
code, _ = service.MyService.ZiMa().CreateFile(path)
|
||||
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)})
|
||||
// decodedPath, err := url.QueryUnescape(path)
|
||||
// if err != nil {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
// return
|
||||
// }
|
||||
code, _ = service.MyService.System().CreateFile(path)
|
||||
c.JSON(http.StatusOK, model.Result{Success: code, Message: common_err.GetMsg(code)})
|
||||
}
|
||||
|
||||
// @Summary upload file
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path formData string false "file path"
|
||||
@@ -343,7 +392,7 @@ func GetFileUpload(c *gin.Context) {
|
||||
path := c.Query("path")
|
||||
dirPath := ""
|
||||
hash := file.GetHashByContent([]byte(fileName))
|
||||
tempDir := config.AppInfo.RootPath + "/temp/" + hash + strconv.Itoa(totalChunks) + "/"
|
||||
tempDir := config.AppInfo.TempPath + "/" + hash + strconv.Itoa(totalChunks) + "/"
|
||||
if fileName != relative {
|
||||
dirPath = strings.TrimSuffix(relative, fileName)
|
||||
tempDir += dirPath
|
||||
@@ -351,11 +400,11 @@ func GetFileUpload(c *gin.Context) {
|
||||
}
|
||||
tempDir += chunkNumber
|
||||
if !file.CheckNotExist(tempDir) {
|
||||
c.JSON(200, model.Result{Success: 200, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
|
||||
c.JSON(200, model.Result{Success: 200, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(204, model.Result{Success: 204, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(204, model.Result{Success: 204, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary upload file
|
||||
@@ -379,10 +428,10 @@ func PostFileUpload(c *gin.Context) {
|
||||
hash := file.GetHashByContent([]byte(fileName))
|
||||
|
||||
if len(path) == 0 {
|
||||
c.JSON(oasis_err2.INVALID_PARAMS, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(common_err.INVALID_PARAMS, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
tempDir := config.AppInfo.RootPath + "/temp/" + hash + strconv.Itoa(totalChunks) + "/"
|
||||
tempDir := config.AppInfo.TempPath + "/" + hash + strconv.Itoa(totalChunks) + "/"
|
||||
|
||||
if fileName != relative {
|
||||
dirPath = strings.TrimSuffix(relative, fileName)
|
||||
@@ -403,7 +452,7 @@ func PostFileUpload(c *gin.Context) {
|
||||
defer out.Close()
|
||||
_, err := io.Copy(out, f)
|
||||
if err != nil {
|
||||
c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
@@ -411,15 +460,15 @@ func PostFileUpload(c *gin.Context) {
|
||||
defer out.Close()
|
||||
_, err := io.Copy(out, f)
|
||||
if err != nil {
|
||||
c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
return
|
||||
}
|
||||
fileNum, err := ioutil.ReadDir(tempDir)
|
||||
if err != nil {
|
||||
c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
if totalChunks == len(fileNum) {
|
||||
@@ -427,101 +476,123 @@ func PostFileUpload(c *gin.Context) {
|
||||
file.RMDir(tempDir)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary copy or move file
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param from formData string true "from path"
|
||||
// @Param to formData string true "to path"
|
||||
// @Param type formData string true "action" Enums(move,copy)
|
||||
// @Param body body model.FileOperate true "type:move,copy"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/operate [post]
|
||||
func PostOperateFileOrDir(c *gin.Context) {
|
||||
from := c.PostForm("from")
|
||||
to := c.PostForm("to")
|
||||
t := c.PostForm("type")
|
||||
if len(from) == 0 || len(t) == 0 || len(to) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
|
||||
list := model.FileOperate{}
|
||||
c.BindJSON(&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)})
|
||||
return
|
||||
}
|
||||
if t == "move" {
|
||||
lastPath := from[strings.LastIndex(from, "/")+1:]
|
||||
if !file.CheckNotExist(to + "/" + lastPath) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_OR_DIR_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
|
||||
return
|
||||
}
|
||||
err := os.Rename(from, to+"/"+lastPath)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
} else if t == "copy" {
|
||||
err := file.CopyDir(from, to)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
} else {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
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)})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
|
||||
var total int64 = 0
|
||||
for i := 0; i < len(list.Item); i++ {
|
||||
|
||||
size, err := file.GetFileOrDirSize(list.Item[i].From)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
list.Item[i].Size = size
|
||||
total += size
|
||||
}
|
||||
|
||||
list.TotalSize = total
|
||||
list.ProcessedSize = 0
|
||||
|
||||
uid := uuid.NewV4().String()
|
||||
service.FileQueue.Store(uid, list)
|
||||
service.OpStrArr = append(service.OpStrArr, uid)
|
||||
|
||||
if len(service.OpStrArr) == 1 {
|
||||
go service.ExecOpFile()
|
||||
go service.CheckFileStatus()
|
||||
|
||||
go service.MyService.Notify().SendFileOperateNotify(false)
|
||||
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary delete file
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path query string true "path"
|
||||
// @Param body body string true "paths eg ["/a/b/c","/d/e/f"]"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/delete [delete]
|
||||
func DeleteFile(c *gin.Context) {
|
||||
path := c.Query("path")
|
||||
//err := os.Remove(path)
|
||||
err := os.RemoveAll(path)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_DELETE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.FILE_DELETE_ERROR), Data: err})
|
||||
|
||||
paths := []string{}
|
||||
c.BindJSON(&paths)
|
||||
if len(paths) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
// path := c.Query("path")
|
||||
|
||||
// paths := strings.Split(path, ",")
|
||||
|
||||
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})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary update file
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags file
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path formData string true "path"
|
||||
// @Param content formData string true "content"
|
||||
// @Param path body string true "path"
|
||||
// @Param content body string true "content"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /file/update [put]
|
||||
func PutFileContent(c *gin.Context) {
|
||||
path := c.PostForm("path")
|
||||
content := c.PostForm("content")
|
||||
if !file.Exists(path) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_ALREADY_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
|
||||
|
||||
fi := model.FileUpdate{}
|
||||
c.BindJSON(&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)})
|
||||
return
|
||||
}
|
||||
//err := os.Remove(path)
|
||||
err := os.RemoveAll(path)
|
||||
err := os.RemoveAll(fi.FilePath)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_DELETE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.FILE_DELETE_ERROR), Data: err})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.FILE_DELETE_ERROR, Message: common_err.GetMsg(common_err.FILE_DELETE_ERROR), Data: err})
|
||||
return
|
||||
}
|
||||
err = file.CreateFileAndWriteContent(path, content)
|
||||
err = file.CreateFileAndWriteContent(fi.FilePath, fi.FileContent)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary image thumbnail/original image
|
||||
@@ -537,13 +608,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: oasis_err2.FILE_ALREADY_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
|
||||
c.JSON(http.StatusInternalServerError, 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: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Writer.WriteString(string(f))
|
||||
@@ -551,14 +622,36 @@ func GetFileImage(c *gin.Context) {
|
||||
}
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := ioutil.ReadAll(f)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Writer.WriteString(string(data))
|
||||
}
|
||||
|
||||
func DeleteOperateFileOrDir(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "0" {
|
||||
service.FileQueue = sync.Map{}
|
||||
service.OpStrArr = []string{}
|
||||
} else {
|
||||
|
||||
service.FileQueue.Delete(id)
|
||||
tempList := []string{}
|
||||
for _, v := range service.OpStrArr {
|
||||
if v != id {
|
||||
tempList = append(tempList, v)
|
||||
}
|
||||
}
|
||||
service.OpStrArr = tempList
|
||||
|
||||
}
|
||||
|
||||
go service.MyService.Notify().SendFileOperateNotify(true)
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
@@ -17,9 +17,10 @@ import (
|
||||
natType "github.com/Curtis-Milo/nat-type-identifier-go"
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
@@ -40,18 +41,18 @@ func GetPersonReFile(c *gin.Context) {
|
||||
uid := c.Param("uuid")
|
||||
_, err := uuid.FromString(uid)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
task := service.MyService.Download().GetDownloadById(uid)
|
||||
if reflect.DeepEqual(task, model2.PersonDownloadDBModel{}) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_REMOTE_ERROR, Message: common_err.GetMsg(common_err.PERSON_REMOTE_ERROR)})
|
||||
return
|
||||
}
|
||||
token := task.From
|
||||
if _, ok := service.UDPAddressMap[token]; !ok {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_REMOTE_ERROR, Message: common_err.GetMsg(common_err.PERSON_REMOTE_ERROR)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -63,7 +64,7 @@ func GetPersonReFile(c *gin.Context) {
|
||||
m.UUId = uid
|
||||
go service.Dial(m, false)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary download file
|
||||
@@ -85,20 +86,20 @@ func GetPersonFile(c *gin.Context) {
|
||||
fileName := c.Query("file_name")
|
||||
_, err := uuid.FromString(token)
|
||||
if len(path) == 0 || err != nil || len(localPath) == 0 || len(fileName) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if file.CheckNotExist(localPath) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.DIR_NOT_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.DIR_NOT_EXISTS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.DIR_NOT_EXISTS, Message: common_err.GetMsg(common_err.DIR_NOT_EXISTS)})
|
||||
return
|
||||
}
|
||||
if _, ok := service.UDPAddressMap[token]; !ok {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_REMOTE_ERROR, Message: common_err.GetMsg(common_err.PERSON_REMOTE_ERROR)})
|
||||
return
|
||||
}
|
||||
|
||||
if _, ok := service.UDPAddressMap[token]; !ok {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_REMOTE_ERROR, Message: common_err.GetMsg(common_err.PERSON_REMOTE_ERROR)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -117,7 +118,7 @@ func GetPersonFile(c *gin.Context) {
|
||||
task.Type = types.PERSONFILEDOWNLOAD
|
||||
task.LocalPath = localPath
|
||||
if service.MyService.Download().GetDownloadListByPath(task) > 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_EXIST_DOWNLOAD, Message: oasis_err2.GetMsg(oasis_err2.PERSON_EXIST_DOWNLOAD)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_EXIST_DOWNLOAD, Message: common_err.GetMsg(common_err.PERSON_EXIST_DOWNLOAD)})
|
||||
return
|
||||
}
|
||||
service.MyService.Download().AddDownloadTask(task)
|
||||
@@ -130,7 +131,7 @@ func GetPersonFile(c *gin.Context) {
|
||||
m.UUId = uuid
|
||||
go service.Dial(m, false)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary delete download file records
|
||||
@@ -146,7 +147,7 @@ func DeletePersonDownloadFile(c *gin.Context) {
|
||||
id := c.Param("uuid")
|
||||
_, err := uuid.FromString(id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -163,7 +164,7 @@ func DeletePersonDownloadFile(c *gin.Context) {
|
||||
}
|
||||
service.MyService.Download().DelDownload(id)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary Get file download list
|
||||
@@ -180,7 +181,7 @@ func GetPersonDownloadList(c *gin.Context) {
|
||||
//if it is downloading, it need to add 'already'
|
||||
for i := 0; i < len(list); i++ {
|
||||
if list[i].State == types.DOWNLOADING {
|
||||
tempDir := config.AppInfo.RootPath + "/temp" + "/" + list[i].UUID
|
||||
tempDir := config.AppInfo.TempPath + "/" + list[i].UUID
|
||||
files, err := ioutil.ReadDir(tempDir)
|
||||
if err == nil {
|
||||
list[i].Already = len(files)
|
||||
@@ -188,7 +189,7 @@ func GetPersonDownloadList(c *gin.Context) {
|
||||
}
|
||||
list[i].Duration = time.Now().Unix() - list[i].Created
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
// @Summary edit friend's remarks
|
||||
@@ -204,14 +205,14 @@ func PutPersonRemarks(c *gin.Context) {
|
||||
_, err := uuid.FromString(token)
|
||||
mark := c.PostForm("remarks")
|
||||
if err != nil || len(mark) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
friend := model2.FriendModel{}
|
||||
friend.Token = token
|
||||
friend.Mark = mark
|
||||
service.MyService.Friend().EditFriendMark(friend)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary edit friend's
|
||||
@@ -226,7 +227,7 @@ func PutPersonWrite(c *gin.Context) {
|
||||
token := c.Param("shareid")
|
||||
_, err := uuid.FromString(token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
write, _ := strconv.ParseBool(c.PostForm("write"))
|
||||
@@ -234,7 +235,7 @@ func PutPersonWrite(c *gin.Context) {
|
||||
friend.Token = token
|
||||
friend.Write = write
|
||||
service.MyService.Friend().EditFriendMark(friend)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary image thumbnail
|
||||
@@ -250,7 +251,7 @@ func GetPersonImageThumbnail(c *gin.Context) {
|
||||
path := c.Query("path")
|
||||
_, err := uuid.FromString(token)
|
||||
if err != nil || len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
uuid := uuid.NewV4().String()
|
||||
@@ -263,7 +264,7 @@ func GetPersonImageThumbnail(c *gin.Context) {
|
||||
|
||||
img, err := service.Dial(m, false)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -271,20 +272,20 @@ func GetPersonImageThumbnail(c *gin.Context) {
|
||||
//err = gob.NewEncoder(&buf).Encode(img.Data)
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
err = gob.NewEncoder(&buf).Encode(img.Data)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
imageBuffer, _ := base64.StdEncoding.DecodeString(img.Data.(string))
|
||||
c.Writer.WriteString(string(imageBuffer))
|
||||
// c.String(http.StatusOK, "data:image/"+filesuffix+";base64,"+img.Data.(string))
|
||||
//c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: img.Data.(string)})
|
||||
//c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: img.Data.(string)})
|
||||
}
|
||||
|
||||
// @Summary get my friend list
|
||||
@@ -304,7 +305,7 @@ func GetPersonFriend(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
// @Summary network type detection
|
||||
@@ -325,11 +326,11 @@ func GetPersonDetection(c *gin.Context) {
|
||||
|
||||
result, err := natType.GetDeterminedNatType(true, 5, "stun.l.google.com")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
//result := service.MyService.Person().GetPersionNetWorkTypeDetection()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: result})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: result})
|
||||
}
|
||||
|
||||
// @Summary add friend
|
||||
@@ -346,24 +347,24 @@ func PostAddPersonFriend(c *gin.Context) {
|
||||
for _, v := range tokenList {
|
||||
_, err := uuid.FromString(v)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
if v == config.ServerInfo.Token {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_MYSELF, Message: oasis_err2.GetMsg(oasis_err2.PERSON_MYSELF)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_MYSELF, Message: common_err.GetMsg(common_err.PERSON_MYSELF)})
|
||||
return
|
||||
}
|
||||
|
||||
udb := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: v})
|
||||
if !reflect.DeepEqual(udb, model2.FriendModel{Token: v}) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_EXIST_FRIEND, Message: oasis_err2.GetMsg(oasis_err2.PERSON_EXIST_FRIEND)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_EXIST_FRIEND, Message: common_err.GetMsg(common_err.PERSON_EXIST_FRIEND)})
|
||||
return
|
||||
}
|
||||
|
||||
user := service.MyService.Casa().GetUserInfoByShareId(v)
|
||||
if reflect.DeepEqual(user, model.UserInfo{}) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_NOT_EXIST_USER, Message: oasis_err2.GetMsg(oasis_err2.PERSON_NOT_EXIST_USER)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_NOT_EXIST_USER, Message: common_err.GetMsg(common_err.PERSON_NOT_EXIST_USER)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -396,7 +397,7 @@ func PostAddPersonFriend(c *gin.Context) {
|
||||
service.MyService.Friend().AddFriend(friend)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary Get a list of directories
|
||||
@@ -413,11 +414,11 @@ func GetPersonDirectory(c *gin.Context) {
|
||||
token := c.Query("share_id")
|
||||
_, err := uuid.FromString(token)
|
||||
if len(path) == 0 || err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if _, ok := service.UDPAddressMap[token]; !ok {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_REMOTE_ERROR, Message: common_err.GetMsg(common_err.PERSON_REMOTE_ERROR)})
|
||||
return
|
||||
}
|
||||
uuid := uuid.NewV4().String()
|
||||
@@ -429,7 +430,7 @@ func GetPersonDirectory(c *gin.Context) {
|
||||
m.UUId = uuid
|
||||
result, err := service.Dial(m, false)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
dataModel := []model.Path{}
|
||||
@@ -437,11 +438,11 @@ func GetPersonDirectory(c *gin.Context) {
|
||||
dataModelByte, _ := json.Marshal(result.Data)
|
||||
err := json.Unmarshal(dataModelByte, &dataModel)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: dataModel})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: dataModel})
|
||||
}
|
||||
|
||||
// @Summary Modify the download storage directory
|
||||
@@ -457,17 +458,17 @@ func PostPersonDownDir(c *gin.Context) {
|
||||
downPath := c.PostForm("path")
|
||||
|
||||
if len(downPath) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if file.CheckNotExist(downPath) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.DIR_NOT_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.DIR_NOT_EXISTS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.DIR_NOT_EXISTS, Message: common_err.GetMsg(common_err.DIR_NOT_EXISTS)})
|
||||
return
|
||||
}
|
||||
config.Cfg.Section("file").Key("DownloadDir").SetValue(downPath)
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
config.FileSettingInfo.DownloadDir = downPath
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary Get the download storage directory
|
||||
@@ -478,7 +479,7 @@ func PostPersonDownDir(c *gin.Context) {
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /person/down/dir [get]
|
||||
func GetPersonDownDir(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: config.FileSettingInfo.DownloadDir})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: config.FileSettingInfo.DownloadDir})
|
||||
}
|
||||
|
||||
// @Summary Modify the shared directory
|
||||
@@ -494,7 +495,7 @@ func PostPersonShare(c *gin.Context) {
|
||||
share := c.PostForm("share")
|
||||
|
||||
if len(share) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -502,12 +503,12 @@ func PostPersonShare(c *gin.Context) {
|
||||
json.Unmarshal([]byte(share), &list)
|
||||
|
||||
if len(list) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
for _, v := range list {
|
||||
if !file.Exists(v) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_ALREADY_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.FILE_ALREADY_EXISTS, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)})
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -515,7 +516,7 @@ func PostPersonShare(c *gin.Context) {
|
||||
config.Cfg.Section("file").Key("ShareDir").SetValue(strings.Join(list, "|"))
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
config.FileSettingInfo.ShareDir = list
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary Get the shared directory
|
||||
@@ -526,7 +527,7 @@ func PostPersonShare(c *gin.Context) {
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /person/share [get]
|
||||
func GetPersonShare(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: config.FileSettingInfo.ShareDir})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: config.FileSettingInfo.ShareDir})
|
||||
}
|
||||
|
||||
// @Summary Get the shareid
|
||||
@@ -537,7 +538,7 @@ func GetPersonShare(c *gin.Context) {
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /person/shareid [get]
|
||||
func GetPersonShareId(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: config.ServerInfo.Token})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: config.ServerInfo.Token})
|
||||
}
|
||||
|
||||
// @Summary Modify disabled status
|
||||
@@ -553,14 +554,14 @@ func PutPersonBlock(c *gin.Context) {
|
||||
_, err := uuid.FromString(token)
|
||||
block, _ := strconv.ParseBool(c.PostForm("block"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
friend := model2.FriendModel{}
|
||||
friend.Token = token
|
||||
friend.Block = block
|
||||
service.MyService.Friend().EditFriendBlock(friend)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary Delete my friend
|
||||
@@ -574,14 +575,14 @@ func DeletePersonFriend(c *gin.Context) {
|
||||
token := c.Param("shareid")
|
||||
_, err := uuid.FromString(token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
friend := model2.FriendModel{}
|
||||
friend.Token = token
|
||||
|
||||
service.MyService.Friend().DeleteFriend(friend)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary Get public person
|
||||
@@ -593,7 +594,7 @@ func DeletePersonFriend(c *gin.Context) {
|
||||
// @Router /person/public [get]
|
||||
func GetPersonPublic(c *gin.Context) {
|
||||
list := service.MyService.Casa().GetPersonPublic()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
// @Summary upload file to friend
|
||||
@@ -611,11 +612,11 @@ func PostPersonFile(c *gin.Context) {
|
||||
path := c.PostForm("path")
|
||||
localPath := c.PostForm("local_path")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if !file.Exists(localPath) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_DOES_NOT_EXIST, Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.FILE_DOES_NOT_EXIST, Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST)})
|
||||
return
|
||||
}
|
||||
uuid := uuid.NewV4().String()
|
||||
@@ -641,12 +642,12 @@ func PostPersonFile(c *gin.Context) {
|
||||
task.Type = types.PERSONFILEUPLOAD
|
||||
task.LocalPath = localPath
|
||||
if service.MyService.Download().GetDownloadListByPath(task) > 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_EXIST_DOWNLOAD, Message: oasis_err2.GetMsg(oasis_err2.PERSON_EXIST_DOWNLOAD)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.PERSON_EXIST_DOWNLOAD, Message: common_err.GetMsg(common_err.PERSON_EXIST_DOWNLOAD)})
|
||||
return
|
||||
}
|
||||
service.MyService.Download().AddDownloadTask(task)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary agree add friend
|
||||
@@ -660,14 +661,14 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
token := c.Param("shareid")
|
||||
_, err := uuid.FromString(token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
user := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: token})
|
||||
|
||||
if user.State != types.FRIENDSTATEREQUEST {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.COMMAND_ERROR_INVALID_OPERATION, Message: oasis_err2.GetMsg(oasis_err2.COMMAND_ERROR_INVALID_OPERATION)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.COMMAND_ERROR_INVALID_OPERATION, Message: common_err.GetMsg(common_err.COMMAND_ERROR_INVALID_OPERATION)})
|
||||
return
|
||||
}
|
||||
service.MyService.Friend().AgreeFrined(user.Token)
|
||||
@@ -681,7 +682,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
m.UUId = uuid
|
||||
go service.Dial(m, true)
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// // @Summary upload file
|
||||
@@ -699,7 +700,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
// _, err := uuid.FromString(token)
|
||||
// path := c.Query("path")
|
||||
// if err != nil {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
// return
|
||||
// }
|
||||
|
||||
@@ -717,11 +718,11 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
// }
|
||||
// tempDir += chunkNumber
|
||||
// if !file.CheckNotExist(tempDir) {
|
||||
// c.JSON(200, model.Result{Success: 200, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
|
||||
// c.JSON(200, model.Result{Success: 200, Message: common_err.GetMsg(common_err.FILE_ALREADY_EXISTS)})
|
||||
// return
|
||||
// }
|
||||
|
||||
// c.JSON(204, model.Result{Success: 204, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
// c.JSON(204, model.Result{Success: 204, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
// }
|
||||
|
||||
// // @Summary upload file
|
||||
@@ -737,7 +738,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
// token := c.Param("shareid")
|
||||
// _, err := uuid.FromString(token)
|
||||
// if err != nil {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
// return
|
||||
// }
|
||||
// f, _, _ := c.Request.FormFile("file")
|
||||
@@ -751,7 +752,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
// hash := file.GetHashByContent([]byte(fileName))
|
||||
|
||||
// if len(path) == 0 {
|
||||
// c.JSON(oasis_err2.INVALID_PARAMS, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
// c.JSON(common_err.INVALID_PARAMS, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
// return
|
||||
// }
|
||||
// tempDir := "/casaOS/temp/" + hash + strconv.Itoa(totalChunks) + "/"
|
||||
@@ -775,7 +776,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
// defer out.Close()
|
||||
// _, err := io.Copy(out, f)
|
||||
// if err != nil {
|
||||
// c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
// c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
// return
|
||||
// }
|
||||
// } else {
|
||||
@@ -783,21 +784,21 @@ func PutPersonAgreeFriend(c *gin.Context) {
|
||||
// defer out.Close()
|
||||
// _, err := io.Copy(out, f)
|
||||
// if err != nil {
|
||||
// c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
// c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
// return
|
||||
// }
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
// return
|
||||
// }
|
||||
|
||||
// fileNum, err := ioutil.ReadDir(tempDir)
|
||||
// if err != nil {
|
||||
// c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
|
||||
// c.JSON(common_err.ERROR, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR), Data: err.Error()})
|
||||
// return
|
||||
// }
|
||||
// if totalChunks == len(fileNum) {
|
||||
// file.RMDir(tempDir)
|
||||
// }
|
||||
|
||||
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
// }
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GetSearchList(c *gin.Context) {
|
||||
key := c.DefaultQuery("key", "")
|
||||
if len(key) == 0 {
|
||||
return
|
||||
}
|
||||
list, err := service.MyService.Search().SearchList(key)
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: list})
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// @Summary 获取列表
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags share
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /share/list [get]
|
||||
func GetShareDirList(c *gin.Context) {
|
||||
list := service.MyService.ShareDirectory().List(true)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
// @Summary 添加文件共享
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Tags share
|
||||
// @Security ApiKeyAuth
|
||||
// @Param path formData string true "要分享的文件路径"
|
||||
// @Param name formData string true "名称"
|
||||
// @Param comment formData string true "描述"
|
||||
// @Param read_only formData bool false "是否只读"
|
||||
// @Param writeable formData bool false "是否可写"
|
||||
// @Param browseable formData bool false "是否可浏览"
|
||||
// @Param user formData string false "用户"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /share/add [post]
|
||||
func PostShareDirAdd(c *gin.Context) {
|
||||
|
||||
name := c.PostForm("name")
|
||||
comment := c.PostForm("comment")
|
||||
path := c.PostForm("path")
|
||||
readOnly, _ := strconv.ParseBool(c.DefaultPostForm("read_only", "false"))
|
||||
writeable, _ := strconv.ParseBool(c.DefaultPostForm("writeable", "true"))
|
||||
browse, _ := strconv.ParseBool(c.DefaultPostForm("browseable", "true"))
|
||||
user := c.PostForm("user")
|
||||
|
||||
if len(name) == 0 || len(comment) == 0 || len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
var m model2.ShareDirDBModel
|
||||
m.Name = name
|
||||
m.Comment = comment
|
||||
m.Path = path
|
||||
m.ReadOnly = readOnly
|
||||
m.Writeable = writeable
|
||||
m.Browseable = browse
|
||||
m.ValidUsers = user
|
||||
|
||||
service.MyService.ShareDirectory().Add(&m)
|
||||
service.MyService.ShareDirectory().UpConfig()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary 删除分享
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags share
|
||||
// @Security ApiKeyAuth
|
||||
// @Param id path string true "id"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /share/del/{id} [delete]
|
||||
func DeleteShareDirDel(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
service.MyService.ShareDirectory().Delete(id)
|
||||
service.MyService.ShareDirectory().UpConfig()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary 分享详情
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags share
|
||||
// @Security ApiKeyAuth
|
||||
// @Param id path string true "id"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /share/info/{id} [get]
|
||||
func GetShareDirInfo(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
info := service.MyService.ShareDirectory().Info(id)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: info})
|
||||
}
|
||||
|
||||
// @Summary 更新分享详情
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags share
|
||||
// @Security ApiKeyAuth
|
||||
// @Param id path string true "id"
|
||||
// @Param path formData string true "要分享的文件路径"
|
||||
// @Param name formData string true "名称"
|
||||
// @Param comment formData string true "描述"
|
||||
// @Param read_only formData bool false "是否只读"
|
||||
// @Param writeable formData bool false "是否可写"
|
||||
// @Param browseable formData bool false "是否可浏览"
|
||||
// @Param user formData string false "用户"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /share/update/{id} [put]
|
||||
func PutShareDirEdit(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 32)
|
||||
|
||||
if err != nil || id == 0 {
|
||||
//todo 报错出去
|
||||
}
|
||||
|
||||
name := c.PostForm("name")
|
||||
comment := c.PostForm("comment")
|
||||
path := c.PostForm("path")
|
||||
readOnly, _ := strconv.ParseBool(c.DefaultPostForm("read_only", "false"))
|
||||
writeable, _ := strconv.ParseBool(c.DefaultPostForm("writeable", "true"))
|
||||
browse, _ := strconv.ParseBool(c.DefaultPostForm("browseable", "true"))
|
||||
user := c.PostForm("user")
|
||||
|
||||
if len(name) == 0 || len(comment) == 0 || len(path) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
|
||||
var m model2.ShareDirDBModel
|
||||
m.Id = uint(id)
|
||||
m.Name = name
|
||||
m.Comment = comment
|
||||
m.Path = path
|
||||
m.ReadOnly = readOnly
|
||||
m.Writeable = writeable
|
||||
m.Browseable = browse
|
||||
m.ValidUsers = user
|
||||
service.MyService.ShareDirectory().Update(&m)
|
||||
service.MyService.ShareDirectory().UpConfig()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
}
|
||||
@@ -1,13 +1,24 @@
|
||||
/*
|
||||
* @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/oasis_err"
|
||||
"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"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// @Summary 获取短链列表
|
||||
@@ -21,7 +32,7 @@ import (
|
||||
// @Router /shortcuts/list [get]
|
||||
func GetShortcutsList(c *gin.Context) {
|
||||
list := service.MyService.Shortcuts().GetList()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: list})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
// @Summary 添加shortcuts
|
||||
@@ -38,17 +49,17 @@ func PostShortcutsAdd(c *gin.Context) {
|
||||
|
||||
c.BindJSON(&m)
|
||||
if len(m.Url) == 0 || len(m.Title) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
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: oasis_err.SHORTCUTS_URL_ERROR, Message: oasis_err.GetMsg(oasis_err.SHORTCUTS_URL_ERROR), Data: err.Error()})
|
||||
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: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
|
||||
}
|
||||
|
||||
@@ -63,8 +74,8 @@ func DeleteShortcutsDelete(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
service.MyService.Shortcuts().DeleteData(id)
|
||||
c.JSON(http.StatusOK, model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: "",
|
||||
})
|
||||
}
|
||||
@@ -82,15 +93,15 @@ 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: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
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: oasis_err.SHORTCUTS_URL_ERROR, Message: oasis_err.GetMsg(oasis_err.SHORTCUTS_URL_ERROR), Data: err.Error()})
|
||||
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: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: ""})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: ""})
|
||||
}
|
||||
|
||||
@@ -1,35 +1,27 @@
|
||||
/*
|
||||
* @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"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func SyncToSyncthing(c *gin.Context) {
|
||||
u := c.Param("url")
|
||||
target := "http://" + strings.Split(c.Request.Host, ":")[0] + ":" + config.SystemConfigInfo.SyncPort
|
||||
remote, err := url.Parse(target)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
proxy := httputil.NewSingleHostReverseProxy(remote)
|
||||
c.Request.Header.Add("X-API-Key", config.SystemConfigInfo.SyncKey)
|
||||
//c.Request.Header.Add("X-API-Key", config.SystemConfigInfo.SyncKey)
|
||||
c.Request.URL.Path = u
|
||||
|
||||
proxy.ServeHTTP(c.Writer, c.Request)
|
||||
}
|
||||
|
||||
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: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
@@ -13,14 +13,16 @@ import (
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/version"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// @Summary check version
|
||||
@@ -29,9 +31,9 @@ import (
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/chackversion [get]
|
||||
func CheckVersion(c *gin.Context) {
|
||||
need, version := version.IsNeedUpdate()
|
||||
// @Router /sys/version/check [get]
|
||||
func GetSystemCheckVersion(c *gin.Context) {
|
||||
need, version := version.IsNeedUpdate(service.MyService.Casa().GetCasaosVersion())
|
||||
if need {
|
||||
installLog := model2.AppNotify{}
|
||||
installLog.State = 0
|
||||
@@ -42,38 +44,11 @@ func CheckVersion(c *gin.Context) {
|
||||
installLog.Name = "CasaOS System"
|
||||
service.MyService.Notify().AddLog(installLog)
|
||||
}
|
||||
data := make(map[string]interface{}, 1)
|
||||
data := make(map[string]interface{}, 3)
|
||||
data["is_need"] = need
|
||||
data["version"] = version
|
||||
data["current_version"] = types.CURRENTVERSION
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
|
||||
return
|
||||
}
|
||||
|
||||
// @Summary check client version
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/client/version [get]
|
||||
func GetClientVersion(c *gin.Context) {
|
||||
need, version := version.IsClientNeedUpdate()
|
||||
if need {
|
||||
installLog := model2.AppNotify{}
|
||||
installLog.State = 0
|
||||
installLog.Message = "New version " + version.Version + " is ready, ready to upgrade"
|
||||
installLog.Type = types.NOTIFY_TYPE_NEED_CONFIRM
|
||||
installLog.CreatedAt = strconv.FormatInt(time.Now().Unix(), 10)
|
||||
installLog.UpdatedAt = strconv.FormatInt(time.Now().Unix(), 10)
|
||||
installLog.Name = "CasaOS System"
|
||||
service.MyService.Notify().AddLog(installLog)
|
||||
}
|
||||
data := make(map[string]interface{}, 1)
|
||||
data["is_need"] = need
|
||||
data["version"] = version
|
||||
data["current_version"] = types.CURRENTVERSION
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary 系统信息
|
||||
@@ -84,16 +59,16 @@ func GetClientVersion(c *gin.Context) {
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/update [post]
|
||||
func SystemUpdate(c *gin.Context) {
|
||||
need, version := version.IsNeedUpdate()
|
||||
need, version := version.IsNeedUpdate(service.MyService.Casa().GetCasaosVersion())
|
||||
if need {
|
||||
service.MyService.System().UpdateSystemVersion(version.Version)
|
||||
}
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
//系统配置
|
||||
//Get system config
|
||||
func GetSystemConfig(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: json.RawMessage(config.SystemConfigInfo.ConfigStr)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: ""})
|
||||
}
|
||||
|
||||
// @Summary get logs
|
||||
@@ -105,7 +80,7 @@ func GetSystemConfig(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: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: service.MyService.System().GetCasaOSLogs(line)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: service.MyService.System().GetCasaOSLogs(line)})
|
||||
}
|
||||
|
||||
// @Summary 修改配置文件
|
||||
@@ -123,8 +98,8 @@ func PostSetSystemConfig(c *gin.Context) {
|
||||
service.MyService.System().UpSystemConfig(string(buf[0:n]), "")
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: json.RawMessage(config.SystemConfigInfo.ConfigStr),
|
||||
})
|
||||
}
|
||||
@@ -133,8 +108,8 @@ func PostSetSystemConfig(c *gin.Context) {
|
||||
func GetSystemConfigDebug(c *gin.Context) {
|
||||
|
||||
array := service.MyService.System().GetSystemConfigDebug()
|
||||
disk := service.MyService.ZiMa().GetDiskInfo()
|
||||
sys := service.MyService.ZiMa().GetSysInfo()
|
||||
disk := service.MyService.System().GetDiskInfo()
|
||||
sys := service.MyService.System().GetSysInfo()
|
||||
//todo 准备sync需要显示的数据(镜像,容器)
|
||||
var systemAppStatus string
|
||||
images := service.MyService.Docker().IsExistImage("linuxserver/syncthing")
|
||||
@@ -160,12 +135,12 @@ func GetSystemConfigDebug(c *gin.Context) {
|
||||
|
||||
// array = append(array, fmt.Sprintf("disk,total:%v,used:%v,UsedPercent:%v", disk.Total>>20, disk.Used>>20, disk.UsedPercent))
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: bugContent})
|
||||
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: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: json.RawMessage(config.SystemConfigInfo.WidgetList)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: json.RawMessage(config.SystemConfigInfo.WidgetList)})
|
||||
}
|
||||
|
||||
// @Summary 修改组件配置文件
|
||||
@@ -181,8 +156,8 @@ func PostSetWidgetConfig(c *gin.Context) {
|
||||
service.MyService.System().UpSystemConfig("", string(buf[0:n]))
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: json.RawMessage(config.SystemConfigInfo.WidgetList),
|
||||
})
|
||||
}
|
||||
@@ -197,8 +172,8 @@ func PostSetWidgetConfig(c *gin.Context) {
|
||||
func GetCasaOSPort(c *gin.Context) {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: config.ServerInfo.HttpPort,
|
||||
})
|
||||
}
|
||||
@@ -208,15 +183,18 @@ func GetCasaOSPort(c *gin.Context) {
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Param port formData string true "port"
|
||||
// @Param port json string true "port"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/port [put]
|
||||
func PutCasaOSPort(c *gin.Context) {
|
||||
port, err := strconv.Atoi(c.PostForm("port"))
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
portStr := json["port"]
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.ERROR,
|
||||
Success: common_err.ERROR,
|
||||
Message: err.Error(),
|
||||
})
|
||||
return
|
||||
@@ -226,16 +204,16 @@ func PutCasaOSPort(c *gin.Context) {
|
||||
if !isAvailable {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.PORT_IS_OCCUPIED,
|
||||
Message: oasis_err.GetMsg(oasis_err.PORT_IS_OCCUPIED),
|
||||
Success: common_err.PORT_IS_OCCUPIED,
|
||||
Message: common_err.GetMsg(common_err.PORT_IS_OCCUPIED),
|
||||
})
|
||||
return
|
||||
}
|
||||
service.MyService.System().UpSystemPort(strconv.Itoa(port))
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -245,18 +223,23 @@ func PutCasaOSPort(c *gin.Context) {
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /guide/check [get]
|
||||
func GetGuideCheck(c *gin.Context) {
|
||||
initUser := false
|
||||
if !config.UserInfo.Initialized {
|
||||
initUser = true
|
||||
// @Router /sys/init/check [get]
|
||||
func GetSystemInitCheck(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
|
||||
}
|
||||
data := make(map[string]interface{}, 1)
|
||||
data["need_init_user"] = initUser
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
@@ -267,7 +250,7 @@ func GetGuideCheck(c *gin.Context) {
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/kill [post]
|
||||
// @Router /sys/restart [post]
|
||||
func PostKillCasaOS(c *gin.Context) {
|
||||
os.Exit(0)
|
||||
}
|
||||
@@ -279,13 +262,20 @@ func PostKillCasaOS(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/usb/off [put]
|
||||
func PutSystemOffUSBAutoMount(c *gin.Context) {
|
||||
service.MyService.System().UpdateUSBAutoMount("False")
|
||||
service.MyService.System().ExecUSBAutoMountShell("False")
|
||||
func PutSystemUSBAutoMount(c *gin.Context) {
|
||||
status := c.Param("status")
|
||||
if status == "on" {
|
||||
service.MyService.System().UpdateUSBAutoMount("True")
|
||||
service.MyService.System().ExecUSBAutoMountShell("True")
|
||||
} else {
|
||||
service.MyService.System().UpdateUSBAutoMount("False")
|
||||
service.MyService.System().ExecUSBAutoMountShell("False")
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -304,8 +294,8 @@ func GetSystemUSBAutoMount(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: state,
|
||||
})
|
||||
}
|
||||
@@ -320,40 +310,23 @@ func GetSystemUSBAutoMount(c *gin.Context) {
|
||||
func GetSystemHardwareInfo(c *gin.Context) {
|
||||
|
||||
data := make(map[string]string, 1)
|
||||
data["drive_model"] = service.MyService.ZiMa().GetDeviceTree()
|
||||
data["drive_model"] = service.MyService.System().GetDeviceTree()
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary Turn off usb auto-mount
|
||||
// @Summary system utilization
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/usb/on [put]
|
||||
func PutSystemOnUSBAutoMount(c *gin.Context) {
|
||||
service.MyService.System().UpdateUSBAutoMount("True")
|
||||
service.MyService.System().ExecUSBAutoMountShell("True")
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err.SUCCESS,
|
||||
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary system info
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/info [get]
|
||||
func Info(c *gin.Context) {
|
||||
// @Router /sys/utilization [get]
|
||||
func GetSystemUtilization(c *gin.Context) {
|
||||
var data = make(map[string]interface{}, 6)
|
||||
|
||||
list := service.MyService.Disk().LSBLK(true)
|
||||
@@ -373,6 +346,8 @@ func Info(c *gin.Context) {
|
||||
s, _ := strconv.ParseUint(v.FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(v.FSUsed, 10, 64)
|
||||
loger.Info("disk info", zap.Any("/ total:", s))
|
||||
loger.Info("disk path", zap.Any("path", v.Path))
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
@@ -385,6 +360,8 @@ func Info(c *gin.Context) {
|
||||
s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(list[i].Children[j].FSUsed, 10, 64)
|
||||
loger.Info("disk info", zap.Any("/ total:", s))
|
||||
loger.Info("disk path", zap.Any("path", list[i].Path))
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
@@ -399,21 +376,20 @@ func Info(c *gin.Context) {
|
||||
findSystem += 1
|
||||
continue
|
||||
}
|
||||
if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" {
|
||||
if list[i].Tran == "sata" || list[i].Tran == "nvme" || list[i].Tran == "spi" || list[i].Tran == "sas" || strings.Contains(list[i].SubSystems, "virtio") || (list[i].Tran == "ata" && list[i].Type == "disk") {
|
||||
temp := service.MyService.Disk().SmartCTL(list[i].Path)
|
||||
if reflect.DeepEqual(temp, model.SmartctlA{}) {
|
||||
continue
|
||||
}
|
||||
|
||||
//list[i].Temperature = temp.Temperature.Current
|
||||
if !temp.SmartStatus.Passed {
|
||||
healthy = false
|
||||
healthy = true
|
||||
} else {
|
||||
healthy = temp.SmartStatus.Passed
|
||||
}
|
||||
if len(list[i].Children) > 0 {
|
||||
for _, v := range list[i].Children {
|
||||
s, _ := strconv.ParseUint(v.FSSize, 10, 64)
|
||||
a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
|
||||
u, _ := strconv.ParseUint(v.FSUsed, 10, 64)
|
||||
loger.Info("disk info", zap.Any("/ total:", s))
|
||||
loger.Info("disk path", zap.Any("path", list[i].Path))
|
||||
summary.Size += s
|
||||
summary.Avail += a
|
||||
summary.Used += u
|
||||
@@ -452,23 +428,23 @@ func Info(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
data["usb"] = usb
|
||||
cpu := service.MyService.ZiMa().GetCpuPercent()
|
||||
num := service.MyService.ZiMa().GetCpuCoreNum()
|
||||
cpu := service.MyService.System().GetCpuPercent()
|
||||
num := service.MyService.System().GetCpuCoreNum()
|
||||
cpuData := make(map[string]interface{})
|
||||
cpuData["percent"] = cpu
|
||||
cpuData["num"] = num
|
||||
data["cpu"] = cpuData
|
||||
data["mem"] = service.MyService.ZiMa().GetMemInfo()
|
||||
data["mem"] = service.MyService.System().GetMemInfo()
|
||||
|
||||
//拼装网络信息
|
||||
netList := service.MyService.ZiMa().GetNetInfo()
|
||||
netList := service.MyService.System().GetNetInfo()
|
||||
newNet := []model.IOCountersStat{}
|
||||
nets := service.MyService.ZiMa().GetNet(true)
|
||||
nets := service.MyService.System().GetNet(true)
|
||||
for _, n := range netList {
|
||||
for _, netCardName := range nets {
|
||||
if n.Name == netCardName {
|
||||
item := *(*model.IOCountersStat)(unsafe.Pointer(&n))
|
||||
item.State = strings.TrimSpace(service.MyService.ZiMa().GetNetState(n.Name))
|
||||
item.State = strings.TrimSpace(service.MyService.System().GetNetState(n.Name))
|
||||
item.Time = time.Now().Unix()
|
||||
newNet = append(newNet, item)
|
||||
break
|
||||
@@ -478,5 +454,112 @@ func Info(c *gin.Context) {
|
||||
|
||||
data["net"] = newNet
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
// @Summary Get notification port
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/socket/port [get]
|
||||
func GetSystemSocketPort(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: config.ServerInfo.SocketPort,
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary get cpu info
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/cpu [get]
|
||||
func GetSystemCupInfo(c *gin.Context) {
|
||||
cpu := service.MyService.System().GetCpuPercent()
|
||||
num := service.MyService.System().GetCpuCoreNum()
|
||||
data := make(map[string]interface{})
|
||||
data["percent"] = cpu
|
||||
data["num"] = num
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
|
||||
}
|
||||
|
||||
// @Summary get mem info
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/mem [get]
|
||||
func GetSystemMemInfo(c *gin.Context) {
|
||||
mem := service.MyService.System().GetMemInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: mem})
|
||||
|
||||
}
|
||||
|
||||
// @Summary get disk info
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/disk [get]
|
||||
func GetSystemDiskInfo(c *gin.Context) {
|
||||
disk := service.MyService.System().GetDiskInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: disk})
|
||||
}
|
||||
|
||||
// @Summary get Net info
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /sys/net [get]
|
||||
func GetSystemNetInfo(c *gin.Context) {
|
||||
netList := service.MyService.System().GetNetInfo()
|
||||
newNet := []model.IOCountersStat{}
|
||||
for _, n := range netList {
|
||||
for _, netCardName := range service.MyService.System().GetNet(true) {
|
||||
if n.Name == netCardName {
|
||||
item := *(*model.IOCountersStat)(unsafe.Pointer(&n))
|
||||
item.State = strings.TrimSpace(service.MyService.System().GetNetState(n.Name))
|
||||
item.Time = time.Now().Unix()
|
||||
newNet = append(newNet, item)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: newNet})
|
||||
}
|
||||
|
||||
//********************************************* Soon to be removed ***********************************************
|
||||
// @Summary 检查是否进入引导状态
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags sys
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /guide/check [get]
|
||||
func GetGuideCheck(c *gin.Context) {
|
||||
initUser := true
|
||||
if service.MyService.User().GetUserCount() > 0 {
|
||||
initUser = false
|
||||
}
|
||||
data := make(map[string]interface{}, 1)
|
||||
data["need_init_user"] = initUser
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// @Summary 获取task列表
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags task
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /task/list [get]
|
||||
func GetTaskList(c *gin.Context) {
|
||||
//list := service.MyService.Task().List(true)
|
||||
list := service.MyService.Task().GetServerTasks()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: list})
|
||||
}
|
||||
|
||||
func PutTaskUpdate(c *gin.Context) {
|
||||
service.MyService.Task().SyncTaskService()
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary 标记task已完成
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags task
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /task/completion/{id} [put]
|
||||
func PutTaskMarkerCompletion(c *gin.Context) {
|
||||
id, _ := strconv.Atoi(c.Param("id"))
|
||||
if id == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
var m model2.TaskDBModel
|
||||
m.Id = uint(id)
|
||||
m.State = types.TASK_STATE_COMPLETED
|
||||
service.MyService.Task().Update(&m)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
}
|
||||
|
||||
func PostTaskAdd(c *gin.Context) {
|
||||
var m model2.TaskDBModel
|
||||
c.BindJSON(&m)
|
||||
service.MyService.Task().Add(&m)
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
|
||||
}
|
||||
772
route/v1/user.go
772
route/v1/user.go
@@ -1,225 +1,281 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
json2 "encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
url2 "net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
jwt2 "github.com/IceWhaleTech/CasaOS/pkg/utils/jwt"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
"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"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
var user_service service.UserService
|
||||
|
||||
func init() {
|
||||
user_service = service.NewUserService()
|
||||
}
|
||||
|
||||
// @Summary 设置用户名和密码
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Tags user
|
||||
// @Param username formData string true "User name"
|
||||
// @Param pwd formData string true "password"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/setusernamepwd [post]
|
||||
func Set_Name_Pwd(c *gin.Context) {
|
||||
//json := make(map[string]string)
|
||||
//c.BindJSON(&json)
|
||||
username := c.PostForm("username")
|
||||
pwd := c.PostForm("pwd")
|
||||
//老用户名是否存在即新用户名和密码的验证
|
||||
if config.UserInfo.Initialized || len(username) == 0 || len(pwd) == 0 {
|
||||
// @Summary register user
|
||||
// @Router /user/register/ [post]
|
||||
func PostUserRegister(c *gin.Context) {
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
username := json["user_name"]
|
||||
pwd := json["password"]
|
||||
key := c.Param("key")
|
||||
if _, ok := service.UserRegisterHash[key]; !ok {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
model.Result{Success: common_err.KEY_NOT_EXIST, Message: common_err.GetMsg(common_err.KEY_NOT_EXIST)})
|
||||
return
|
||||
}
|
||||
//开始设置
|
||||
err := user_service.SetUser(username, pwd, "", "", "", "")
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: fmt.Sprintf("%v", err)})
|
||||
return
|
||||
} else {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
|
||||
if len(username) == 0 || len(pwd) == 0 {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
if len(pwd) < 6 {
|
||||
c.JSON(http.StatusOK,
|
||||
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,
|
||||
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.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)})
|
||||
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)})
|
||||
|
||||
}
|
||||
|
||||
// @Summary 登录
|
||||
// @Summary login
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags user
|
||||
// @Param username formData string true "User name"
|
||||
// @Param pwd formData string true "password"
|
||||
// @Param user_name query string true "User name"
|
||||
// @Param pwd query string true "password"
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/login [post]
|
||||
func Login(c *gin.Context) {
|
||||
username := c.PostForm("username")
|
||||
pwd := c.PostForm("pwd")
|
||||
//检查参数是否正确
|
||||
func PostUserLogin(c *gin.Context) {
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
|
||||
username := json["username"]
|
||||
pwd := json["pwd"]
|
||||
//check params is empty
|
||||
if len(username) == 0 || len(pwd) == 0 {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.ERROR,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS),
|
||||
Success: common_err.ERROR,
|
||||
Message: common_err.GetMsg(common_err.INVALID_PARAMS),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if config.UserInfo.UserName == username && config.UserInfo.PWD == pwd {
|
||||
//if username == "admin" && pwd == "admin" {
|
||||
|
||||
data := make(map[string]string, 2)
|
||||
data["token"] = jwt2.GetToken(username, pwd)
|
||||
data["version"] = types.CURRENTVERSION
|
||||
//user_service.SetUser("", "", token, "", "")
|
||||
user := service.MyService.User().GetUserAllInfoByName(username)
|
||||
if user.Id == 0 {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
Data: data,
|
||||
})
|
||||
model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
|
||||
return
|
||||
}
|
||||
if user.Password != encryption.GetMD5ByStr(pwd) {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{Success: common_err.PWD_INVALID, Message: common_err.GetMsg(common_err.PWD_INVALID)})
|
||||
return
|
||||
}
|
||||
user.Password = ""
|
||||
// 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)
|
||||
// data["token"] = token
|
||||
// data["user"] = user
|
||||
data := make(map[string]interface{}, 3)
|
||||
data["token"] = jwt.GetToken(username, pwd)
|
||||
data["version"] = types.CURRENTVERSION
|
||||
data["user"] = user
|
||||
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.ERROR,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.ERROR),
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: data,
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
// @Summary 修改头像
|
||||
// @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/changhead [post]
|
||||
func PostUserHead(c *gin.Context) {
|
||||
file, _, _ := c.Request.FormFile("file")
|
||||
user_service.UpLoadFile(file, config.UserInfo.Head)
|
||||
// @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(http.StatusOK,
|
||||
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()})
|
||||
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: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
Data: config.UserInfo.Head,
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: user,
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary 修改用户名
|
||||
/**
|
||||
* @description: get user avatar by user id
|
||||
* @param {query} id string user id
|
||||
* @method: GET
|
||||
*/
|
||||
func GetUserAvatar(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
user := service.MyService.User().GetUserInfoById(id)
|
||||
|
||||
path := "default.png"
|
||||
if user.Id > 0 {
|
||||
path = user.Avatar
|
||||
}
|
||||
c.File(path)
|
||||
}
|
||||
|
||||
// @Summary edit user name
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags user
|
||||
// @Param username formData string true "User name"
|
||||
// @Param oldname formData string true "Old user name"
|
||||
// @Param old_name query string true "Old user name"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/username [put]
|
||||
// @Router /user/name/:id [put]
|
||||
func PutUserName(c *gin.Context) {
|
||||
if config.ServerInfo.LockAccount {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ACCOUNT_LOCK, Message: oasis_err2.GetMsg(oasis_err2.ACCOUNT_LOCK)})
|
||||
//id := c.GetHeader("user_id")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
//userName := json["user_name"]
|
||||
username := json["username"]
|
||||
id := json["user_id"]
|
||||
if len(username) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)})
|
||||
return
|
||||
}
|
||||
oldname := c.PostForm("oldname")
|
||||
username := c.PostForm("username")
|
||||
if len(username) == 0 || config.UserInfo.UserName != oldname {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
|
||||
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_service.SetUser(username, "", "", "", "", "")
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
user.UserName = username
|
||||
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 修改密码
|
||||
// @Summary edit user password
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags user
|
||||
// @Param pwd formData string true "Password"
|
||||
// @Param old_pwd formData string true "Old password"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/password [put]
|
||||
// @Router /user/password/:id [put]
|
||||
func PutUserPwd(c *gin.Context) {
|
||||
oldPwd := c.PostForm("old_pwd")
|
||||
pwd := c.PostForm("pwd")
|
||||
if config.UserInfo.PWD != oldPwd {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PWD_INVALID_OLD, Message: oasis_err2.GetMsg(oasis_err2.PWD_INVALID_OLD)})
|
||||
//id := c.GetHeader("user_id")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
oldPwd := json["old_pwd"]
|
||||
pwd := json["pwd"]
|
||||
id := json["user_id"]
|
||||
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)})
|
||||
return
|
||||
}
|
||||
if config.ServerInfo.LockAccount {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ACCOUNT_LOCK, Message: oasis_err2.GetMsg(oasis_err2.ACCOUNT_LOCK)})
|
||||
user := service.MyService.User().GetUserAllInfoById(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
|
||||
}
|
||||
if len(pwd) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PWD_IS_EMPTY, Message: oasis_err2.GetMsg(oasis_err2.PWD_IS_EMPTY)})
|
||||
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)})
|
||||
return
|
||||
}
|
||||
user_service.SetUser("", pwd, "", "", "", "")
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
|
||||
}
|
||||
|
||||
// @Summary edit user info
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Tags user
|
||||
// @Param user_name formData string false "User Name"
|
||||
// @Param email formData string false "Email"
|
||||
// @Param description formData string false "Description"
|
||||
// @Param pwd formData string false "Password"
|
||||
// @Param old_pwd formData string false "Old password"
|
||||
// @Param nick_name formData string false "nick name"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/info [post]
|
||||
func PostUserChangeInfo(c *gin.Context) {
|
||||
username := c.PostForm("user_name")
|
||||
email := c.PostForm("email")
|
||||
description := c.PostForm("description")
|
||||
nickName := c.PostForm("nick_name")
|
||||
oldpwd := c.PostForm("old_pwd")
|
||||
pwd := c.PostForm("pwd")
|
||||
if len(pwd) > 0 && config.UserInfo.PWD != oldpwd {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PWD_INVALID, Message: oasis_err2.GetMsg(oasis_err2.PWD_INVALID)})
|
||||
return
|
||||
}
|
||||
user_service.SetUser(username, pwd, "", email, description, nickName)
|
||||
data := make(map[string]string, 4)
|
||||
|
||||
data["token"] = jwt2.GetToken(username, pwd)
|
||||
data["user_name"] = username
|
||||
data["head"] = config.UserInfo.Head
|
||||
data["nick_name"] = config.UserInfo.NickName
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
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})
|
||||
}
|
||||
|
||||
// @Summary edit user nick
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Accept application/json
|
||||
// @Tags user
|
||||
// @Param nick_name formData string false "nick name"
|
||||
// @Param nick_name query string false "nick name"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/nick [put]
|
||||
func PutUserChangeNick(c *gin.Context) {
|
||||
|
||||
nickName := c.PostForm("nick_name")
|
||||
func PutUserNick(c *gin.Context) {
|
||||
|
||||
//id := c.GetHeader("user_id")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
nickName := json["nick_name"]
|
||||
id := json["user_id"]
|
||||
if len(nickName) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
user_service.SetUser("", "", "", "", "", nickName)
|
||||
data := make(map[string]string, 1)
|
||||
data["nick_name"] = config.UserInfo.NickName
|
||||
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)
|
||||
//TODO:person remove together
|
||||
go service.MyService.Casa().PushUserInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: user})
|
||||
}
|
||||
|
||||
// @Summary edit user description
|
||||
@@ -230,18 +286,27 @@ func PutUserChangeNick(c *gin.Context) {
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/desc [put]
|
||||
func PutUserChangeDesc(c *gin.Context) {
|
||||
desc := c.PostForm("description")
|
||||
|
||||
func PutUserDesc(c *gin.Context) {
|
||||
// id := c.GetHeader("user_id")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
id := json["user_id"]
|
||||
desc := json["description"]
|
||||
if len(desc) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
user_service.SetUser("", "", "", "", desc, "")
|
||||
data := make(map[string]string, 1)
|
||||
data["description"] = config.UserInfo.Description
|
||||
go service.MyService.Casa().PushUserInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
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 Modify user person information (Initialization use)
|
||||
@@ -254,38 +319,85 @@ func PutUserChangeDesc(c *gin.Context) {
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/person/info [post]
|
||||
func PostUserPersonInfo(c *gin.Context) {
|
||||
desc := c.PostForm("description")
|
||||
nickName := c.PostForm("nick_name")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
desc := json["description"]
|
||||
nickName := json["nick_name"]
|
||||
id := json["user_id"]
|
||||
if len(desc) == 0 || len(nickName) == 0 {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
user_service.SetUser("", "", "", "", desc, nickName)
|
||||
data := make(map[string]string, 2)
|
||||
data["description"] = config.UserInfo.Description
|
||||
data["nick_name"] = config.UserInfo.NickName
|
||||
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_service.SetUser("", "", "", "", desc, nickName)
|
||||
user.NickName = nickName
|
||||
user.Description = desc
|
||||
service.MyService.User().UpdateUser(user)
|
||||
go service.MyService.Casa().PushUserInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
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 mapplication/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")
|
||||
id := c.Param("id")
|
||||
user := service.MyService.User().GetUserInfoById(id)
|
||||
|
||||
//*****
|
||||
var u = make(map[string]string, 5)
|
||||
u["user_name"] = user.UserName
|
||||
u["head"] = user.Avatar
|
||||
u["email"] = user.Email
|
||||
u["description"] = user.NickName
|
||||
u["nick_name"] = user.NickName
|
||||
u["id"] = strconv.Itoa(user.Id)
|
||||
|
||||
//**
|
||||
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: u,
|
||||
})
|
||||
}
|
||||
|
||||
// @Summary get user info
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags user
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/info [get]
|
||||
func GetUserInfo(c *gin.Context) {
|
||||
var u = make(map[string]string, 5)
|
||||
u["user_name"] = config.UserInfo.UserName
|
||||
u["head"] = config.UserInfo.Head
|
||||
u["email"] = config.UserInfo.Email
|
||||
u["description"] = config.UserInfo.Description
|
||||
u["nick_name"] = config.UserInfo.NickName
|
||||
func GetUserInfoByUserName(c *gin.Context) {
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
userName := json["user_name"]
|
||||
if len(userName) == 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().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)})
|
||||
return
|
||||
}
|
||||
//**
|
||||
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{
|
||||
Success: oasis_err2.SUCCESS,
|
||||
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
|
||||
Data: u,
|
||||
Success: common_err.SUCCESS,
|
||||
Message: common_err.GetMsg(common_err.SUCCESS),
|
||||
Data: user,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -297,5 +409,327 @@ func GetUserInfo(c *gin.Context) {
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/shareid [get]
|
||||
func GetUserShareID(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: config.ServerInfo.Token})
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: config.ServerInfo.Token})
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: get all user name
|
||||
* @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(http.StatusOK,
|
||||
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(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
//id := c.GetHeader("user_id")
|
||||
id := c.Param("id")
|
||||
user := service.MyService.User().GetUserInfoById(id)
|
||||
// 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)})
|
||||
return
|
||||
}
|
||||
filePath := config.AppInfo.UserDataPath + "/" + id + "/" + name + ".json"
|
||||
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)})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, 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(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
//id := c.GetHeader("user_id")
|
||||
id := c.Param("id")
|
||||
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
|
||||
}
|
||||
data, _ := ioutil.ReadAll(c.Request.Body)
|
||||
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))})
|
||||
}
|
||||
|
||||
/**
|
||||
* @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(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
return
|
||||
}
|
||||
//id := c.GetHeader("user_id")
|
||||
id := c.Param("id")
|
||||
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
|
||||
}
|
||||
filePath := config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id) + "/" + name + ".json"
|
||||
os.Remove(filePath)
|
||||
c.JSON(http.StatusOK, 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(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: id})
|
||||
}
|
||||
|
||||
/**
|
||||
* @description:update user image
|
||||
* @method:POST
|
||||
* @router:/user/file/image/:key
|
||||
*/
|
||||
func PostUserFileImage(c *gin.Context) {
|
||||
//id := c.GetHeader("user_id")
|
||||
id := c.Param("id")
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&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/user/image?path=" + filePath
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
|
||||
}
|
||||
|
||||
/**
|
||||
* @description:create or update user's custom image
|
||||
* @param {formData} file file "a file to be uploaded"
|
||||
* @param {path} key string "file name"
|
||||
* @method:POST
|
||||
* @router:/user/upload/image/:key
|
||||
*/
|
||||
func PostUserUploadImage(c *gin.Context) {
|
||||
//id := c.GetHeader("user_id")
|
||||
id := c.Param("id")
|
||||
f, err := c.FormFile("file")
|
||||
key := c.Param("key")
|
||||
if len(key) == 0 {
|
||||
c.JSON(http.StatusOK, 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()})
|
||||
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)})
|
||||
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)})
|
||||
return
|
||||
}
|
||||
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/user/image?path=" + path
|
||||
c.JSON(http.StatusOK, 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)
|
||||
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
|
||||
c.File(filePath)
|
||||
}
|
||||
func DeleteUserImage(c *gin.Context) {
|
||||
// id := c.GetHeader("user_id")
|
||||
id := c.Param("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)})
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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)})
|
||||
return
|
||||
}
|
||||
os.Remove(path)
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
|
||||
}
|
||||
|
||||
////refresh token
|
||||
// func PostUserRefreshToken(c *gin.Context) {
|
||||
// json := make(map[string]string)
|
||||
// c.BindJSON(&json)
|
||||
// refresh := json["refresh_token"]
|
||||
// claims, err := jwt.ParseToken(refresh)
|
||||
// if err != nil {
|
||||
// c.JSON(http.StatusOK, model.Result{Success: common_err.ERROR, 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)})
|
||||
// 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})
|
||||
|
||||
// }
|
||||
|
||||
//******** soon to be removed ********
|
||||
|
||||
// @Summary 设置用户名和密码
|
||||
// @Produce application/json
|
||||
// @Accept multipart/form-data
|
||||
// @Tags user
|
||||
// @Param username formData string true "User name"
|
||||
// @Param pwd formData string true "password"
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /user/setusernamepwd [post]
|
||||
func Set_Name_Pwd(c *gin.Context) {
|
||||
json := make(map[string]string)
|
||||
c.BindJSON(&json)
|
||||
username := json["username"]
|
||||
pwd := json["pwd"]
|
||||
if service.MyService.User().GetUserCount() > 0 || len(username) == 0 || len(pwd) == 0 {
|
||||
c.JSON(http.StatusOK,
|
||||
model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
|
||||
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(http.StatusOK, model.Result{Success: common_err.ERROR, Message: common_err.GetMsg(common_err.ERROR)})
|
||||
return
|
||||
}
|
||||
file.MkDir(config.AppInfo.UserDataPath + "/" + strconv.Itoa(user.Id))
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: user})
|
||||
|
||||
}
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/IceWhaleTech/CasaOS/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// @Summary 获取cpu信息
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags zima
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /zima/getcpuinfo [get]
|
||||
func CupInfo(c *gin.Context) {
|
||||
//检查参数是否正确
|
||||
cpu := service.MyService.ZiMa().GetCpuPercent()
|
||||
num := service.MyService.ZiMa().GetCpuCoreNum()
|
||||
data := make(map[string]interface{})
|
||||
data["percent"] = cpu
|
||||
data["num"] = num
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
|
||||
|
||||
}
|
||||
|
||||
// @Summary 获取内存信息
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags zima
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /zima/getmeminfo [get]
|
||||
func MemInfo(c *gin.Context) {
|
||||
|
||||
//检查参数是否正确
|
||||
mem := service.MyService.ZiMa().GetMemInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: mem})
|
||||
|
||||
}
|
||||
|
||||
// @Summary 获取硬盘信息
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags zima
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /zima/getdiskinfo [get]
|
||||
func DiskInfo(c *gin.Context) {
|
||||
disk := service.MyService.ZiMa().GetDiskInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: disk})
|
||||
}
|
||||
|
||||
// @Summary 获取网络信息
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags zima
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /zima/getnetinfo [get]
|
||||
func NetInfo(c *gin.Context) {
|
||||
netList := service.MyService.ZiMa().GetNetInfo()
|
||||
|
||||
newNet := []model.IOCountersStat{}
|
||||
for _, n := range netList {
|
||||
for _, netCardName := range service.MyService.ZiMa().GetNet(true) {
|
||||
if n.Name == netCardName {
|
||||
item := *(*model.IOCountersStat)(unsafe.Pointer(&n))
|
||||
item.State = strings.TrimSpace(service.MyService.ZiMa().GetNetState(n.Name))
|
||||
item.Time = time.Now().Unix()
|
||||
newNet = append(newNet, item)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: newNet})
|
||||
}
|
||||
|
||||
// @Summary 获取信息系统信息
|
||||
// @Produce application/json
|
||||
// @Accept application/json
|
||||
// @Tags zima
|
||||
// @Security ApiKeyAuth
|
||||
// @Success 200 {string} string "ok"
|
||||
// @Router /zima/sysinfo [get]
|
||||
func SysInfo(c *gin.Context) {
|
||||
info := service.MyService.ZiMa().GetSysInfo()
|
||||
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: info})
|
||||
}
|
||||
116
service/app.go
116
service/app.go
@@ -7,7 +7,6 @@ import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -15,23 +14,19 @@ import (
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/docker/docker/api/types"
|
||||
"github.com/docker/docker/api/types/filters"
|
||||
client2 "github.com/docker/docker/client"
|
||||
"github.com/pkg/errors"
|
||||
uuid "github.com/satori/go.uuid"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AppService interface {
|
||||
CreateApplication(m model2.ApplicationModel) model2.ApplicationModel
|
||||
GetApplicationList() (m []model2.ApplicationModel)
|
||||
GetApplicationById(id string) (m model2.ApplicationModel)
|
||||
UpdateApplicationOrderById(id string, order int)
|
||||
GetMyList(index, size int, position bool) (*[]model2.MyAppList, *[]model2.MyAppList)
|
||||
GetCasaOSCount() int
|
||||
SaveContainer(m model2.AppListDBModel)
|
||||
GetUninstallInfo(id string) model2.AppListDBModel
|
||||
DeleteApp(id string)
|
||||
@@ -50,26 +45,7 @@ type AppService interface {
|
||||
}
|
||||
|
||||
type appStruct struct {
|
||||
db *gorm.DB
|
||||
log loger2.OLog
|
||||
}
|
||||
|
||||
func (a *appStruct) GetApplicationById(id string) (m model2.ApplicationModel) {
|
||||
a.db.Where("id = ?", id).First(&m)
|
||||
return
|
||||
}
|
||||
|
||||
func (a *appStruct) UpdateApplicationOrderById(id string, order int) {
|
||||
a.db.Model(&model2.ApplicationModel{}).Where("id = ?", id).Update("order", order)
|
||||
}
|
||||
|
||||
func (a *appStruct) CreateApplication(m model2.ApplicationModel) model2.ApplicationModel {
|
||||
a.db.Create(&m)
|
||||
return m
|
||||
}
|
||||
func (a *appStruct) GetApplicationList() (m []model2.ApplicationModel) {
|
||||
a.db.Find(&m)
|
||||
return
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (a *appStruct) CheckNewImage() {
|
||||
@@ -155,37 +131,13 @@ func (a *appStruct) ImportApplications(casaApp bool) {
|
||||
// }
|
||||
// MyService.Docker().DockerContainerStart(container_id)
|
||||
//}
|
||||
|
||||
}
|
||||
|
||||
func (a *appStruct) GetCasaOSCount() int {
|
||||
//获取docker应用
|
||||
cli, err := client2.NewClientWithOpts(client2.FromEnv, client2.WithTimeout(time.Second*5))
|
||||
if err != nil {
|
||||
a.log.Error("初始化client失败", "app.getmylist", "line:36", err)
|
||||
return 0
|
||||
}
|
||||
defer cli.Close()
|
||||
fts := filters.NewArgs()
|
||||
fts.Add("label", "casaos=casaos")
|
||||
//fts.Add("label", "casaos:casaos")
|
||||
|
||||
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{Filters: fts, Limit: 200})
|
||||
if err != nil {
|
||||
a.log.Error("获取docker容器失败", "app.getmylist", "line:42", err)
|
||||
return 0
|
||||
}
|
||||
|
||||
systemApp := MyService.App().GetApplicationList()
|
||||
return len(containers) + len(systemApp)
|
||||
}
|
||||
|
||||
//获取我的应用列表
|
||||
func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppList, *[]model2.MyAppList) {
|
||||
//获取docker应用
|
||||
cli, err := client2.NewClientWithOpts(client2.FromEnv, client2.WithTimeout(time.Second*5))
|
||||
if err != nil {
|
||||
a.log.Error("初始化client失败", "app.getmylist", "line:36", err)
|
||||
loger.Error("Failed to init client", zap.Any("err", err))
|
||||
}
|
||||
defer cli.Close()
|
||||
// fts := filters.NewArgs()
|
||||
@@ -194,7 +146,7 @@ func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppLi
|
||||
//fts.Add("casaos", "casaos")
|
||||
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true})
|
||||
if err != nil {
|
||||
a.log.Error("获取docker容器失败", "app.getmylist", "line:42", err)
|
||||
loger.Error("Failed to get container_list", zap.Any("err", err))
|
||||
}
|
||||
//获取本地数据库应用
|
||||
|
||||
@@ -202,23 +154,6 @@ func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppLi
|
||||
|
||||
list := []model2.MyAppList{}
|
||||
|
||||
systemApp := MyService.App().GetApplicationList()
|
||||
for _, v := range systemApp {
|
||||
list = append(list, model2.MyAppList{
|
||||
Name: v.Name,
|
||||
Icon: v.Icon,
|
||||
State: strconv.Itoa(v.State),
|
||||
Id: strconv.Itoa(v.Id),
|
||||
CustomId: strconv.Itoa(v.Id),
|
||||
Port: "",
|
||||
//Order: strconv.Itoa(v.Order),
|
||||
Index: "/",
|
||||
Image: "",
|
||||
Type: v.Type,
|
||||
NewVersion: false,
|
||||
})
|
||||
}
|
||||
|
||||
for _, m := range containers {
|
||||
if m.Labels["casaos"] == "casaos" {
|
||||
if m.Labels["origin"] == "system" {
|
||||
@@ -239,6 +174,8 @@ func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppLi
|
||||
Type: m.Labels["origin"],
|
||||
//Slogan: m.Slogan,
|
||||
//Rely: m.Rely,
|
||||
Host: m.Labels["host"],
|
||||
Protocol: m.Labels["protocol"],
|
||||
})
|
||||
} else {
|
||||
unTranslation = append(unTranslation, model2.MyAppList{
|
||||
@@ -249,6 +186,8 @@ func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppLi
|
||||
Id: m.ID,
|
||||
Port: "",
|
||||
NewVersion: false,
|
||||
Host: "",
|
||||
Protocol: "",
|
||||
Image: m.Image,
|
||||
})
|
||||
}
|
||||
@@ -304,14 +243,14 @@ func (a *appStruct) GetSystemAppList() []types.Container {
|
||||
//获取docker应用
|
||||
cli, err := client2.NewClientWithOpts(client2.FromEnv)
|
||||
if err != nil {
|
||||
a.log.Error("初始化client失败", "app.getmylist", "line:36", err)
|
||||
loger.Error("Failed to init client", zap.Any("err", err))
|
||||
}
|
||||
defer cli.Close()
|
||||
fts := filters.NewArgs()
|
||||
fts.Add("label", "origin=system")
|
||||
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts})
|
||||
if err != nil {
|
||||
a.log.Error("获取docker容器失败", "app.sys", "line:123", err)
|
||||
loger.Error("Failed to get container_list", zap.Any("err", err))
|
||||
}
|
||||
|
||||
//获取本地数据库应用
|
||||
@@ -339,13 +278,13 @@ func (a *appStruct) GetContainerInfo(name string) (types.Container, error) {
|
||||
//获取docker应用
|
||||
cli, err := client2.NewClientWithOpts(client2.FromEnv)
|
||||
if err != nil {
|
||||
a.log.Error("初始化client失败", "app.getmylist", "line:36", err)
|
||||
loger.Error("Failed to init client", zap.Any("err", err))
|
||||
}
|
||||
filters := filters.NewArgs()
|
||||
filters.Add("name", name)
|
||||
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: filters})
|
||||
if err != nil {
|
||||
a.log.Error("获取docker容器失败", "app.getcontainerinfo", "line:182", err)
|
||||
loger.Error("Failed to get container_list", zap.Any("err", err))
|
||||
}
|
||||
|
||||
if len(containers) > 0 {
|
||||
@@ -399,7 +338,7 @@ func (a *appStruct) UpdateApp(m model2.AppListDBModel) {
|
||||
}
|
||||
|
||||
func (a *appStruct) DelAppConfigDir(path string) {
|
||||
command.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;DelAppConfigDir " + path)
|
||||
command.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;DelAppConfigDir " + path)
|
||||
}
|
||||
|
||||
func (a *appStruct) DeleteApp(id string) {
|
||||
@@ -460,12 +399,8 @@ func (a *appStruct) GetHardwareUsageSteam() {
|
||||
|
||||
fts := filters.NewArgs()
|
||||
fts.Add("label", "casaos=casaos")
|
||||
//fts.Add("label", "casaos")
|
||||
//fts.Add("casaos", "casaos")
|
||||
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts})
|
||||
if err != nil {
|
||||
a.log.Error("获取docker容器失败", "app.getmylist", "line:42", err)
|
||||
}
|
||||
//fts.Add("status", "running")
|
||||
|
||||
for i := 0; i < 100; i++ {
|
||||
if config.CasaOSGlobalVariables.AppChange {
|
||||
config.CasaOSGlobalVariables.AppChange = false
|
||||
@@ -475,8 +410,16 @@ func (a *appStruct) GetHardwareUsageSteam() {
|
||||
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 {
|
||||
if v.State != "running" {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(v types.Container, i int) {
|
||||
defer wg.Done()
|
||||
@@ -497,20 +440,23 @@ func (a *appStruct) GetHardwareUsageSteam() {
|
||||
dockerStats.Data = data
|
||||
dockerStats.Icon = v.Labels["icon"]
|
||||
dockerStats.Title = strings.ReplaceAll(v.Names[0], "/", "")
|
||||
dataStats.Store(v.ID, dockerStats)
|
||||
|
||||
temp.Store(v.ID, dockerStats)
|
||||
if i == 99 {
|
||||
stats.Body.Close()
|
||||
}
|
||||
}(v, i)
|
||||
}
|
||||
wg.Wait()
|
||||
dataStats = temp
|
||||
isFinish = true
|
||||
time.Sleep(time.Second * 3)
|
||||
|
||||
time.Sleep(time.Second * 1)
|
||||
}
|
||||
isFinish = false
|
||||
cancel()
|
||||
}
|
||||
|
||||
func NewAppService(db *gorm.DB, logger loger2.OLog) AppService {
|
||||
return &appStruct{db: db, log: logger}
|
||||
func NewAppService(db *gorm.DB) AppService {
|
||||
return &appStruct{db: db}
|
||||
}
|
||||
|
||||
261
service/casa.go
261
service/casa.go
@@ -4,28 +4,34 @@ import (
|
||||
"encoding/json"
|
||||
json2 "encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
|
||||
httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/tidwall/gjson"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type CasaService interface {
|
||||
GetServerList(index, size, tp, categoryId, key, language string) (recommend, list, community []model.ServerAppList)
|
||||
GetServerCategoryList() []model.ServerCategoryList
|
||||
GetTaskList(size int) []model2.TaskDBModel
|
||||
GetServerList(index, size, tp, categoryId, key string) model.ServerAppListCollection
|
||||
GetServerCategoryList() []model.CategoryList
|
||||
GetServerAppInfo(id, t string, language string) model.ServerAppList
|
||||
ShareAppFile(body []byte) string
|
||||
PushHeart(id, t string, language string)
|
||||
PushAppAnalyse(uuid, t string, name, language string)
|
||||
|
||||
PushConnectionStatus(uuid, err string, from, to, event string)
|
||||
PushUserInfo()
|
||||
GetUserInfoByShareId(shareId string) model.UserInfo
|
||||
GetPersonPublic() (list []model.FriendsModel)
|
||||
GetCasaosVersion() model.Version
|
||||
AsyncGetServerList() (collection model.ServerAppListCollection)
|
||||
AsyncGetServerCategoryList() []model.CategoryList
|
||||
}
|
||||
|
||||
type casaService struct {
|
||||
@@ -40,62 +46,187 @@ func (o *casaService) ShareAppFile(body []byte) string {
|
||||
return content
|
||||
}
|
||||
|
||||
func (o *casaService) GetTaskList(size int) []model2.TaskDBModel {
|
||||
head := make(map[string]string)
|
||||
|
||||
head["Authorization"] = GetToken()
|
||||
|
||||
listS := httper2.Get(config.ServerInfo.ServerApi+"/v1/task/list/"+strconv.Itoa(size), head)
|
||||
|
||||
list := []model2.TaskDBModel{}
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list)
|
||||
|
||||
return list
|
||||
}
|
||||
|
||||
func (o *casaService) GetServerList(index, size, tp, categoryId, key, language string) (recommend, list, community []model.ServerAppList) {
|
||||
|
||||
keyName := fmt.Sprintf("list_%s_%s_%s_%s_%s", index, size, tp, categoryId, language)
|
||||
func (o *casaService) GetServerList(index, size, tp, categoryId, key string) model.ServerAppListCollection {
|
||||
|
||||
keyName := fmt.Sprintf("list_%s_%s_%s_%s_%s", index, size, tp, categoryId, "en")
|
||||
collection := model.ServerAppListCollection{}
|
||||
if result, ok := Cache.Get(keyName); ok {
|
||||
res, ok := result.(string)
|
||||
if ok {
|
||||
json2.Unmarshal([]byte(gjson.Get(res, "data.list").String()), &list)
|
||||
json2.Unmarshal([]byte(gjson.Get(res, "data.recommend").String()), &recommend)
|
||||
json2.Unmarshal([]byte(gjson.Get(res, "data.community").String()), &community)
|
||||
return
|
||||
json2.Unmarshal([]byte(res), &collection)
|
||||
return collection
|
||||
}
|
||||
}
|
||||
|
||||
collectionStr := file.ReadFullFile(config.AppInfo.DBPath + "/app_list.json")
|
||||
|
||||
err := json2.Unmarshal(collectionStr, &collection)
|
||||
if err != nil {
|
||||
loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(collectionStr)))
|
||||
collection = o.AsyncGetServerList()
|
||||
}
|
||||
|
||||
go o.AsyncGetServerList()
|
||||
|
||||
if categoryId != "0" {
|
||||
categoryInt, _ := strconv.Atoi(categoryId)
|
||||
nList := []model.ServerAppList{}
|
||||
for _, v := range collection.List {
|
||||
if v.CategoryId == categoryInt {
|
||||
nList = append(nList, v)
|
||||
}
|
||||
}
|
||||
collection.List = nList
|
||||
nCommunity := []model.ServerAppList{}
|
||||
for _, v := range collection.Community {
|
||||
if v.CategoryId == categoryInt {
|
||||
nCommunity = append(nCommunity, v)
|
||||
}
|
||||
}
|
||||
collection.Community = nCommunity
|
||||
}
|
||||
if tp != "name" {
|
||||
if tp == "new" {
|
||||
sort.Slice(collection.List, func(i, j int) bool {
|
||||
return collection.List[i].CreatedAt.After(collection.List[j].CreatedAt)
|
||||
})
|
||||
sort.Slice(collection.Community, func(i, j int) bool {
|
||||
return collection.Community[i].CreatedAt.After(collection.Community[j].CreatedAt)
|
||||
})
|
||||
} else if tp == "rank" {
|
||||
sort.Slice(collection.List, func(i, j int) bool {
|
||||
return collection.List[i].QueryCount > collection.List[j].QueryCount
|
||||
})
|
||||
sort.Slice(collection.Community, func(i, j int) bool {
|
||||
return collection.Community[i].QueryCount > collection.Community[j].QueryCount
|
||||
})
|
||||
}
|
||||
}
|
||||
sizeInt, _ := strconv.Atoi(size)
|
||||
|
||||
if index != "1" {
|
||||
indexInt, _ := strconv.Atoi(index)
|
||||
collection.List = collection.List[(indexInt-1)*sizeInt : indexInt*sizeInt]
|
||||
collection.Community = collection.Community[(indexInt-1)*sizeInt : indexInt*sizeInt]
|
||||
} else {
|
||||
if len(collection.List) > sizeInt {
|
||||
collection.List = collection.List[:sizeInt]
|
||||
}
|
||||
if len(collection.Community) > sizeInt {
|
||||
collection.Community = collection.Community[:sizeInt]
|
||||
}
|
||||
}
|
||||
|
||||
if len(collection.List) > 0 {
|
||||
by, _ := json.Marshal(collection)
|
||||
Cache.Set(keyName, string(by), time.Minute*10)
|
||||
}
|
||||
|
||||
return collection
|
||||
|
||||
}
|
||||
|
||||
func (o *casaService) AsyncGetServerList() (collection model.ServerAppListCollection) {
|
||||
|
||||
results := file.ReadFullFile(config.AppInfo.DBPath + "/app_list.json")
|
||||
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
|
||||
}
|
||||
|
||||
head := make(map[string]string)
|
||||
|
||||
head["Authorization"] = GetToken()
|
||||
|
||||
listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/newlist?index="+index+"&size="+size+"&rank="+tp+"&category_id="+categoryId+"&key="+key+"&language="+language, head)
|
||||
listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/newlist?index=1&size=1000&rank=name&category_id=0&key=&language=en", head)
|
||||
listModel := []model.ServerAppList{}
|
||||
communityModel := []model.ServerAppList{}
|
||||
recommendModel := []model.ServerAppList{}
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data.list").String()), &listModel)
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data.recommend").String()), &recommendModel)
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data.community").String()), &communityModel)
|
||||
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data.list").String()), &list)
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data.recommend").String()), &recommend)
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data.community").String()), &community)
|
||||
|
||||
if len(list) > 0 {
|
||||
Cache.SetDefault(keyName, listS)
|
||||
if len(listModel) > 0 {
|
||||
collection.Community = communityModel
|
||||
collection.List = listModel
|
||||
collection.Recommend = recommendModel
|
||||
collection.Version = o.GetCasaosVersion().Version
|
||||
by, err := json.Marshal(collection)
|
||||
if err != nil {
|
||||
loger.Error("marshal error", zap.Any("err", err))
|
||||
}
|
||||
file.WriteToPath(by, config.AppInfo.DBPath, "app_list.json")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (o *casaService) GetServerCategoryList() []model.ServerCategoryList {
|
||||
// func (o *casaService) GetServerCategoryList() (list []model.ServerCategoryList) {
|
||||
|
||||
// keyName := fmt.Sprintf("category_list")
|
||||
// if result, ok := Cache.Get(keyName); ok {
|
||||
// res, ok := result.(string)
|
||||
// if ok {
|
||||
// json2.Unmarshal([]byte(gjson.Get(res, "data").String()), &list)
|
||||
// return list
|
||||
// }
|
||||
// }
|
||||
|
||||
// head := make(map[string]string)
|
||||
// head["Authorization"] = GetToken()
|
||||
|
||||
// listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/category", head)
|
||||
|
||||
// json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list)
|
||||
// if len(list) > 0 {
|
||||
// Cache.Set(keyName, listS, time.Hour*24)
|
||||
// }
|
||||
// return list
|
||||
// }
|
||||
|
||||
func (o *casaService) GetServerCategoryList() (list []model.CategoryList) {
|
||||
category := model.ServerCategoryList{}
|
||||
results := file.ReadFullFile(config.AppInfo.DBPath + "/app_category.json")
|
||||
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
|
||||
}
|
||||
|
||||
func (o *casaService) AsyncGetServerCategoryList() []model.CategoryList {
|
||||
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
|
||||
}
|
||||
item := []model.CategoryList{}
|
||||
head := make(map[string]string)
|
||||
head["Authorization"] = GetToken()
|
||||
|
||||
listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/category", head)
|
||||
|
||||
list := []model.ServerCategoryList{}
|
||||
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list)
|
||||
|
||||
return list
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &item)
|
||||
if len(item) > 0 {
|
||||
list.Version = o.GetCasaosVersion().Version
|
||||
list.Item = item
|
||||
by, err := json.Marshal(list)
|
||||
if err != nil {
|
||||
loger.Error("marshal error", zap.Any("err", err))
|
||||
}
|
||||
file.WriteToPath(by, config.AppInfo.DBPath, "app_category.json")
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func (o *casaService) GetServerAppInfo(id, t string, language string) model.ServerAppList {
|
||||
|
||||
head := make(map[string]string)
|
||||
@@ -130,6 +261,34 @@ func GetToken() string {
|
||||
return auth
|
||||
}
|
||||
|
||||
/**
|
||||
* @description: get remote version
|
||||
* @return {model.Version}
|
||||
*/
|
||||
func (o *casaService) GetCasaosVersion() model.Version {
|
||||
keyName := "casa_version"
|
||||
var dataStr string
|
||||
var version model.Version
|
||||
if result, ok := Cache.Get(keyName); ok {
|
||||
dataStr, ok = result.(string)
|
||||
if ok {
|
||||
data := gjson.Get(dataStr, "data")
|
||||
json2.Unmarshal([]byte(data.String()), &version)
|
||||
return version
|
||||
}
|
||||
}
|
||||
|
||||
v := httper.OasisGet(config.ServerInfo.ServerApi + "/v1/sys/version")
|
||||
data := gjson.Get(v, "data")
|
||||
json2.Unmarshal([]byte(data.String()), &version)
|
||||
|
||||
if len(version.Version) > 0 {
|
||||
Cache.Set(keyName, v, time.Minute*20)
|
||||
}
|
||||
|
||||
return version
|
||||
}
|
||||
|
||||
func (o *casaService) PushHeart(id, t string, language string) {
|
||||
|
||||
m := model.CasaOSHeart{}
|
||||
@@ -148,26 +307,6 @@ func (o *casaService) PushHeart(id, t string, language string) {
|
||||
|
||||
}
|
||||
|
||||
func (o *casaService) PushAppAnalyse(uuid, t string, name, language string) {
|
||||
|
||||
m := model.AppAnalyse{}
|
||||
m.UUId = uuid
|
||||
m.Type = t
|
||||
m.Name = name
|
||||
m.Language = language
|
||||
m.Version = types.CURRENTVERSION
|
||||
b, _ := json.Marshal(m)
|
||||
|
||||
head := make(map[string]string)
|
||||
|
||||
head["Authorization"] = GetToken()
|
||||
|
||||
infoS := httper2.Post(config.ServerInfo.ServerApi+"/v1/analyse/app", b, "application/json", head)
|
||||
|
||||
info := model.ServerAppList{}
|
||||
json2.Unmarshal([]byte(gjson.Get(infoS, "data").String()), &info)
|
||||
|
||||
}
|
||||
func (o *casaService) PushConnectionStatus(uuid, err string, from, to, event string) {
|
||||
|
||||
m := model.ConnectionStatus{}
|
||||
|
||||
118
service/ddns.go
118
service/ddns.go
@@ -1,118 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
|
||||
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/IceWhaleTech/CasaOS/service/ddns"
|
||||
"github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type ddnsStruct struct {
|
||||
db *gorm.DB
|
||||
log loger2.OLog
|
||||
}
|
||||
|
||||
type DDNSService interface {
|
||||
IsExis(t int, domain string, host string) bool
|
||||
GetExternalIP() (string, string)
|
||||
GetConfigList() *[]model.DDNSList
|
||||
DeleteConfig(id uint) bool
|
||||
GetType(name string) (uint, string)
|
||||
SaveConfig(model model.DDNSUpdateDBModel) error
|
||||
}
|
||||
|
||||
//判断当前添加的是否存在
|
||||
func (d *ddnsStruct) IsExis(t int, domain string, host string) bool {
|
||||
var count int64
|
||||
d.db.Table(model.DDNSLISTTABLENAME).Where("type=? AND domain=? AND host=?", t, domain, host).Count(&count)
|
||||
|
||||
return count > 0
|
||||
}
|
||||
|
||||
//前台获取已配置的ddns列表
|
||||
func (d *ddnsStruct) GetConfigList() *[]model.DDNSList {
|
||||
var s []model.DDNSList
|
||||
d.db.Table(model.DDNSLISTTABLENAME).Select("o_ddns_type.name as name,o_ddns.id,host,domain,created_at,updated_at,message,state").Joins("left join o_ddns_type on o_ddns.type=o_ddns_type.id").Scan(&s)
|
||||
return &s
|
||||
}
|
||||
|
||||
func (d *ddnsStruct) DeleteConfig(id uint) bool {
|
||||
d.db.Delete(&model.DDNSUpdateDBModel{Id: id})
|
||||
return true
|
||||
}
|
||||
|
||||
func (d *ddnsStruct) GetExternalIP() (string, string) {
|
||||
ipv4 := make(chan string)
|
||||
ipv6 := make(chan string)
|
||||
go func() { ipv4 <- ip_helper2.GetExternalIPV4() }()
|
||||
go func() { ipv6 <- ip_helper2.GetExternalIPV6() }()
|
||||
|
||||
return <-ipv4, <-ipv6
|
||||
}
|
||||
|
||||
func NewDDNSService(db *gorm.DB, log loger2.OLog) DDNSService {
|
||||
return &ddnsStruct{db, log}
|
||||
}
|
||||
|
||||
//根据名称获取类型
|
||||
func (d *ddnsStruct) GetType(name string) (uint, string) {
|
||||
var result model.DDNSTypeDBModel
|
||||
d.db.Model(&model.DDNSTypeDBModel{}).Where("name = ?", name).First(&result)
|
||||
return result.Id, result.Name
|
||||
}
|
||||
|
||||
//保存配置到数据库
|
||||
func (d *ddnsStruct) GetDockerRootDir(model model.DDNSUpdateDBModel) error {
|
||||
return d.db.Create(&model).Error
|
||||
}
|
||||
|
||||
//保存配置到数据库
|
||||
func (d *ddnsStruct) SaveConfig(model model.DDNSUpdateDBModel) error {
|
||||
return d.db.Create(&model).Error
|
||||
}
|
||||
|
||||
//更新数据库ping状态
|
||||
func chackPing(b chan bool, url string) {
|
||||
cmd := exec.Command("ping", url, "-c", "1", "-W", "5")
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
b <- false
|
||||
} else {
|
||||
b <- true
|
||||
}
|
||||
}
|
||||
|
||||
//更新列表
|
||||
func UpdateDDNSList(db *gorm.DB) {
|
||||
var s []model.DDNSCoreList
|
||||
db.Table(model.DDNSLISTTABLENAME).Select("o_ddns_type.name as name,o_ddns_type.api_host as api_host,o_ddns.id,`host`,domain,user_name,`password`,`key`,secret,type").Joins("left join o_ddns_type on o_ddns.type=o_ddns_type.id").Scan(&s)
|
||||
for _, item := range s {
|
||||
var msg string
|
||||
switch item.Type {
|
||||
case 1:
|
||||
var godaddy = &ddns.GoDaddy{
|
||||
Host: item.Host,
|
||||
Key: item.Key,
|
||||
Secret: item.Secret,
|
||||
Domain: item.Domain,
|
||||
IPV4: ip_helper2.GetExternalIPV4(),
|
||||
IPV6: ip_helper2.GetExternalIPV6(),
|
||||
ApiHost: item.ApiHost,
|
||||
}
|
||||
msg = godaddy.Update()
|
||||
}
|
||||
|
||||
b := make(chan bool)
|
||||
|
||||
//获取ping状态
|
||||
go chackPing(b, item.Host+"."+item.Domain)
|
||||
|
||||
item.State = <-b
|
||||
item.Message = msg
|
||||
db.Table(model.DDNSLISTTABLENAME).Model(&item).Select("state", "message").Updates(&item)
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
package ddns
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func SetUserAgent(request *http.Request) {
|
||||
request.Header.Set("User-Agent", "Oasis lauren.pan@icewhale.org")
|
||||
}
|
||||
|
||||
func SetContentType(request *http.Request, contentType string) {
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
|
||||
func SetAccept(request *http.Request, acceptContent string) {
|
||||
request.Header.Set("Accept", acceptContent)
|
||||
}
|
||||
|
||||
func SetAuthBearer(request *http.Request, token string) {
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
|
||||
func SetAuthSSOKey(request *http.Request, key, secret string) {
|
||||
request.Header.Set("Authorization", "sso-key "+key+":"+secret)
|
||||
}
|
||||
|
||||
func SetOauth(request *http.Request, value string) {
|
||||
request.Header.Set("oauth", value)
|
||||
}
|
||||
|
||||
func SetXFilter(request *http.Request, value string) {
|
||||
request.Header.Set("X-Filter", value)
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
package ddns
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/ddns"
|
||||
"github.com/tidwall/gjson"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GoDaddyService interface {
|
||||
Update(ctx context.Context, client *http.Client)
|
||||
}
|
||||
type GoDaddy struct {
|
||||
Host string `json:"host"`
|
||||
Key string `json:"key"`
|
||||
Secret string `json:"secret"`
|
||||
Domain string `json:"domain"`
|
||||
IPV4 string `json:"ipv_4"`
|
||||
IPV6 string `json:"ipv_6"`
|
||||
ApiHost string `json:"api_host"`
|
||||
}
|
||||
|
||||
func (g *GoDaddy) Update() string {
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
recordType := ddns.A
|
||||
buffer1 := bytes.NewBuffer(nil)
|
||||
buffer1.WriteString(`[{"data":"`)
|
||||
buffer1.WriteString(g.IPV4)
|
||||
buffer1.WriteString(`"}]`)
|
||||
request, err := http.NewRequest(http.MethodPut, fmt.Sprintf("%s/v1/domains/%s/records/%s/%s", g.ApiHost, g.Domain, recordType, g.Host), buffer1)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
g.setHead(request)
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
defer response.Body.Close()
|
||||
b, err := ioutil.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if len(b) > 0 {
|
||||
r := gjson.GetBytes(b, "message")
|
||||
return r.String()
|
||||
}
|
||||
if len(g.IPV6) > 0 {
|
||||
recordType = ddns.AAAA
|
||||
buffer1 := bytes.NewBuffer(nil)
|
||||
buffer1.WriteString(`[{"data":"`)
|
||||
buffer1.WriteString(g.IPV6)
|
||||
buffer1.WriteString(`"}]`)
|
||||
request6, err := http.NewRequest(http.MethodPut, fmt.Sprintf("%s/v1/domains/%s/records/%s/%s", ddns.GODADDYAPIURL, g.Domain, recordType, g.Host), buffer1)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
g.setHead(request6)
|
||||
response6, err := client.Do(request6)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
defer response6.Body.Close()
|
||||
|
||||
d, err := ioutil.ReadAll(response6.Body)
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
if len(d) > 0 {
|
||||
r := gjson.GetBytes(d, "message")
|
||||
return r.String()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (g *GoDaddy) setHead(request *http.Request) {
|
||||
SetUserAgent(request)
|
||||
SetAuthSSOKey(request, g.Key, g.Secret)
|
||||
SetContentType(request, "application/json")
|
||||
SetAccept(request, "application/json")
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package ddns
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSetConfig(t *testing.T) {
|
||||
var model GoDaddy
|
||||
model.IPV4 = "180.164.179.198"
|
||||
model.Domain = "link-liang.xyz"
|
||||
model.Secret = "secret"
|
||||
model.Key = "key"
|
||||
//model.Type=ddns.GOGADDY
|
||||
//model.SetConfig()
|
||||
}
|
||||
@@ -11,10 +11,11 @@ import (
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
command2 "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/tidwall/gjson"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -37,8 +38,7 @@ type DiskService interface {
|
||||
RemoveLSBLKCache()
|
||||
}
|
||||
type diskService struct {
|
||||
log loger2.OLog
|
||||
db *gorm.DB
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (d *diskService) RemoveLSBLKCache() {
|
||||
@@ -58,47 +58,47 @@ func (d *diskService) SmartCTL(path string) model.SmartctlA {
|
||||
var m model.SmartctlA
|
||||
str := command2.ExecSmartCTLByPath(path)
|
||||
if str == nil {
|
||||
d.log.Error("smartctl exec error,smartctl")
|
||||
loger.Error("failed to exec shell ", zap.Any("err", "smartctl exec error"))
|
||||
return m
|
||||
}
|
||||
|
||||
err := json2.Unmarshal([]byte(str), &m)
|
||||
if err != nil {
|
||||
d.log.Error("json ummarshal error", err)
|
||||
loger.Error("Failed to unmarshal json", zap.Any("err", err))
|
||||
}
|
||||
if !reflect.DeepEqual(m, model.SmartctlA{}) {
|
||||
Cache.Add(key, m, time.Second*10)
|
||||
Cache.Add(key, m, time.Hour*24)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
//通过脚本获取外挂磁盘
|
||||
func (d *diskService) GetPlugInDisk() []string {
|
||||
return command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetPlugInDisk")
|
||||
return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetPlugInDisk")
|
||||
}
|
||||
|
||||
//格式化硬盘
|
||||
func (d *diskService) FormatDisk(path, format string) []string {
|
||||
r := command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;FormatDisk " + path + " " + format)
|
||||
r := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;FormatDisk " + path + " " + format)
|
||||
return r
|
||||
}
|
||||
|
||||
//移除挂载点,删除目录
|
||||
func (d *diskService) UmountPointAndRemoveDir(path string) []string {
|
||||
r := command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;UMountPorintAndRemoveDir " + path)
|
||||
r := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;UMountPorintAndRemoveDir " + path)
|
||||
return r
|
||||
}
|
||||
|
||||
//删除分区
|
||||
func (d *diskService) DelPartition(path, num string) string {
|
||||
r := command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;DelPartition " + path + " " + num)
|
||||
r := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;DelPartition " + path + " " + num)
|
||||
fmt.Println(r)
|
||||
return ""
|
||||
}
|
||||
|
||||
//part
|
||||
func (d *diskService) AddPartition(path string) string {
|
||||
command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;AddPartition " + path)
|
||||
command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;AddPartition " + path)
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -133,47 +133,13 @@ func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {
|
||||
|
||||
str := command2.ExecLSBLK()
|
||||
if str == nil {
|
||||
d.log.Error("lsblk exec error,lsblk")
|
||||
loger.Error("Failed to exec shell", zap.Any("err", "lsblk exec error"))
|
||||
return nil
|
||||
}
|
||||
var m []model.LSBLKModel
|
||||
// strStr := `{
|
||||
// "blockdevices": [
|
||||
// {"name":"loop0", "kname":"loop0", "path":"/dev/loop0", "maj:min":"7:0", "fsavail":"0", "fssize":"62M", "fstype":"squashfs", "fsused":"62M", "fsuse%":"100%", "fsver":"4.0", "mountpoint":"/snap/core20/1405", "label":null, "uuid":null, "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":true, "rm":false, "hotplug":false, "model":null, "serial":null, "size":619, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"mq-deadline", "rq-size":256, "type":"loop", "disc-aln":0, "disc-gran":"4K", "disc-max":"4G", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":null, "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"loop1", "kname":"loop1", "path":"/dev/loop1", "maj:min":"7:1", "fsavail":"0", "fssize":"55.6M", "fstype":"squashfs", "fsused":"55.6M", "fsuse%":"100%", "fsver":"4.0", "mountpoint":"/snap/core18/2344", "label":null, "uuid":null, "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":true, "rm":false, "hotplug":false, "model":null, "serial":null, "size":55, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"mq-deadline", "rq-size":256, "type":"loop", "disc-aln":0, "disc-gran":"4K", "disc-max":"4G", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":null, "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"loop2", "kname":"loop2", "path":"/dev/loop2", "maj:min":"7:2", "fsavail":"0", "fssize":"44.8M", "fstype":"squashfs", "fsused":"44.8M", "fsuse%":"100%", "fsver":"4.0", "mountpoint":"/snap/snapd/15314", "label":null, "uuid":null, "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":true, "rm":false, "hotplug":false, "model":null, "serial":null, "size":446, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"mq-deadline", "rq-size":256, "type":"loop", "disc-aln":0, "disc-gran":"4K", "disc-max":"4G", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":null, "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"loop3", "kname":"loop3", "path":"/dev/loop3", "maj:min":"7:3", "fsavail":"0", "fssize":"78.9M", "fstype":"squashfs", "fsused":"78.9M", "fsuse%":"100%", "fsver":"4.0", "mountpoint":"/snap/lxd/22754", "label":null, "uuid":null, "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":true, "rm":false, "hotplug":false, "model":null, "serial":null, "size":788, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"mq-deadline", "rq-size":256, "type":"loop", "disc-aln":0, "disc-gran":"4K", "disc-max":"4G", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":null, "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"loop4", "kname":"loop4", "path":"/dev/loop4", "maj:min":"7:4", "fsavail":"0", "fssize":"43.8M", "fstype":"squashfs", "fsused":"43.8M", "fsuse%":"100%", "fsver":"4.0", "mountpoint":"/snap/snapd/15177", "label":null, "uuid":null, "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":true, "rm":false, "hotplug":false, "model":null, "serial":null, "size":436, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"mq-deadline", "rq-size":256, "type":"loop", "disc-aln":0, "disc-gran":"4K", "disc-max":"4G", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":null, "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"loop5", "kname":"loop5", "path":"/dev/loop5", "maj:min":"7:5", "fsavail":"0", "fssize":"55.5M", "fstype":"squashfs", "fsused":"55.5M", "fsuse%":"100%", "fsver":"4.0", "mountpoint":"/snap/core18/1997", "label":null, "uuid":null, "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":true, "rm":false, "hotplug":false, "model":null, "serial":null, "size":554, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"mq-deadline", "rq-size":256, "type":"loop", "disc-aln":0, "disc-gran":"4K", "disc-max":"4G", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":null, "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"loop6", "kname":"loop6", "path":"/dev/loop6", "maj:min":"7:6", "fsavail":"0", "fssize":"80M", "fstype":"squashfs", "fsused":"80M", "fsuse%":"100%", "fsver":"4.0", "mountpoint":"/snap/lxd/22826", "label":null, "uuid":null, "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":true, "rm":false, "hotplug":false, "model":null, "serial":null, "size":799, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"mq-deadline", "rq-size":256, "type":"loop", "disc-aln":0, "disc-gran":"4K", "disc-max":"4G", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":null, "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"sda", "kname":"sda", "path":"/dev/sda", "maj:min":"8:0", "fsavail":null, "fssize":null, "fstype":null, "fsused":null, "fsuse%":null, "fsver":null, "mountpoint":null, "label":null, "uuid":null, "ptuuid":"1596101a-e20d-4296-96e2-0870efce554a", "pttype":"gpt", "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":"ST1000DM003-1ER1", "serial":"Z4YCS1B6", "size":9315, "state":"running", "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":4096, "opt-io":0, "phy-sec":4096, "log-sec":512, "rota":true, "sched":"mq-deadline", "rq-size":64, "type":"disk", "disc-aln":0, "disc-gran":"0B", "disc-max":"0B", "disc-zero":false, "wsame":"0B", "wwn":"0x5000c50090db103a", "rand":true, "pkname":null, "hctl":"0:0:0:0", "tran":"sata", "subsystems":"block:scsi:pci", "rev":"CC61", "vendor":"ATA ", "zoned":"none", "dax":false,
|
||||
// "children": [
|
||||
// {"name":"sda1", "kname":"sda1", "path":"/dev/sda1", "maj:min":"8:1", "fsavail":null, "fssize":null, "fstype":null, "fsused":null, "fsuse%":null, "fsver":null, "mountpoint":null, "label":null, "uuid":null, "ptuuid":"1596101a-e20d-4296-96e2-0870efce554a", "pttype":"gpt", "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":null, "serial":null, "size":9315, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":3072, "min-io":4096, "opt-io":0, "phy-sec":4096, "log-sec":512, "rota":true, "sched":"mq-deadline", "rq-size":64, "type":"part", "disc-aln":0, "disc-gran":"0B", "disc-max":"0B", "disc-zero":false, "wsame":"0B", "wwn":"0x5000c50090db103a", "rand":true, "pkname":"sda", "hctl":null, "tran":null, "subsystems":"block:scsi:pci", "rev":null, "vendor":null, "zoned":"none", "dax":false}
|
||||
// ]
|
||||
// },
|
||||
// {"name":"sdb", "kname":"sdb", "path":"/dev/sdb", "maj:min":"8:16", "fsavail":null, "fssize":null, "fstype":null, "fsused":null, "fsuse%":null, "fsver":null, "mountpoint":null, "label":null, "uuid":null, "ptuuid":"baed02d0-e92d-4a00-9609-f94f31271a0e", "pttype":"gpt", "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":"ST1000DM003-1ER1", "serial":"W4Y51MFH", "size":9315, "state":"running", "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":4096, "opt-io":0, "phy-sec":4096, "log-sec":512, "rota":true, "sched":"mq-deadline", "rq-size":64, "type":"disk", "disc-aln":0, "disc-gran":"0B", "disc-max":"0B", "disc-zero":false, "wsame":"0B", "wwn":"0x5000c5008acd2f00", "rand":true, "pkname":null, "hctl":"1:0:0:0", "tran":"sata", "subsystems":"block:scsi:pci", "rev":"CC46", "vendor":"ATA ", "zoned":"none", "dax":false,
|
||||
// "children": [
|
||||
// {"name":"sdb1", "kname":"sdb1", "path":"/dev/sdb1", "maj:min":"8:17", "fsavail":null, "fssize":null, "fstype":"zfs_member", "fsused":null, "fsuse%":null, "fsver":"5000", "mountpoint":null, "label":null, "uuid":null, "ptuuid":"baed02d0-e92d-4a00-9609-f94f31271a0e", "pttype":"gpt", "parttype":"0fc63daf-8483-4772-8e79-3d69d8477de4", "parttypename":"Linux filesystem", "partlabel":"primary", "partuuid":"57880cc0-2695-41c3-bf14-7161693e5bff", "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":null, "serial":null, "size":9315, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":3072, "min-io":4096, "opt-io":0, "phy-sec":4096, "log-sec":512, "rota":true, "sched":"mq-deadline", "rq-size":64, "type":"part", "disc-aln":0, "disc-gran":"0B", "disc-max":"0B", "disc-zero":false, "wsame":"0B", "wwn":"0x5000c5008acd2f00", "rand":true, "pkname":"sdb", "hctl":null, "tran":null, "subsystems":"block:scsi:pci", "rev":null, "vendor":null, "zoned":"none", "dax":false}
|
||||
// ]
|
||||
// },
|
||||
// {"name":"nvme0n1", "kname":"nvme0n1", "path":"/dev/nvme0n1", "maj:min":"259:0", "fsavail":null, "fssize":null, "fstype":null, "fsused":null, "fsuse%":null, "fsver":null, "mountpoint":null, "label":null, "uuid":null, "ptuuid":"338abc31-a3d4-4af2-9342-b53268d9e5ac", "pttype":"gpt", "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":"LITEON CL1-8D128-HP", "serial":"UJDJA01PJDH3UI", "size":1192, "state":"live", "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"none", "rq-size":255, "type":"disk", "disc-aln":0, "disc-gran":"512B", "disc-max":"2T", "disc-zero":false, "wsame":"0B", "wwn":"eui.0023035630392fe7", "rand":false, "pkname":null, "hctl":null, "tran":"nvme", "subsystems":"block:nvme:pci", "rev":null, "vendor":null, "zoned":"none", "dax":false,
|
||||
// "children": [
|
||||
// {"name":"nvme0n1p1", "kname":"nvme0n1p1", "path":"/dev/nvme0n1p1", "maj:min":"259:1", "fsavail":null, "fssize":null, "fstype":null, "fsused":null, "fsuse%":null, "fsver":null, "mountpoint":null, "label":null, "uuid":null, "ptuuid":"338abc31-a3d4-4af2-9342-b53268d9e5ac", "pttype":"gpt", "parttype":"21686148-6449-6e6f-744e-656564454649", "parttypename":"BIOS boot", "partlabel":null, "partuuid":"b2bac638-9468-449f-9669-79be44e3c80d", "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":null, "serial":null, "size":1, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"none", "rq-size":255, "type":"part", "disc-aln":0, "disc-gran":"512B", "disc-max":"2T", "disc-zero":false, "wsame":"0B", "wwn":"eui.0023035630392fe7", "rand":false, "pkname":"nvme0n1", "hctl":null, "tran":"nvme", "subsystems":"block:nvme:pci", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"nvme0n1p2", "kname":"nvme0n1p2", "path":"/dev/nvme0n1p2", "maj:min":"259:2", "fsavail":"1.2G", "fssize":"1.4G", "fstype":"ext4", "fsused":"131.5M", "fsuse%":"9%", "fsver":"1.0", "mountpoint":"/boot", "label":null, "uuid":"cd8164e9-bf7a-4684-8a3b-1d9f209b4930", "ptuuid":"338abc31-a3d4-4af2-9342-b53268d9e5ac", "pttype":"gpt", "parttype":"0fc63daf-8483-4772-8e79-3d69d8477de4", "parttypename":"Linux filesystem", "partlabel":null, "partuuid":"42ed9ed6-1221-4bea-901a-bc2f7b7cb9e1", "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":null, "serial":null, "size":15, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"none", "rq-size":255, "type":"part", "disc-aln":0, "disc-gran":"512B", "disc-max":"2T", "disc-zero":false, "wsame":"0B", "wwn":"eui.0023035630392fe7", "rand":false, "pkname":"nvme0n1", "hctl":null, "tran":"nvme", "subsystems":"block:nvme:pci", "rev":null, "vendor":null, "zoned":"none", "dax":false},
|
||||
// {"name":"nvme0n1p3", "kname":"nvme0n1p3", "path":"/dev/nvme0n1p3", "maj:min":"259:3", "fsavail":null, "fssize":null, "fstype":"LVM2_member", "fsused":null, "fsuse%":null, "fsver":"LVM2 001", "mountpoint":null, "label":null, "uuid":"0G7ryL-p2Ks-i9HS-wvEO-lXHs-oyZX-1KIlZO", "ptuuid":"338abc31-a3d4-4af2-9342-b53268d9e5ac", "pttype":"gpt", "parttype":"0fc63daf-8483-4772-8e79-3d69d8477de4", "parttypename":"Linux filesystem", "partlabel":null, "partuuid":"f6ae2e8c-14ae-4d94-89f1-2c154e909843", "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":null, "serial":null, "size":1177, "state":null, "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":"none", "rq-size":255, "type":"part", "disc-aln":0, "disc-gran":"512B", "disc-max":"2T", "disc-zero":false, "wsame":"0B", "wwn":"eui.0023035630392fe7", "rand":false, "pkname":"nvme0n1", "hctl":null, "tran":"nvme", "subsystems":"block:nvme:pci", "rev":null, "vendor":null, "zoned":"none", "dax":false,
|
||||
// "children": [
|
||||
// {"name":"ubuntu--vg-ubuntu--lv", "kname":"dm-0", "path":"/dev/mapper/ubuntu--vg-ubuntu--lv", "maj:min":"253:0", "fsavail":"78.6G", "fssize":"115.4G", "fstype":"ext4", "fsused":"30.9G", "fsuse%":"27%", "fsver":"1.0", "mountpoint":"/", "label":null, "uuid":"e8a9082f-3643-4820-a5e5-05817d7738c6", "ptuuid":null, "pttype":null, "parttype":null, "parttypename":null, "partlabel":null, "partuuid":null, "partflags":null, "ra":128, "ro":false, "rm":false, "hotplug":false, "model":null, "serial":null, "size":1177, "state":"running", "owner":"root", "group":"disk", "mode":"brw-rw----", "alignment":0, "min-io":512, "opt-io":0, "phy-sec":512, "log-sec":512, "rota":false, "sched":null, "rq-size":128, "type":"lvm", "disc-aln":0, "disc-gran":"512B", "disc-max":"2T", "disc-zero":false, "wsame":"0B", "wwn":null, "rand":false, "pkname":"nvme0n1p3", "hctl":null, "tran":null, "subsystems":"block", "rev":null, "vendor":null, "zoned":"none", "dax":false}
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
// ]
|
||||
// }`
|
||||
// fmt.Println(gjson.Get(strStr, "blockdevices").String())
|
||||
err := json2.Unmarshal([]byte(gjson.Get(string(str), "blockdevices").String()), &m)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
d.log.Error("json ummarshal error", err)
|
||||
loger.Error("Failed to unmarshal json", zap.Any("err", err))
|
||||
}
|
||||
|
||||
var c []model.LSBLKModel
|
||||
@@ -186,7 +152,7 @@ func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {
|
||||
fsused = 0
|
||||
for _, child := range i.Children {
|
||||
if child.RM {
|
||||
child.Health = strings.TrimSpace(command2.ExecResultStr("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetDiskHealthState " + child.Path))
|
||||
child.Health = strings.TrimSpace(command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDiskHealthState " + child.Path))
|
||||
if strings.ToLower(strings.TrimSpace(child.State)) != "ok" {
|
||||
health = false
|
||||
}
|
||||
@@ -197,7 +163,7 @@ func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {
|
||||
}
|
||||
c = append(c, child)
|
||||
}
|
||||
i.Format = strings.TrimSpace(command2.ExecResultStr("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetDiskType " + i.Path))
|
||||
//i.Format = strings.TrimSpace(command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDiskType " + i.Path))
|
||||
if health {
|
||||
i.Health = "OK"
|
||||
}
|
||||
@@ -206,7 +172,7 @@ func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {
|
||||
if fsused > 0 {
|
||||
i.UsedPercent, err = strconv.ParseFloat(fmt.Sprintf("%.4f", float64(fsused)/float64(i.Size)), 64)
|
||||
if err != nil {
|
||||
d.log.Fatal("diskservice_lsblk_fsused", err)
|
||||
loger.Error("Failed to parse float", zap.Any("err", err))
|
||||
}
|
||||
}
|
||||
n = append(n, i)
|
||||
@@ -224,15 +190,14 @@ func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {
|
||||
func (d *diskService) GetDiskInfo(path string) model.LSBLKModel {
|
||||
str := command2.ExecLSBLKByPath(path)
|
||||
if str == nil {
|
||||
d.log.Error("lsblk exec error,str")
|
||||
loger.Error("Failed to exec shell", zap.Any("err", "lsblk exec error"))
|
||||
return model.LSBLKModel{}
|
||||
}
|
||||
|
||||
var ml []model.LSBLKModel
|
||||
err := json2.Unmarshal([]byte(gjson.Get(string(str), "blockdevices").String()), &ml)
|
||||
if err != nil {
|
||||
d.log.Info(string(str))
|
||||
d.log.Error("json ummarshal error", err)
|
||||
loger.Error("Failed to unmarshal json", zap.Any("err", err))
|
||||
return model.LSBLKModel{}
|
||||
}
|
||||
|
||||
@@ -243,10 +208,9 @@ func (d *diskService) GetDiskInfo(path string) model.LSBLKModel {
|
||||
return m
|
||||
// 下面为计算是否可以继续分区的部分,暂时不需要
|
||||
chiArr := make(map[string]string)
|
||||
chiList := command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetPartitionSectors " + m.Path)
|
||||
chiList := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetPartitionSectors " + m.Path)
|
||||
if len(chiList) == 0 {
|
||||
d.log.Error(m.Path, chiList)
|
||||
d.log.Error("chiList length error")
|
||||
loger.Error("chiList length error", zap.Any("err", "chiList length error"))
|
||||
}
|
||||
for i := 0; i < len(chiList); i++ {
|
||||
tempArr := strings.Split(chiList[i], ",")
|
||||
@@ -262,10 +226,10 @@ func (d *diskService) GetDiskInfo(path string) model.LSBLKModel {
|
||||
}
|
||||
|
||||
}
|
||||
diskEndSector := command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetDiskSizeAndSectors " + m.Path)
|
||||
diskEndSector := command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDiskSizeAndSectors " + m.Path)
|
||||
|
||||
if len(diskEndSector) < 2 {
|
||||
d.log.Error("diskEndSector length error")
|
||||
loger.Error("diskEndSector length error", zap.Any("err", "diskEndSector length error"))
|
||||
}
|
||||
diskEndSectorInt, _ := strconv.ParseUint(diskEndSector[len(diskEndSector)-1], 10, 64)
|
||||
if (diskEndSectorInt-maxSector)*m.MinIO/1024/1024 > 100 {
|
||||
@@ -278,7 +242,7 @@ func (d *diskService) GetDiskInfo(path string) model.LSBLKModel {
|
||||
}
|
||||
|
||||
func (d *diskService) MountDisk(path, volume string) {
|
||||
r := command2.ExecResultStr("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;do_mount " + path + " " + volume)
|
||||
r := command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;do_mount " + path + " " + volume)
|
||||
fmt.Print(r)
|
||||
}
|
||||
|
||||
@@ -300,7 +264,7 @@ func (d *diskService) DeleteMountPoint(path, mountPoint string) {
|
||||
|
||||
d.db.Where("path = ? AND mount_point = ?", path, mountPoint).Delete(&model2.SerialDisk{})
|
||||
|
||||
command2.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;do_umount " + path)
|
||||
command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;do_umount " + path)
|
||||
}
|
||||
|
||||
func (d *diskService) GetSerialAll() []model2.SerialDisk {
|
||||
@@ -309,6 +273,6 @@ func (d *diskService) GetSerialAll() []model2.SerialDisk {
|
||||
return m
|
||||
}
|
||||
|
||||
func NewDiskService(log loger2.OLog, db *gorm.DB) DiskService {
|
||||
return &diskService{log: log, db: db}
|
||||
func NewDiskService(db *gorm.DB) DiskService {
|
||||
return &diskService{db: db}
|
||||
}
|
||||
|
||||
@@ -7,23 +7,22 @@ import (
|
||||
"encoding/binary"
|
||||
json2 "encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"syscall"
|
||||
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
types2 "github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/IceWhaleTech/CasaOS/model/notify"
|
||||
"github.com/containerd/containerd"
|
||||
"github.com/containerd/containerd/cio"
|
||||
"github.com/containerd/containerd/namespaces"
|
||||
"github.com/containerd/containerd/oci"
|
||||
"github.com/pkg/errors"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/docker"
|
||||
command2 "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/env_helper"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
|
||||
//"github.com/containerd/containerd/oci"
|
||||
"io"
|
||||
@@ -44,9 +43,9 @@ import (
|
||||
)
|
||||
|
||||
type DockerService interface {
|
||||
DockerPullImage(imageName string, m model2.AppNotify) error
|
||||
DockerPullImage(imageName string, icon, name string) error
|
||||
IsExistImage(imageName string) bool
|
||||
DockerContainerCreate(imageName string, m model.CustomizationPostData, net string) (containerId string, err error)
|
||||
DockerContainerCreate(imageName string, m model.CustomizationPostData) (containerId string, err error)
|
||||
DockerContainerCopyCreate(info *types.ContainerJSON) (containerId string, err error)
|
||||
DockerContainerStart(name string) error
|
||||
DockerContainerStats(name string) (string, error)
|
||||
@@ -69,7 +68,6 @@ type DockerService interface {
|
||||
|
||||
type dockerService struct {
|
||||
rootDir string
|
||||
log loger2.OLog
|
||||
}
|
||||
|
||||
func (ds *dockerService) DockerContainerList() []types.Container {
|
||||
@@ -319,7 +317,7 @@ func (ds *dockerService) IsExistImage(imageName string) bool {
|
||||
}
|
||||
|
||||
//安装镜像
|
||||
func (ds *dockerService) DockerPullImage(imageName string, m model2.AppNotify) error {
|
||||
func (ds *dockerService) DockerPullImage(imageName string, icon, name string) error {
|
||||
cli, err := client2.NewClientWithOpts(client2.FromEnv)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -334,7 +332,8 @@ func (ds *dockerService) DockerPullImage(imageName string, m model2.AppNotify) e
|
||||
|
||||
return err
|
||||
}
|
||||
buf := make([]byte, 256)
|
||||
//io.Copy()
|
||||
buf := make([]byte, 2048*4)
|
||||
for {
|
||||
n, err := out.Read(buf)
|
||||
if err != nil {
|
||||
@@ -343,11 +342,16 @@ func (ds *dockerService) DockerPullImage(imageName string, m model2.AppNotify) e
|
||||
}
|
||||
break
|
||||
}
|
||||
if !reflect.DeepEqual(m, model2.AppNotify{}) {
|
||||
m.Type = types2.NOTIFY_TYPE_INSTALL_LOG
|
||||
m.State = 0
|
||||
m.Message = string(buf[:n])
|
||||
MyService.Notify().UpdateLog(m)
|
||||
if len(icon) > 0 && len(name) > 0 {
|
||||
notify := notify.Application{}
|
||||
notify.Icon = icon
|
||||
notify.Name = name
|
||||
notify.State = "PULLING"
|
||||
notify.Type = "INSTALL"
|
||||
notify.Finished = false
|
||||
notify.Success = true
|
||||
notify.Message = string(buf[:n])
|
||||
MyService.Notify().SendInstallAppBySocket(notify)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -372,9 +376,9 @@ func (ds *dockerService) DockerContainerCopyCreate(info *types.ContainerJSON) (c
|
||||
//param mapPort 容器主端口映射到外部的端口
|
||||
//param tcp 容器其他tcp端口
|
||||
//param udp 容器其他udp端口
|
||||
func (ds *dockerService) DockerContainerCreate(imageName string, m model.CustomizationPostData, net string) (containerId string, err error) {
|
||||
if len(net) == 0 {
|
||||
net = "bridge"
|
||||
func (ds *dockerService) DockerContainerCreate(imageName string, m model.CustomizationPostData) (containerId string, err error) {
|
||||
if len(m.NetworkModel) == 0 {
|
||||
m.NetworkModel = "bridge"
|
||||
}
|
||||
|
||||
cli, err := client2.NewClientWithOpts(client2.FromEnv)
|
||||
@@ -398,7 +402,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
tContainer, _ := strconv.Atoi(portMap.ContainerPort)
|
||||
if tContainer > 0 {
|
||||
ports[nat.Port(portMap.ContainerPort+"/tcp")] = struct{}{}
|
||||
if net != "host" {
|
||||
if m.NetworkModel != "host" {
|
||||
portMaps[nat.Port(portMap.ContainerPort+"/tcp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
|
||||
}
|
||||
}
|
||||
@@ -407,7 +411,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
tContainer, _ := strconv.Atoi(portMap.ContainerPort)
|
||||
if tContainer > 0 {
|
||||
ports[nat.Port(portMap.ContainerPort+"/tcp")] = struct{}{}
|
||||
if net != "host" {
|
||||
if m.NetworkModel != "host" {
|
||||
portMaps[nat.Port(portMap.ContainerPort+"/tcp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
|
||||
}
|
||||
}
|
||||
@@ -415,7 +419,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
uContainer, _ := strconv.Atoi(portMap.ContainerPort)
|
||||
if uContainer > 0 {
|
||||
ports[nat.Port(portMap.ContainerPort+"/udp")] = struct{}{}
|
||||
if net != "host" {
|
||||
if m.NetworkModel != "host" {
|
||||
portMaps[nat.Port(portMap.ContainerPort+"/udp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
|
||||
}
|
||||
}
|
||||
@@ -424,7 +428,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
uContainer, _ := strconv.Atoi(portMap.ContainerPort)
|
||||
if uContainer > 0 {
|
||||
ports[nat.Port(portMap.ContainerPort+"/udp")] = struct{}{}
|
||||
if net != "host" {
|
||||
if m.NetworkModel != "host" {
|
||||
portMaps[nat.Port(portMap.ContainerPort+"/udp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
|
||||
}
|
||||
}
|
||||
@@ -433,7 +437,10 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
}
|
||||
|
||||
var envArr []string
|
||||
var showENV []string
|
||||
showENV = append(showENV, "casaos")
|
||||
for _, e := range m.Envs {
|
||||
showENV = append(showENV, e.Name)
|
||||
if strings.HasPrefix(e.Value, "$") {
|
||||
envArr = append(envArr, e.Name+"="+env_helper.ReplaceDefaultENV(e.Value, MyService.System().GetTimeZone()))
|
||||
continue
|
||||
@@ -476,7 +483,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
//if len(result1) == 0 {
|
||||
err = file.IsNotExistMkDir(path)
|
||||
if err != nil {
|
||||
ds.log.Error("mkdir error", err)
|
||||
loger.Error("Failed to create a folder", zap.Any("err", err))
|
||||
continue
|
||||
}
|
||||
//}
|
||||
@@ -530,8 +537,10 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
config.Labels["desc"] = m.Description
|
||||
config.Labels["index"] = m.Index
|
||||
config.Labels["custom_id"] = m.CustomId
|
||||
//config.Labels["order"] = strconv.Itoa(MyService.App().GetCasaOSCount() + 1)
|
||||
hostConfig := &container.HostConfig{Resources: res, Mounts: volumes, RestartPolicy: rp, NetworkMode: container.NetworkMode(net), Privileged: m.Privileged, CapAdd: m.CapAdd}
|
||||
config.Labels["show_env"] = strings.Join(showENV, ",")
|
||||
config.Labels["protocol"] = m.Protocol
|
||||
config.Labels["host"] = m.Host
|
||||
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
|
||||
hostConfig.PortBindings = portMaps
|
||||
@@ -540,7 +549,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
|
||||
containerDb, err := cli.ContainerCreate(context.Background(),
|
||||
config,
|
||||
hostConfig,
|
||||
&network.NetworkingConfig{EndpointsConfig: map[string]*network.EndpointSettings{net: {NetworkID: "", Aliases: []string{}}}},
|
||||
&network.NetworkingConfig{EndpointsConfig: map[string]*network.EndpointSettings{m.NetworkModel: {NetworkID: "", Aliases: []string{}}}},
|
||||
nil,
|
||||
m.Label)
|
||||
if err != nil {
|
||||
@@ -827,8 +836,8 @@ func (ds *dockerService) DockerNetworkModelList() []types.NetworkResource {
|
||||
networks, _ := cli.NetworkList(context.Background(), types.NetworkListOptions{})
|
||||
return networks
|
||||
}
|
||||
func NewDockerService(log loger2.OLog) DockerService {
|
||||
return &dockerService{rootDir: command2.ExecResultStr(`source ./shell/helper.sh ;GetDockerRootDir`), log: log}
|
||||
func NewDockerService() DockerService {
|
||||
return &dockerService{rootDir: command2.ExecResultStr(`source ./shell/helper.sh ;GetDockerRootDir`)}
|
||||
}
|
||||
|
||||
// ---------------------------------------test------------------------------------
|
||||
|
||||
141
service/file.go
141
service/file.go
@@ -1,38 +1,33 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2021-12-20 14:15:46
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-16 16:47:46
|
||||
* @FilePath: /CasaOS/service/file.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// type InteruptReader struct {
|
||||
// r io.Reader
|
||||
// interupt chan int
|
||||
// }
|
||||
var FileQueue sync.Map
|
||||
|
||||
// func NewInteruptReader(r io.Reader) InteruptReader {
|
||||
// return InteruptReader{
|
||||
// r,
|
||||
// make(chan int),
|
||||
// }
|
||||
// }
|
||||
|
||||
// func (r InteruptReader) Read(p []byte) (n int, err error) {
|
||||
// if r.r == nil {
|
||||
// return 0, io.EOF
|
||||
// }
|
||||
// select {
|
||||
// case <-r.interupt:
|
||||
// return r.r.Read(p)
|
||||
// default:
|
||||
// r.r = nil
|
||||
// return 0, io.EOF
|
||||
// }
|
||||
// }
|
||||
|
||||
// func (r InteruptReader) Cancel() {
|
||||
// r.interupt <- 0
|
||||
// }
|
||||
var OpStrArr []string
|
||||
|
||||
type reader struct {
|
||||
ctx context.Context
|
||||
@@ -83,3 +78,95 @@ func (w *writer) Write(p []byte) (n int, err error) {
|
||||
return w.w.Write(p)
|
||||
}
|
||||
}
|
||||
func FileOperate(k string) {
|
||||
|
||||
list, ok := FileQueue.Load(k)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
temp := list.(model.FileOperate)
|
||||
if temp.ProcessedSize > 0 {
|
||||
return
|
||||
}
|
||||
for i := 0; i < len(temp.Item); i++ {
|
||||
v := temp.Item[i]
|
||||
if temp.Type == "move" {
|
||||
lastPath := v.From[strings.LastIndex(v.From, "/")+1:]
|
||||
if !file.CheckNotExist(temp.To + "/" + lastPath) {
|
||||
if temp.Style == "skip" {
|
||||
temp.Item[i].Finished = true
|
||||
continue
|
||||
} else {
|
||||
os.RemoveAll(temp.To + "/" + lastPath)
|
||||
}
|
||||
}
|
||||
|
||||
err := os.Rename(v.From, temp.To+"/"+lastPath)
|
||||
if err != nil {
|
||||
loger.Debug("file move error", zap.Any("err", err))
|
||||
continue
|
||||
}
|
||||
} else if temp.Type == "copy" {
|
||||
err := file.CopyDir(v.From, temp.To, temp.Style)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
temp.Finished = true
|
||||
FileQueue.Store(k, temp)
|
||||
}
|
||||
|
||||
func ExecOpFile() {
|
||||
len := len(OpStrArr)
|
||||
if len == 0 {
|
||||
return
|
||||
}
|
||||
if len > 1 {
|
||||
len = 1
|
||||
}
|
||||
for i := 0; i < len; i++ {
|
||||
go FileOperate(OpStrArr[i])
|
||||
}
|
||||
}
|
||||
|
||||
// file move or copy and send notify
|
||||
func CheckFileStatus() {
|
||||
for {
|
||||
if len(OpStrArr) == 0 {
|
||||
return
|
||||
}
|
||||
for _, v := range OpStrArr {
|
||||
var total int64 = 0
|
||||
item, ok := FileQueue.Load(v)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
temp := item.(model.FileOperate)
|
||||
for i := 0; i < len(temp.Item); i++ {
|
||||
|
||||
if !temp.Item[i].Finished {
|
||||
size, err := file.GetFileOrDirSize(temp.To + "/" + filepath.Base(temp.Item[i].From))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
temp.Item[i].ProcessedSize = size
|
||||
if size == temp.Item[i].Size {
|
||||
temp.Item[i].Finished = true
|
||||
}
|
||||
total += size
|
||||
} else {
|
||||
total += temp.Item[i].ProcessedSize
|
||||
}
|
||||
|
||||
}
|
||||
temp.ProcessedSize = total
|
||||
FileQueue.Store(v, temp)
|
||||
}
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/google/go-github/v36/github"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
type GithubService interface {
|
||||
GetManifestJsonByRepo() (image, tcp, udp string)
|
||||
}
|
||||
|
||||
type githubService struct {
|
||||
cl *github.Client
|
||||
}
|
||||
|
||||
func (g *githubService) GetManifestJsonByRepo() (image, tcp, udp string) {
|
||||
c, _, _, e := g.cl.Repositories.GetContents(context.Background(), "a624669980", "o_test_json", "/OasisManifest.json", &github.RepositoryContentGetOptions{})
|
||||
if e != nil {
|
||||
fmt.Println(e)
|
||||
}
|
||||
str, e := c.GetContent()
|
||||
if e != nil {
|
||||
fmt.Println(e)
|
||||
}
|
||||
image = gjson.Get(str, "dockerImage").String()
|
||||
tcp = gjson.Get(str, "tcp_ports").Raw
|
||||
udp = gjson.Get(str, "udp_ports").Raw
|
||||
return
|
||||
}
|
||||
|
||||
func GetNewGithubService(cl *github.Client) GithubService {
|
||||
return &githubService{cl: cl}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApplicationModel struct {
|
||||
Id int `gorm:"column:id;primary_key" json:"id"`
|
||||
Name string `json:"name"`
|
||||
Icon string `json:"icon"`
|
||||
State int `json:"state"`
|
||||
Type string `json:"type"`
|
||||
Order int `json:"order"`
|
||||
CreatedAt time.Time `gorm:"<-:create" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"<-:create;<-:update" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (p *ApplicationModel) TableName() string {
|
||||
return "o_application"
|
||||
}
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-13 18:15:46
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-05-30 17:33:21
|
||||
* @FilePath: /CasaOS/service/model/o_container.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package model
|
||||
|
||||
const CONTAINERTABLENAME = "o_container"
|
||||
@@ -64,4 +74,6 @@ type MyAppList struct {
|
||||
Image string `json:"image"`
|
||||
Volumes string `json:"volumes"`
|
||||
NewVersion bool `json:"new_version"`
|
||||
Host string `json:"host"`
|
||||
Protocol string `json:"protocol"`
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
func (p *DDNSUpdateDBModel) TableName() string {
|
||||
return "o_ddns"
|
||||
}
|
||||
|
||||
type DDNSUpdateDBModel struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
Ipv4 string `gorm:"-"`
|
||||
Ipv6 string `gorm:"-"`
|
||||
Type uint `json:"type" form:"type"`
|
||||
Domain string `json:"domain" form:"domain"`
|
||||
Host string `json:"host" form:"host"`
|
||||
Key string `json:"key" form:"key"`
|
||||
Secret string `json:"secret" form:"secret"`
|
||||
UserName string `json:"user_name" form:"user_name"`
|
||||
Password string `json:"password" form:"password"`
|
||||
CreatedAt time.Time `gorm:"<-:create" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"<-:create;<-:update" json:"updated_at"`
|
||||
}
|
||||
|
||||
const DDNSLISTTABLENAME = "o_ddns"
|
||||
|
||||
//返回给前台使用
|
||||
type DDNSList struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
Name string `json:"name"`
|
||||
Domain string `json:"domain" form:"domain"`
|
||||
Host string `json:"host" form:"host"`
|
||||
IPV4 string `json:"ipv_4" gorm:"-"`
|
||||
IPV6 string `json:"ipv_6" gorm:"-"`
|
||||
Message string `json:"message"`
|
||||
State bool `json:"state"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
//定时任务使用
|
||||
type DDNSCoreList struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
Domain string `json:"domain" form:"domain"`
|
||||
Name string `json:"name" form:"name"`
|
||||
Type uint `json:"type"`
|
||||
Key string `json:"key"`
|
||||
Message string `json:"message"`
|
||||
State bool `json:"state"`
|
||||
Secret string `json:"secret" form:"secret"`
|
||||
UserName string `json:"user_name" form:"user_name"`
|
||||
Password string `json:"password" form:"password"`
|
||||
ApiHost string `json:"api_host"`
|
||||
Host string `json:"host"`
|
||||
IPV4 string `json:"ipv_4" gorm:"-"`
|
||||
IPV6 string `json:"ipv_6" gorm:"-"`
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package model
|
||||
|
||||
type DDNSTypeDBModel struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
Name string `json:"name"`
|
||||
ApiHost string `json:"api_host"`
|
||||
}
|
||||
|
||||
func (p *DDNSTypeDBModel) TableName() string {
|
||||
return "o_ddns_type"
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type ShareDirDBModel struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
Name string `gorm:"size:50" json:"name"`
|
||||
Comment string `gorm:"size:200" json:"comment"`
|
||||
Path string `json:"path"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
Writeable bool `json:"writeable"`
|
||||
Browseable bool `json:"browseable"`
|
||||
ValidUsers string `gorm:"size:200" json:"valid_users"` //可以访问的用户 多用户用 , 分割
|
||||
CreatedAt time.Time `gorm:"<-:create" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"<-:create;<-:update" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (p *ShareDirDBModel) TableName() string {
|
||||
return "o_share_directory"
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package model
|
||||
|
||||
type TaskDBModel struct {
|
||||
Id uint `gorm:"column:id;primary_key" json:"id"`
|
||||
Title string `gorm:"size:200" json:"title"`
|
||||
ImageUrl string `json:"image_url"`
|
||||
Content string `gorm:"size:255" json:"content"`
|
||||
Url string `json:"url"`
|
||||
State int `json:"state"` // 0:未阅读,1:已阅读
|
||||
Type int `json:"type"`
|
||||
CreatedAt string `gorm:"<-:create;autoCreateTime" json:"created_at"`
|
||||
UpdatedAt string `gorm:"<-:create;<-:update;autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (p *TaskDBModel) TableName() string {
|
||||
return "o_task"
|
||||
}
|
||||
31
service/model/o_user.go
Normal file
31
service/model/o_user.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-05-13 18:15:46
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-23 15:43:07
|
||||
* @FilePath: /CasaOS/service/model/o_user.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
//Soon to be removed
|
||||
type UserDBModel struct {
|
||||
Id int `gorm:"column:id;primary_key" json:"id"`
|
||||
UserName string `json:"user_name"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Role string `json:"role"`
|
||||
Email string `json:"email"`
|
||||
NickName string `json:"nick_name"`
|
||||
Avatar string `json:"avatar"`
|
||||
Description string `json:"description"`
|
||||
CreatedAt time.Time `gorm:"<-:create;autoCreateTime" json:"created_at,omitempty"`
|
||||
UpdatedAt time.Time `gorm:"<-:create;<-:update;autoUpdateTime" json:"updated_at,omitempty"`
|
||||
}
|
||||
|
||||
func (p *UserDBModel) TableName() string {
|
||||
return "o_user"
|
||||
}
|
||||
@@ -2,14 +2,22 @@ package service
|
||||
|
||||
import (
|
||||
json2 "encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
model2 "github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/model/notify"
|
||||
"github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/ambelovsky/gosf"
|
||||
socketio "github.com/googollee/go-socket.io"
|
||||
"github.com/gorilla/websocket"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var NotifyMsg chan notify.Message
|
||||
var ClientCount int = 0
|
||||
|
||||
type NotifyServer interface {
|
||||
GetLog(id string) model.AppNotify
|
||||
AddLog(log model.AppNotify)
|
||||
@@ -18,13 +26,336 @@ type NotifyServer interface {
|
||||
DelLog(id string)
|
||||
GetList(c int) (list []model.AppNotify)
|
||||
MarkRead(id string, state int)
|
||||
SendText(m model.AppNotify)
|
||||
// SendText(m model.AppNotify)
|
||||
SendUninstallAppBySocket(app notify.Application)
|
||||
SendNetInfoBySocket(netList []model2.IOCountersStat)
|
||||
SendCPUInfoBySocket(cpu map[string]interface{})
|
||||
SendMemInfoBySocket(mem map[string]interface{})
|
||||
SendUSBInfoBySocket(list []model2.DriveUSB)
|
||||
SendDiskInfoBySocket(disk model2.Summary)
|
||||
SendPersonStatusBySocket(status notify.Person)
|
||||
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)
|
||||
}
|
||||
|
||||
type notifyServer struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
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{})
|
||||
body["sys_disk"] = disk
|
||||
|
||||
body["sys_usb"] = list
|
||||
|
||||
body["sys_mem"] = mem
|
||||
|
||||
body["sys_cpu"] = cpu
|
||||
|
||||
body["sys_net"] = netList
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "sys_hardware_status"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "sys_hardware_status"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
|
||||
}
|
||||
|
||||
// Send periodic broadcast messages
|
||||
func (i *notifyServer) SendFileOperateNotify(nowSend bool) {
|
||||
|
||||
if nowSend {
|
||||
|
||||
len := 0
|
||||
FileQueue.Range(func(k, v interface{}) bool {
|
||||
len++
|
||||
return true
|
||||
})
|
||||
|
||||
model := notify.NotifyModel{}
|
||||
listMsg := make(map[string]interface{})
|
||||
if len == 0 {
|
||||
model.Data = []string{}
|
||||
|
||||
listMsg["file_operate"] = model
|
||||
msg := gosf.Message{}
|
||||
msg.Success = true
|
||||
msg.Body = listMsg
|
||||
msg.Text = "file_operate"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "file_operate"
|
||||
notify.Msg = msg
|
||||
NotifyMsg <- notify
|
||||
return
|
||||
}
|
||||
|
||||
model.State = "NORMAL"
|
||||
list := []notify.File{}
|
||||
OpStrArrbak := OpStrArr
|
||||
|
||||
for _, v := range OpStrArrbak {
|
||||
tempItem, ok := FileQueue.Load(v)
|
||||
temp := tempItem.(model2.FileOperate)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
task := notify.File{}
|
||||
task.Id = v
|
||||
task.ProcessedSize = temp.ProcessedSize
|
||||
task.TotalSize = temp.TotalSize
|
||||
task.To = temp.To
|
||||
task.Type = temp.Type
|
||||
if task.ProcessedSize == 0 {
|
||||
task.Status = "STARTING"
|
||||
} else {
|
||||
task.Status = "PROCESSING"
|
||||
}
|
||||
|
||||
if temp.Finished || temp.ProcessedSize >= temp.TotalSize {
|
||||
|
||||
task.Finished = true
|
||||
task.Status = "FINISHED"
|
||||
FileQueue.Delete(v)
|
||||
OpStrArr = OpStrArr[1:]
|
||||
go ExecOpFile()
|
||||
list = append(list, task)
|
||||
continue
|
||||
}
|
||||
for _, v := range temp.Item {
|
||||
if v.Size != v.ProcessedSize {
|
||||
task.ProcessingPath = v.From
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
list = append(list, task)
|
||||
}
|
||||
model.Data = list
|
||||
|
||||
listMsg["file_operate"] = model
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Success = true
|
||||
msg.Body = listMsg
|
||||
msg.Text = "file_operate"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "file_operate"
|
||||
notify.Msg = msg
|
||||
NotifyMsg <- notify
|
||||
} else {
|
||||
for {
|
||||
|
||||
len := 0
|
||||
FileQueue.Range(func(k, v interface{}) bool {
|
||||
len++
|
||||
return true
|
||||
})
|
||||
if len == 0 {
|
||||
return
|
||||
}
|
||||
listMsg := make(map[string]interface{})
|
||||
model := notify.NotifyModel{}
|
||||
model.State = "NORMAL"
|
||||
list := []notify.File{}
|
||||
OpStrArrbak := OpStrArr
|
||||
|
||||
for _, v := range OpStrArrbak {
|
||||
tempItem, ok := FileQueue.Load(v)
|
||||
temp := tempItem.(model2.FileOperate)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
task := notify.File{}
|
||||
task.Id = v
|
||||
task.ProcessedSize = temp.ProcessedSize
|
||||
task.TotalSize = temp.TotalSize
|
||||
task.To = temp.To
|
||||
task.Type = temp.Type
|
||||
if task.ProcessedSize == 0 {
|
||||
task.Status = "STARTING"
|
||||
} else {
|
||||
task.Status = "PROCESSING"
|
||||
}
|
||||
if temp.Finished || temp.ProcessedSize >= temp.TotalSize {
|
||||
|
||||
task.Finished = true
|
||||
task.Status = "FINISHED"
|
||||
FileQueue.Delete(v)
|
||||
OpStrArr = OpStrArr[1:]
|
||||
go ExecOpFile()
|
||||
list = append(list, task)
|
||||
continue
|
||||
}
|
||||
for _, v := range temp.Item {
|
||||
if v.Size != v.ProcessedSize {
|
||||
task.ProcessingPath = v.From
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
list = append(list, task)
|
||||
}
|
||||
model.Data = list
|
||||
|
||||
listMsg["file_operate"] = model
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Success = true
|
||||
msg.Body = listMsg
|
||||
msg.Text = "file_operate"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "file_operate"
|
||||
notify.Msg = msg
|
||||
NotifyMsg <- notify
|
||||
time.Sleep(time.Second * 3)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (i *notifyServer) SendPersonStatusBySocket(status notify.Person) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = status
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "person_status"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "person_status"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
|
||||
func (i *notifyServer) SendDiskInfoBySocket(disk model2.Summary) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = disk
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "sys_disk"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "sys_disk"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
|
||||
func (i *notifyServer) SendUSBInfoBySocket(list []model2.DriveUSB) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = list
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "sys_usb"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "sys_usb"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
|
||||
func (i *notifyServer) SendMemInfoBySocket(mem map[string]interface{}) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = mem
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "sys_mem"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "sys_mem"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
|
||||
func (i *notifyServer) SendInstallAppBySocket(app notify.Application) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = app
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "app_install"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "app_install"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
|
||||
func (i *notifyServer) SendCPUInfoBySocket(cpu map[string]interface{}) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = cpu
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "sys_cpu"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "sys_cpu"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
func (i *notifyServer) SendNetInfoBySocket(netList []model2.IOCountersStat) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = netList
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "sys_net"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "sys_net"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
|
||||
func (i *notifyServer) SendUninstallAppBySocket(app notify.Application) {
|
||||
body := make(map[string]interface{})
|
||||
body["data"] = app
|
||||
|
||||
msg := gosf.Message{}
|
||||
msg.Body = body
|
||||
msg.Success = true
|
||||
msg.Text = "app_uninstall"
|
||||
|
||||
notify := notify.Message{}
|
||||
notify.Path = "app_uninstall"
|
||||
notify.Msg = msg
|
||||
|
||||
NotifyMsg <- notify
|
||||
}
|
||||
|
||||
func (i *notifyServer) SSR() {
|
||||
server := socketio.NewServer(nil)
|
||||
fmt.Println(server)
|
||||
}
|
||||
|
||||
func (i notifyServer) GetList(c int) (list []model.AppNotify) {
|
||||
i.db.Where("class = ?", c).Where(i.db.Where("state = ?", types.NOTIFY_DYNAMICE).Or("state = ?", types.NOTIFY_UNREAD)).Find(&list)
|
||||
return
|
||||
@@ -103,25 +434,25 @@ func SendMeg() {
|
||||
// }
|
||||
}
|
||||
|
||||
func (i notifyServer) SendText(m model.AppNotify) {
|
||||
list := []model.AppNotify{}
|
||||
list = append(list, m)
|
||||
json, _ := json2.Marshal(list)
|
||||
var temp []*websocket.Conn
|
||||
for _, v := range WebSocketConns {
|
||||
// func (i notifyServer) SendText(m model.AppNotify) {
|
||||
// list := []model.AppNotify{}
|
||||
// list = append(list, m)
|
||||
// json, _ := json2.Marshal(list)
|
||||
// var temp []*websocket.Conn
|
||||
// for _, v := range WebSocketConns {
|
||||
|
||||
err := v.WriteMessage(1, json)
|
||||
if err == nil {
|
||||
temp = append(temp, v)
|
||||
}
|
||||
}
|
||||
WebSocketConns = temp
|
||||
// err := v.WriteMessage(1, json)
|
||||
// if err == nil {
|
||||
// temp = append(temp, v)
|
||||
// }
|
||||
// }
|
||||
// WebSocketConns = temp
|
||||
|
||||
if len(WebSocketConns) == 0 {
|
||||
SocketRun = false
|
||||
}
|
||||
// if len(WebSocketConns) == 0 {
|
||||
// SocketRun = false
|
||||
// }
|
||||
|
||||
}
|
||||
// }
|
||||
|
||||
func NewNotifyService(db *gorm.DB) NotifyServer {
|
||||
return ¬ifyServer{db: db}
|
||||
|
||||
@@ -198,11 +198,11 @@ func ProcessingContent(stream quic.Stream) {
|
||||
if m.Data.(string) == "" || m.Data.(string) == "/" {
|
||||
for _, v := range config.FileSettingInfo.ShareDir {
|
||||
//tempList := MyService.ZiMa().GetDirPath(v)
|
||||
temp := MyService.ZiMa().GetDirPathOne(v)
|
||||
temp := MyService.System().GetDirPathOne(v)
|
||||
list = append(list, temp)
|
||||
}
|
||||
} else {
|
||||
list = MyService.ZiMa().GetDirPath(m.Data.(string))
|
||||
list = MyService.System().GetDirPath(m.Data.(string))
|
||||
}
|
||||
} else {
|
||||
list = []model.Path{}
|
||||
|
||||
102
service/redis.go
102
service/redis.go
@@ -1,102 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/gomodule/redigo/redis"
|
||||
)
|
||||
|
||||
type RedisService interface {
|
||||
Set(key string, data interface{}, time int) error
|
||||
Exists(key string) bool
|
||||
Get(key string) ([]byte, error)
|
||||
PutExpireTime(key string, time int)
|
||||
Delete(key string) (bool, error)
|
||||
LikeDeletes(key string) error
|
||||
}
|
||||
|
||||
type redisService struct {
|
||||
rp *redis.Pool
|
||||
}
|
||||
|
||||
// Set a key/value
|
||||
func (r *redisService) Set(key string, data interface{}, time int) error {
|
||||
conn := r.rp.Get()
|
||||
defer conn.Close()
|
||||
|
||||
value, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = conn.Do("SET", key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = conn.Do("EXPIRE", key, time)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
//设置过期时间
|
||||
func (r *redisService) PutExpireTime(key string, time int) {
|
||||
conn := r.rp.Get()
|
||||
defer conn.Close()
|
||||
conn.Do("EXPIRE", key, time)
|
||||
}
|
||||
|
||||
// Exists check a key
|
||||
func (r *redisService) Exists(key string) bool {
|
||||
conn := r.rp.Get()
|
||||
defer conn.Close()
|
||||
exists, err := redis.Bool(conn.Do("EXISTS", key))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return exists
|
||||
}
|
||||
|
||||
// Get get a key
|
||||
func (r *redisService) Get(key string) ([]byte, error) {
|
||||
conn := r.rp.Get()
|
||||
defer conn.Close()
|
||||
|
||||
reply, err := redis.Bytes(conn.Do("GET", key))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return reply, nil
|
||||
}
|
||||
|
||||
func NewRedisService(rp *redis.Pool) RedisService {
|
||||
return &redisService{rp: rp}
|
||||
}
|
||||
|
||||
// Delete delete a kye
|
||||
func (r *redisService) Delete(key string) (bool, error) {
|
||||
conn := r.rp.Get()
|
||||
defer conn.Close()
|
||||
|
||||
return redis.Bool(conn.Do("DEL", key))
|
||||
}
|
||||
|
||||
// LikeDeletes batch delete
|
||||
func (r *redisService) LikeDeletes(key string) error {
|
||||
conn := r.rp.Get()
|
||||
defer conn.Close()
|
||||
|
||||
keys, err := redis.Strings(conn.Do("KEYS", "*"+key+"*"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, key := range keys {
|
||||
_, err = r.Delete(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,7 +1,16 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2021-09-30 18:18:14
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-02 18:00:57
|
||||
* @FilePath: /CasaOS/service/rely.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package service
|
||||
|
||||
import (
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
model2 "github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -13,8 +22,7 @@ type RelyService interface {
|
||||
}
|
||||
|
||||
type relyService struct {
|
||||
db *gorm.DB
|
||||
log loger2.OLog
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (r *relyService) Create(rely model2.RelyDBModel) {
|
||||
@@ -35,6 +43,6 @@ func (r *relyService) Delete(id string) {
|
||||
r.db.Where("custom_id = ?", id).Delete(&c)
|
||||
}
|
||||
|
||||
func NewRelyService(db *gorm.DB, log loger2.OLog) RelyService {
|
||||
return &relyService{db: db, log: log}
|
||||
func NewRelyService(db *gorm.DB) RelyService {
|
||||
return &relyService{db: db}
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
)
|
||||
|
||||
type SearchService interface {
|
||||
SearchList(key string) ([]model.SearchFileInfo, error)
|
||||
}
|
||||
|
||||
type searchService struct {
|
||||
}
|
||||
|
||||
func (s *searchService) SearchList(key string) ([]model.SearchFileInfo, error) {
|
||||
pathName := "/Users/liangjianli/go/CasaOSNew/searchTest"
|
||||
resArr := []model.SearchFileInfo{}
|
||||
files, _ := ioutil.ReadDir(pathName)
|
||||
for _, file := range files {
|
||||
if file.IsDir() {
|
||||
tempArr, err := s.SearchList(pathName + "/" + file.Name())
|
||||
if err != nil {
|
||||
resArr = append(resArr, tempArr...)
|
||||
}
|
||||
} else {
|
||||
if strings.Contains(file.Name(), key) {
|
||||
resArr = append(resArr, model.SearchFileInfo{Path: pathName, Name: file.Name(), Type: GetSearchType(path.Ext(file.Name()))})
|
||||
}
|
||||
fmt.Println(pathName + "/" + file.Name())
|
||||
}
|
||||
}
|
||||
return resArr, nil
|
||||
}
|
||||
|
||||
func GetSearchType(ext string) int {
|
||||
var reType int = types.UNKNOWN
|
||||
switch ext {
|
||||
case ".png":
|
||||
reType = types.PICTURE
|
||||
case ".mp4":
|
||||
reType = types.MEDIA
|
||||
case ".mp3":
|
||||
reType = types.MUSIC
|
||||
default:
|
||||
reType = types.UNKNOWN
|
||||
}
|
||||
return reType
|
||||
}
|
||||
|
||||
func NewSearchService() SearchService {
|
||||
return &searchService{}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/patrickmn/go-cache"
|
||||
"gorm.io/gorm"
|
||||
@@ -17,71 +16,54 @@ var SocketRun bool
|
||||
|
||||
type Repository interface {
|
||||
App() AppService
|
||||
DDNS() DDNSService
|
||||
User() UserService
|
||||
Docker() DockerService
|
||||
//Redis() RedisService
|
||||
ZiMa() ZiMaService
|
||||
Casa() CasaService
|
||||
Disk() DiskService
|
||||
Notify() NotifyServer
|
||||
ShareDirectory() ShareDirService
|
||||
Task() TaskService
|
||||
Rely() RelyService
|
||||
System() SystemService
|
||||
Shortcuts() ShortcutsService
|
||||
Search() SearchService
|
||||
Person() PersonService
|
||||
Friend() FriendService
|
||||
Download() DownloadService
|
||||
DownRecord() DownRecordService
|
||||
}
|
||||
|
||||
func NewService(db *gorm.DB, log loger2.OLog) Repository {
|
||||
func NewService(db *gorm.DB) Repository {
|
||||
|
||||
return &store{
|
||||
app: NewAppService(db, log),
|
||||
ddns: NewDDNSService(db, log),
|
||||
user: NewUserService(),
|
||||
docker: NewDockerService(log),
|
||||
//redis: NewRedisService(rp),
|
||||
zima: NewZiMaService(),
|
||||
casa: NewCasaService(),
|
||||
disk: NewDiskService(log, db),
|
||||
notify: NewNotifyService(db),
|
||||
shareDirectory: NewShareDirService(db, log),
|
||||
task: NewTaskService(db, log),
|
||||
rely: NewRelyService(db, log),
|
||||
system: NewSystemService(log),
|
||||
shortcuts: NewShortcutsService(db),
|
||||
search: NewSearchService(),
|
||||
person: NewPersonService(db),
|
||||
friend: NewFriendService(db),
|
||||
download: NewDownloadService(db),
|
||||
downrecord: NewDownRecordService(db),
|
||||
app: NewAppService(db),
|
||||
user: NewUserService(db),
|
||||
docker: NewDockerService(),
|
||||
casa: NewCasaService(),
|
||||
disk: NewDiskService(db),
|
||||
notify: NewNotifyService(db),
|
||||
rely: NewRelyService(db),
|
||||
system: NewSystemService(),
|
||||
shortcuts: NewShortcutsService(db),
|
||||
person: NewPersonService(db),
|
||||
friend: NewFriendService(db),
|
||||
download: NewDownloadService(db),
|
||||
downrecord: NewDownRecordService(db),
|
||||
}
|
||||
}
|
||||
|
||||
type store struct {
|
||||
db *gorm.DB
|
||||
app AppService
|
||||
ddns DDNSService
|
||||
user UserService
|
||||
docker DockerService
|
||||
zima ZiMaService
|
||||
casa CasaService
|
||||
disk DiskService
|
||||
notify NotifyServer
|
||||
shareDirectory ShareDirService
|
||||
task TaskService
|
||||
rely RelyService
|
||||
system SystemService
|
||||
shortcuts ShortcutsService
|
||||
search SearchService
|
||||
person PersonService
|
||||
friend FriendService
|
||||
download DownloadService
|
||||
downrecord DownRecordService
|
||||
db *gorm.DB
|
||||
app AppService
|
||||
user UserService
|
||||
docker DockerService
|
||||
casa CasaService
|
||||
disk DiskService
|
||||
notify NotifyServer
|
||||
rely RelyService
|
||||
system SystemService
|
||||
shortcuts ShortcutsService
|
||||
person PersonService
|
||||
friend FriendService
|
||||
download DownloadService
|
||||
downrecord DownRecordService
|
||||
}
|
||||
|
||||
func (c *store) DownRecord() DownRecordService {
|
||||
@@ -115,10 +97,6 @@ func (c *store) App() AppService {
|
||||
return c.app
|
||||
}
|
||||
|
||||
func (c *store) DDNS() DDNSService {
|
||||
return c.ddns
|
||||
}
|
||||
|
||||
func (c *store) User() UserService {
|
||||
return c.user
|
||||
}
|
||||
@@ -127,9 +105,6 @@ func (c *store) Docker() DockerService {
|
||||
return c.docker
|
||||
}
|
||||
|
||||
func (c *store) ZiMa() ZiMaService {
|
||||
return c.zima
|
||||
}
|
||||
func (c *store) Casa() CasaService {
|
||||
return c.casa
|
||||
}
|
||||
@@ -137,12 +112,3 @@ func (c *store) Casa() CasaService {
|
||||
func (c *store) Disk() DiskService {
|
||||
return c.disk
|
||||
}
|
||||
func (c *store) ShareDirectory() ShareDirService {
|
||||
return c.shareDirectory
|
||||
}
|
||||
func (c *store) Task() TaskService {
|
||||
return c.task
|
||||
}
|
||||
func (c *store) Search() SearchService {
|
||||
return c.search
|
||||
}
|
||||
|
||||
@@ -1,323 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"gorm.io/gorm"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type ShareDirService interface {
|
||||
UpConfig()
|
||||
List(desc bool) []model.ShareDirDBModel
|
||||
Delete(id string)
|
||||
Add(m *model.ShareDirDBModel)
|
||||
Update(m *model.ShareDirDBModel)
|
||||
Info(id string) model.ShareDirDBModel
|
||||
}
|
||||
|
||||
type shareDirService struct {
|
||||
db *gorm.DB
|
||||
log loger2.OLog
|
||||
}
|
||||
|
||||
func (s *shareDirService) List(desc bool) []model.ShareDirDBModel {
|
||||
var list []model.ShareDirDBModel
|
||||
var orderBy string
|
||||
if desc {
|
||||
orderBy = "id"
|
||||
} else {
|
||||
orderBy = "id DESC"
|
||||
}
|
||||
s.db.Order(orderBy).Find(&list)
|
||||
return list
|
||||
}
|
||||
|
||||
func (s *shareDirService) Delete(id string) {
|
||||
var m model.ShareDirDBModel
|
||||
s.db.Where("id = ?", id).Delete(&m)
|
||||
}
|
||||
|
||||
func (s *shareDirService) Add(m *model.ShareDirDBModel) {
|
||||
s.db.Save(m)
|
||||
}
|
||||
func (s *shareDirService) Update(m *model.ShareDirDBModel) {
|
||||
s.db.Save(m)
|
||||
}
|
||||
func (s *shareDirService) UpConfig() {
|
||||
var list []model.ShareDirDBModel
|
||||
|
||||
s.db.Find(&list)
|
||||
|
||||
str := `#
|
||||
# Sample configuration file for the Samba suite for Debian GNU/Linux.
|
||||
#
|
||||
#
|
||||
# This is the main Samba configuration file. You should read the
|
||||
# smb.conf(5) manual page in order to understand the options listed
|
||||
# here. Samba has a huge number of configurable options most of which
|
||||
# are not shown in this example
|
||||
#
|
||||
# Some options that are often worth tuning have been included as
|
||||
# commented-out examples in this file.
|
||||
# - When such options are commented with ";", the proposed setting
|
||||
# differs from the default Samba behaviour
|
||||
# - When commented with "#", the proposed setting is the default
|
||||
# behaviour of Samba but the option is considered important
|
||||
# enough to be mentioned here
|
||||
#
|
||||
# NOTE: Whenever you modify this file you should run the command
|
||||
# "testparm" to check that you have not made any basic syntactic
|
||||
# errors.
|
||||
|
||||
#======================= Global Settings =======================
|
||||
|
||||
[global]
|
||||
|
||||
## Browsing/Identification ###
|
||||
|
||||
# Change this to the workgroup/NT-domain name your Samba server will part of
|
||||
workgroup = WORKGROUP
|
||||
|
||||
#### Networking ####
|
||||
|
||||
# The specific set of interfaces / networks to bind to
|
||||
# This can be either the interface name or an IP address/netmask;
|
||||
# interface names are normally preferred
|
||||
; interfaces = 127.0.0.0/8 eth0
|
||||
|
||||
# Only bind to the named interfaces and/or networks; you must use the
|
||||
# 'interfaces' option above to use this.
|
||||
# It is recommended that you enable this feature if your Samba machine is
|
||||
# not protected by a firewall or is a firewall itself. However, this
|
||||
# option cannot handle dynamic or non-broadcast interfaces correctly.
|
||||
; bind interfaces only = yes
|
||||
|
||||
|
||||
|
||||
#### Debugging/Accounting ####
|
||||
|
||||
# This tells Samba to use a separate log file for each machine
|
||||
# that connects
|
||||
log file = /var/log/samba/log.%m
|
||||
|
||||
# Cap the size of the individual log files (in KiB).
|
||||
max log size = 1000
|
||||
|
||||
# We want Samba to only log to /var/log/samba/log.{smbd,nmbd}.
|
||||
# Append syslog@1 if you want important messages to be sent to syslog too.
|
||||
logging = file
|
||||
|
||||
# Do something sensible when Samba crashes: mail the admin a backtrace
|
||||
panic action = /usr/share/samba/panic-action %d
|
||||
|
||||
|
||||
####### Authentication #######
|
||||
|
||||
# Server role. Defines in which mode Samba will operate. Possible
|
||||
# values are "standalone server", "member server", "classic primary
|
||||
# domain controller", "classic backup domain controller", "active
|
||||
# directory domain controller".
|
||||
#
|
||||
# Most people will want "standalone server" or "member server".
|
||||
# Running as "active directory domain controller" will require first
|
||||
# running "samba-tool domain provision" to wipe databases and create a
|
||||
# new domain.
|
||||
server role = standalone server
|
||||
|
||||
obey pam restrictions = yes
|
||||
|
||||
# This boolean parameter controls whether Samba attempts to sync the Unix
|
||||
# password with the SMB password when the encrypted SMB password in the
|
||||
# passdb is changed.
|
||||
unix password sync = yes
|
||||
|
||||
# For Unix password sync to work on a Debian GNU/Linux system, the following
|
||||
# parameters must be set (thanks to Ian Kahan <<kahan@informatik.tu-muenchen.de> for
|
||||
# sending the correct chat script for the passwd program in Debian Sarge).
|
||||
passwd program = /usr/bin/passwd %u
|
||||
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
|
||||
|
||||
# This boolean controls whether PAM will be used for password changes
|
||||
# when requested by an SMB client instead of the program listed in
|
||||
# 'passwd program'. The default is 'no'.
|
||||
pam password change = yes
|
||||
|
||||
# This option controls how unsuccessful authentication attempts are mapped
|
||||
# to anonymous connections
|
||||
map to guest = bad user
|
||||
|
||||
########## Domains ###########
|
||||
|
||||
#
|
||||
# The following settings only takes effect if 'server role = primary
|
||||
# classic domain controller', 'server role = backup domain controller'
|
||||
# or 'domain logons' is set
|
||||
#
|
||||
|
||||
# It specifies the location of the user's
|
||||
# profile directory from the client point of view) The following
|
||||
# required a [profiles] share to be setup on the samba server (see
|
||||
# below)
|
||||
; logon path = \\%N\profiles\%U
|
||||
# Another common choice is storing the profile in the user's home directory
|
||||
# (this is Samba's default)
|
||||
# logon path = \\%N\%U\profile
|
||||
|
||||
# The following setting only takes effect if 'domain logons' is set
|
||||
# It specifies the location of a user's home directory (from the client
|
||||
# point of view)
|
||||
; logon drive = H:
|
||||
# logon home = \\%N\%U
|
||||
|
||||
# The following setting only takes effect if 'domain logons' is set
|
||||
# It specifies the script to run during logon. The script must be stored
|
||||
# in the [netlogon] share
|
||||
# NOTE: Must be store in 'DOS' file format convention
|
||||
; logon script = logon.cmd
|
||||
|
||||
# This allows Unix users to be created on the domain controller via the SAMR
|
||||
# RPC pipe. The example command creates a user account with a disabled Unix
|
||||
# password; please adapt to your needs
|
||||
; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u
|
||||
|
||||
# This allows machine accounts to be created on the domain controller via the
|
||||
# SAMR RPC pipe.
|
||||
# The following assumes a "machines" group exists on the system
|
||||
; add machine script = /usr/sbin/useradd -g machines -c "%u machine account" -d /var/lib/samba -s /bin/false %u
|
||||
|
||||
# This allows Unix groups to be created on the domain controller via the SAMR
|
||||
# RPC pipe.
|
||||
; add group script = /usr/sbin/addgroup --force-badname %g
|
||||
|
||||
############ Misc ############
|
||||
|
||||
# Using the following line enables you to customise your configuration
|
||||
# on a per machine basis. The %m gets replaced with the netbios name
|
||||
# of the machine that is connecting
|
||||
; include = /home/samba/etc/smb.conf.%m
|
||||
|
||||
# Some defaults for winbind (make sure you're not using the ranges
|
||||
# for something else.)
|
||||
; idmap config * : backend = tdb
|
||||
; idmap config * : range = 3000-7999
|
||||
; idmap config YOURDOMAINHERE : backend = tdb
|
||||
; idmap config YOURDOMAINHERE : range = 100000-999999
|
||||
; template shell = /bin/bash
|
||||
|
||||
# Setup usershare options to enable non-root users to share folders
|
||||
# with the net usershare command.
|
||||
|
||||
# Maximum number of usershare. 0 means that usershare is disabled.
|
||||
# usershare max shares = 100
|
||||
|
||||
# Allow users who've been granted usershare privileges to create
|
||||
# public shares, not just authenticated ones
|
||||
usershare allow guests = yes
|
||||
|
||||
#======================= Share Definitions =======================
|
||||
|
||||
[homes]
|
||||
comment = Home Directories
|
||||
browseable = no
|
||||
|
||||
# By default, the home directories are exported read-only. Change the
|
||||
# next parameter to 'no' if you want to be able to write to them.
|
||||
read only = yes
|
||||
|
||||
# File creation mask is set to 0700 for security reasons. If you want to
|
||||
# create files with group=rw permissions, set next parameter to 0775.
|
||||
create mask = 0700
|
||||
|
||||
# Directory creation mask is set to 0700 for security reasons. If you want to
|
||||
# create dirs. with group=rw permissions, set next parameter to 0775.
|
||||
directory mask = 0700
|
||||
|
||||
# By default, \\server\username shares can be connected to by anyone
|
||||
# with access to the samba server.
|
||||
# The following parameter makes sure that only "username" can connect
|
||||
# to \\server\username
|
||||
# This might need tweaking when using external authentication schemes
|
||||
valid users = %S
|
||||
|
||||
# Un-comment the following and create the netlogon directory for Domain Logons
|
||||
# (you need to configure Samba to act as a domain controller too.)
|
||||
;[netlogon]
|
||||
; comment = Network Logon Service
|
||||
; path = /home/samba/netlogon
|
||||
; guest ok = yes
|
||||
; read only = yes
|
||||
|
||||
# Un-comment the following and create the profiles directory to store
|
||||
# users profiles (see the "logon path" option above)
|
||||
# (you need to configure Samba to act as a domain controller too.)
|
||||
# The path below should be writable by all users so that their
|
||||
# profile directory may be created the first time they log on
|
||||
;[profiles]
|
||||
; comment = Users profiles
|
||||
; path = /home/samba/profiles
|
||||
; guest ok = no
|
||||
; browseable = no
|
||||
; create mask = 0600
|
||||
; directory mask = 0700
|
||||
|
||||
[printers]
|
||||
comment = All Printers
|
||||
browseable = no
|
||||
path = /var/spool/samba
|
||||
printable = yes
|
||||
guest ok = no
|
||||
read only = yes
|
||||
create mask = 0700
|
||||
|
||||
# Windows clients look for this share name as a source of downloadable
|
||||
# printer drivers
|
||||
[print$]
|
||||
comment = Printer Drivers
|
||||
path = /var/lib/samba/printers
|
||||
browseable = yes
|
||||
read only = yes
|
||||
guest ok = no
|
||||
# Uncomment to allow remote administration of Windows print drivers.
|
||||
# You may need to replace 'lpadmin' with the name of the group your
|
||||
# admin users are members of.
|
||||
# Please note that you also need to set appropriate Unix permissions
|
||||
# to the drivers directory for these users to have write rights in it
|
||||
; write list = root, @lpadmin`
|
||||
|
||||
for _, i := range list {
|
||||
str += "\n[" + i.Name + "]"
|
||||
str += "\n comment = " + i.Comment
|
||||
str += "\n path = " + i.Path
|
||||
str += "\n browseable = " + strconv.FormatBool(i.Browseable)
|
||||
str += "\n read only = " + strconv.FormatBool(i.ReadOnly)
|
||||
str += "\n writeable = " + strconv.FormatBool(i.Writeable)
|
||||
if len(i.ValidUsers) == 0 {
|
||||
str += "\n guest ok = yes"
|
||||
} else {
|
||||
str += "\n valid users = " + i.ValidUsers
|
||||
}
|
||||
}
|
||||
|
||||
// /etc/samba/smb.conf
|
||||
f, err := os.OpenFile("/etc/samba/smb.conf", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
|
||||
if err != nil {
|
||||
s.log.Error("file create failed. err: " + err.Error())
|
||||
} else {
|
||||
defer f.Close()
|
||||
f.WriteString(str)
|
||||
command.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;ReloadSamba")
|
||||
}
|
||||
}
|
||||
func (s *shareDirService) Info(id string) model.ShareDirDBModel {
|
||||
var m model.ShareDirDBModel
|
||||
s.db.Where("id = ?", id).First(&m)
|
||||
return m
|
||||
}
|
||||
|
||||
func NewShareDirService(db *gorm.DB, log loger2.OLog) ShareDirService {
|
||||
return &shareDirService{db: db, log: log}
|
||||
}
|
||||
@@ -1,14 +1,26 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
net2 "net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
command2 "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/shirou/gopsutil/v3/host"
|
||||
"github.com/shirou/gopsutil/v3/mem"
|
||||
"github.com/shirou/gopsutil/v3/net"
|
||||
)
|
||||
|
||||
type SystemService interface {
|
||||
@@ -21,38 +33,204 @@ type SystemService interface {
|
||||
GetTimeZone() string
|
||||
UpdateUSBAutoMount(state string)
|
||||
ExecUSBAutoMountShell(state string)
|
||||
UpAppOrderFile(str string)
|
||||
GetAppOrderFile() []byte
|
||||
UpAppOrderFile(str, id string)
|
||||
GetAppOrderFile(id string) []byte
|
||||
GetNet(physics bool) []string
|
||||
GetNetInfo() []net.IOCountersStat
|
||||
GetCpuCoreNum() int
|
||||
GetCpuPercent() float64
|
||||
GetMemInfo() map[string]interface{}
|
||||
GetCpuInfo() []cpu.InfoStat
|
||||
GetDirPath(path string) []model.Path
|
||||
GetDirPathOne(path string) (m model.Path)
|
||||
GetNetState(name string) string
|
||||
GetDiskInfo() *disk.UsageStat
|
||||
GetSysInfo() host.InfoStat
|
||||
GetDeviceTree() string
|
||||
CreateFile(path string) (int, error)
|
||||
RenameFile(oldF, newF string) (int, error)
|
||||
MkdirAll(path string) (int, error)
|
||||
}
|
||||
type systemService struct {
|
||||
log loger.OLog
|
||||
}
|
||||
|
||||
func (c *systemService) MkdirAll(path string) (int, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return common_err.DIR_ALREADY_EXISTS, nil
|
||||
} else {
|
||||
if os.IsNotExist(err) {
|
||||
os.MkdirAll(path, os.ModePerm)
|
||||
return common_err.SUCCESS, nil
|
||||
} else if strings.Contains(err.Error(), ": not a directory") {
|
||||
return common_err.FILE_OR_DIR_EXISTS, err
|
||||
}
|
||||
}
|
||||
return common_err.ERROR, err
|
||||
}
|
||||
func (c *systemService) RenameFile(oldF, newF string) (int, error) {
|
||||
|
||||
_, err := os.Stat(newF)
|
||||
if err == nil {
|
||||
return common_err.DIR_ALREADY_EXISTS, nil
|
||||
} else {
|
||||
if os.IsNotExist(err) {
|
||||
err := os.Rename(oldF, newF)
|
||||
if err != nil {
|
||||
return common_err.ERROR, err
|
||||
}
|
||||
return common_err.SUCCESS, nil
|
||||
}
|
||||
}
|
||||
return common_err.ERROR, err
|
||||
}
|
||||
func (c *systemService) CreateFile(path string) (int, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return common_err.FILE_OR_DIR_EXISTS, nil
|
||||
} else {
|
||||
if os.IsNotExist(err) {
|
||||
file.CreateFile(path)
|
||||
return common_err.SUCCESS, nil
|
||||
}
|
||||
}
|
||||
return common_err.ERROR, err
|
||||
}
|
||||
func (c *systemService) GetDeviceTree() string {
|
||||
return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetDeviceTree")
|
||||
}
|
||||
func (c *systemService) GetSysInfo() host.InfoStat {
|
||||
info, _ := host.Info()
|
||||
return *info
|
||||
}
|
||||
|
||||
func (c *systemService) GetDiskInfo() *disk.UsageStat {
|
||||
path := "/"
|
||||
if runtime.GOOS == "windows" {
|
||||
path = "C:"
|
||||
}
|
||||
diskInfo, _ := disk.Usage(path)
|
||||
diskInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.UsedPercent), 64)
|
||||
diskInfo.InodesUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.InodesUsedPercent), 64)
|
||||
return diskInfo
|
||||
}
|
||||
|
||||
func (c *systemService) GetNetState(name string) string {
|
||||
return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;CatNetCardState " + name)
|
||||
}
|
||||
|
||||
func (c *systemService) GetDirPathOne(path string) (m model.Path) {
|
||||
|
||||
f, err := os.Stat(path)
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.IsDir = f.IsDir()
|
||||
m.Name = f.Name()
|
||||
m.Path = path
|
||||
m.Size = f.Size()
|
||||
m.Date = f.ModTime()
|
||||
return
|
||||
}
|
||||
|
||||
func (c *systemService) GetDirPath(path string) []model.Path {
|
||||
if path == "/DATA" {
|
||||
sysType := runtime.GOOS
|
||||
if sysType == "windows" {
|
||||
path = "C:\\CasaOS\\DATA"
|
||||
}
|
||||
if sysType == "darwin" {
|
||||
path = "./CasaOS/DATA"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ls, _ := ioutil.ReadDir(path)
|
||||
dirs := []model.Path{}
|
||||
if len(path) > 0 {
|
||||
for _, l := range ls {
|
||||
filePath := filepath.Join(path, l.Name())
|
||||
link, err := filepath.EvalSymlinks(filePath)
|
||||
if err != nil {
|
||||
link = filePath
|
||||
}
|
||||
temp := model.Path{Name: l.Name(), Path: filePath, IsDir: l.IsDir(), Date: l.ModTime(), Size: l.Size()}
|
||||
if filePath != link {
|
||||
file, _ := os.Stat(link)
|
||||
temp.IsDir = file.IsDir()
|
||||
}
|
||||
dirs = append(dirs, temp)
|
||||
}
|
||||
} else {
|
||||
dirs = append(dirs, model.Path{Name: "DATA", Path: "/DATA/", IsDir: true, Date: time.Now()})
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
func (c *systemService) GetCpuInfo() []cpu.InfoStat {
|
||||
info, _ := cpu.Info()
|
||||
return info
|
||||
}
|
||||
|
||||
func (c *systemService) GetMemInfo() map[string]interface{} {
|
||||
memInfo, _ := mem.VirtualMemory()
|
||||
memInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", memInfo.UsedPercent), 64)
|
||||
memData := make(map[string]interface{})
|
||||
memData["total"] = memInfo.Total
|
||||
memData["available"] = memInfo.Available
|
||||
memData["used"] = memInfo.Used
|
||||
memData["free"] = memInfo.Free
|
||||
memData["usedPercent"] = memInfo.UsedPercent
|
||||
return memData
|
||||
}
|
||||
|
||||
func (c *systemService) GetCpuPercent() float64 {
|
||||
percent, _ := cpu.Percent(0, false)
|
||||
value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", percent[0]), 64)
|
||||
return value
|
||||
}
|
||||
|
||||
func (c *systemService) GetCpuCoreNum() int {
|
||||
count, _ := cpu.Counts(false)
|
||||
return count
|
||||
}
|
||||
|
||||
func (c *systemService) GetNetInfo() []net.IOCountersStat {
|
||||
parts, _ := net.IOCounters(true)
|
||||
return parts
|
||||
}
|
||||
func (c *systemService) GetNet(physics bool) []string {
|
||||
t := "1"
|
||||
if physics {
|
||||
t = "2"
|
||||
}
|
||||
return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetNetCard " + t)
|
||||
}
|
||||
|
||||
func (s *systemService) UpdateSystemVersion(version string) {
|
||||
//command2.OnlyExec(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version)
|
||||
command2.OnlyExec("curl -fsSL https://raw.githubusercontent.com/IceWhaleTech/get/main/update.sh | bash")
|
||||
//s.log.Error(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version)
|
||||
s.log.Error(command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/tools.sh ;update " + version))
|
||||
//s.log.Error(command2.ExecResultStr(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version))
|
||||
}
|
||||
func (s *systemService) UpdateAssist() {
|
||||
s.log.Error(command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/assist.sh"))
|
||||
command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/assist.sh")
|
||||
}
|
||||
|
||||
func (s *systemService) GetTimeZone() string {
|
||||
return command2.ExecResultStr("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetTimeZone")
|
||||
return command2.ExecResultStr("source " + config.AppInfo.ShellPath + "/helper.sh ;GetTimeZone")
|
||||
}
|
||||
|
||||
func (s *systemService) ExecUSBAutoMountShell(state string) {
|
||||
if state == "False" {
|
||||
command2.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;USB_Remove_File")
|
||||
command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Remove_File")
|
||||
} else {
|
||||
command2.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;USB_Move_File")
|
||||
command2.OnlyExec("source " + config.AppInfo.ShellPath + "/helper.sh ;USB_Move_File")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (s *systemService) GetSystemConfigDebug() []string {
|
||||
return command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetSysInfo")
|
||||
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 {
|
||||
@@ -65,11 +243,11 @@ func (s *systemService) UpSystemConfig(str string, widget string) {
|
||||
}
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
}
|
||||
func (s *systemService) UpAppOrderFile(str string) {
|
||||
file.WriteToPath([]byte(str), config.AppInfo.ProjectPath+"/conf", "app_order.json")
|
||||
func (s *systemService) UpAppOrderFile(str, id string) {
|
||||
file.WriteToPath([]byte(str), config.AppInfo.DBPath+"/"+id, "app_order.json")
|
||||
}
|
||||
func (s *systemService) GetAppOrderFile() []byte {
|
||||
return file.ReadFullFile(config.AppInfo.ProjectPath + "/conf/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
|
||||
@@ -84,7 +262,10 @@ func (s *systemService) UpSystemPort(port string) {
|
||||
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
|
||||
}
|
||||
func (s *systemService) GetCasaOSLogs(lineNumber int) string {
|
||||
file, err := os.Open(s.log.Path())
|
||||
file, err := os.Open(filepath.Join(config.AppInfo.LogPath, fmt.Sprintf("%s.%s",
|
||||
config.AppInfo.LogSaveName,
|
||||
config.AppInfo.LogFileExt,
|
||||
)))
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
@@ -99,12 +280,12 @@ func (s *systemService) GetCasaOSLogs(lineNumber int) string {
|
||||
|
||||
func GetDeviceAllIP() []string {
|
||||
var address []string
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
addrs, err := net2.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return address
|
||||
}
|
||||
for _, a := range addrs {
|
||||
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
|
||||
if ipNet, ok := a.(*net2.IPNet); ok && !ipNet.IP.IsLoopback() {
|
||||
if ipNet.IP.To16() != nil {
|
||||
address = append(address, ipNet.IP.String())
|
||||
}
|
||||
@@ -112,6 +293,6 @@ func GetDeviceAllIP() []string {
|
||||
}
|
||||
return address
|
||||
}
|
||||
func NewSystemService(log loger.OLog) SystemService {
|
||||
return &systemService{log: log}
|
||||
func NewSystemService() SystemService {
|
||||
return &systemService{}
|
||||
}
|
||||
|
||||
146
service/task.go
146
service/task.go
@@ -1,146 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
json2 "encoding/json"
|
||||
"strconv"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
|
||||
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
|
||||
"github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"github.com/IceWhaleTech/CasaOS/types"
|
||||
"github.com/tidwall/gjson"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type TaskService interface {
|
||||
List(desc bool) []model.TaskDBModel
|
||||
Delete(id string)
|
||||
Add(m *model.TaskDBModel)
|
||||
Update(m *model.TaskDBModel)
|
||||
Info(id string) model.TaskDBModel
|
||||
SyncTaskService()
|
||||
GetServerTasks() []model.TaskDBModel
|
||||
}
|
||||
|
||||
type taskService struct {
|
||||
db *gorm.DB
|
||||
log loger2.OLog
|
||||
}
|
||||
|
||||
func (s *taskService) List(desc bool) []model.TaskDBModel {
|
||||
var list []model.TaskDBModel
|
||||
var orderBy string
|
||||
if !desc {
|
||||
orderBy = "id"
|
||||
} else {
|
||||
orderBy = "id DESC"
|
||||
}
|
||||
s.db.Order(orderBy).Where("state=?", types.TASK_STATE_UNCOMPLETE).Find(&list)
|
||||
return list
|
||||
}
|
||||
|
||||
func (s *taskService) Delete(id string) {
|
||||
var m model.TaskDBModel
|
||||
s.db.Where("id = ?", id).Delete(&m)
|
||||
}
|
||||
|
||||
func (s *taskService) Add(m *model.TaskDBModel) {
|
||||
s.db.Save(m)
|
||||
}
|
||||
func (s *taskService) Update(m *model.TaskDBModel) {
|
||||
s.db.Model(&m).Update("state", m.State)
|
||||
}
|
||||
func (s *taskService) taskDirService(id string) model.TaskDBModel {
|
||||
var m model.TaskDBModel
|
||||
s.db.Where("id = ?", id).First(&m)
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *taskService) Info(id string) model.TaskDBModel {
|
||||
var m model.TaskDBModel
|
||||
s.db.Where("id = ?", id).Delete(&m)
|
||||
return m
|
||||
}
|
||||
func (s *taskService) GetServerTasks() []model.TaskDBModel {
|
||||
var count int64
|
||||
s.db.Model(&model.TaskDBModel{}).Count(&count)
|
||||
head := make(map[string]string)
|
||||
|
||||
t := make(chan string)
|
||||
|
||||
go func() {
|
||||
str := httper2.Get(config.ServerInfo.ServerApi+"/token", nil)
|
||||
|
||||
t <- gjson.Get(str, "data").String()
|
||||
}()
|
||||
head["Authorization"] = <-t
|
||||
|
||||
listS := httper2.Get(config.ServerInfo.ServerApi+"/v1/task/list/0?desc=true", head)
|
||||
|
||||
list := []model.TaskDBModel{}
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list)
|
||||
|
||||
//go func(list []model.TaskDBModel) {
|
||||
// for _, dbModel := range list {
|
||||
// dbModel.Id = 0
|
||||
// s.db.Create(&dbModel)
|
||||
// }
|
||||
//}(list)
|
||||
return list
|
||||
}
|
||||
func (s *taskService) SyncTaskService() {
|
||||
var count int64
|
||||
s.db.Model(&model.TaskDBModel{}).Count(&count)
|
||||
head := make(map[string]string)
|
||||
|
||||
t := make(chan string)
|
||||
|
||||
go func() {
|
||||
str := httper2.Get(config.ServerInfo.ServerApi+"/token", nil)
|
||||
|
||||
t <- gjson.Get(str, "data").String()
|
||||
}()
|
||||
head["Authorization"] = <-t
|
||||
|
||||
listS := httper2.Get(config.ServerInfo.ServerApi+"/v1/task/list/"+strconv.Itoa(int(count)), head)
|
||||
|
||||
list := []model.TaskDBModel{}
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list)
|
||||
|
||||
go func(list []model.TaskDBModel) {
|
||||
for _, dbModel := range list {
|
||||
dbModel.Id = 0
|
||||
s.db.Create(&dbModel)
|
||||
}
|
||||
}(list)
|
||||
}
|
||||
func SyncTask(db *gorm.DB) {
|
||||
var count int64
|
||||
db.Model(&model.TaskDBModel{}).Count(&count)
|
||||
head := make(map[string]string)
|
||||
|
||||
t := make(chan string)
|
||||
|
||||
go func() {
|
||||
str := httper2.Get(config.ServerInfo.ServerApi+"/token", nil)
|
||||
|
||||
t <- gjson.Get(str, "data").String()
|
||||
}()
|
||||
head["Authorization"] = <-t
|
||||
|
||||
listS := httper2.Get(config.ServerInfo.ServerApi+"/v1/task/list/"+strconv.Itoa(int(count)), head)
|
||||
|
||||
list := []model.TaskDBModel{}
|
||||
json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list)
|
||||
|
||||
go func(list []model.TaskDBModel) {
|
||||
for _, dbModel := range list {
|
||||
dbModel.Id = 0
|
||||
db.Create(&dbModel)
|
||||
}
|
||||
}(list)
|
||||
}
|
||||
func NewTaskService(db *gorm.DB, log loger2.OLog) TaskService {
|
||||
return &taskService{db: db, log: log}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/model/notify"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/quic_helper"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
@@ -92,7 +93,7 @@ func UDPSendData(msg model.MessageModel, localFilePath string) error {
|
||||
}
|
||||
|
||||
func Dial(msg model.MessageModel, server bool) (m model.MessageModel, err error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
|
||||
defer cancel()
|
||||
Message = make(chan model.MessageModel)
|
||||
_, port, err := net.SplitHostPort(UDPConn.LocalAddr().String())
|
||||
@@ -185,7 +186,7 @@ func ReadContent(stream quic.Stream) {
|
||||
fmt.Println(err)
|
||||
time.Sleep(time.Second * 1)
|
||||
for k, v := range CancelList {
|
||||
tempPath := config.AppInfo.RootPath + "/temp" + "/" + v
|
||||
tempPath := config.AppInfo.TempPath + "/" + v
|
||||
fmt.Println(file.RMDir(tempPath))
|
||||
delete(CancelList, k)
|
||||
}
|
||||
@@ -236,20 +237,20 @@ func ReadContent(stream quic.Stream) {
|
||||
Message <- m
|
||||
break
|
||||
} else if m.Type == types.PERSONGETIP {
|
||||
notify := model2.AppNotify{}
|
||||
notify.CustomId = m.From
|
||||
notify := notify.Person{}
|
||||
notify.ShareId = m.From
|
||||
if len(m.Data.(string)) == 0 {
|
||||
if _, ok := UDPAddressMap[m.From]; ok {
|
||||
notify.Type = types.NOTIFY_TYPE_PERSION_FIRNED_LEAVE
|
||||
go MyService.Notify().SendText(notify)
|
||||
notify.Type = "OFFLINE"
|
||||
go MyService.Notify().SendPersonStatusBySocket(notify)
|
||||
}
|
||||
delete(UDPAddressMap, m.From)
|
||||
Message <- m
|
||||
break
|
||||
}
|
||||
if _, ok := UDPAddressMap[m.From]; !ok {
|
||||
notify.Type = types.NOTIFY_TYPE_PERSION_FIRNED_LIVE
|
||||
go MyService.Notify().SendText(notify)
|
||||
notify.Type = "ONLINE"
|
||||
go MyService.Notify().SendPersonStatusBySocket(notify)
|
||||
}
|
||||
UDPAddressMap[m.From] = m.Data.(string)
|
||||
if config.ServerInfo.Token != m.From && strings.Split(m.Data.(string), ":")[0] == strings.Split(UDPAddressMap[config.ServerInfo.Token], ":")[0] {
|
||||
@@ -330,10 +331,10 @@ func LoopFriend() {
|
||||
data, err := Dial(msg, false)
|
||||
if err != nil || reflect.DeepEqual(data, model.MessageModel{}) || len(data.Data.(string)) == 0 {
|
||||
if oldIP == UDPAddressMap[list[i].Token] {
|
||||
notify := model2.AppNotify{}
|
||||
notify.CustomId = data.From
|
||||
notify.Type = types.NOTIFY_TYPE_PERSION_FIRNED_LEAVE
|
||||
go MyService.Notify().SendText(notify)
|
||||
notify := notify.Person{}
|
||||
notify.ShareId = data.From
|
||||
notify.Type = "LEAVE"
|
||||
go MyService.Notify().SendPersonStatusBySocket(notify)
|
||||
|
||||
delete(UDPAddressMap, list[i].Token)
|
||||
|
||||
@@ -444,7 +445,7 @@ func SaveFile(m model.MessageModel, stream quic.Stream) bool {
|
||||
fmt.Println("hash不匹配", hash, dataModel.Hash)
|
||||
return false
|
||||
}
|
||||
tempPath := config.AppInfo.RootPath + "/temp" + "/" + m.UUId
|
||||
tempPath := config.AppInfo.TempPath + "/" + m.UUId
|
||||
file.IsNotExistMkDir(tempPath)
|
||||
filepath := tempPath + "/" + strconv.Itoa(dataModel.Index)
|
||||
_, err = os.Stat(filepath)
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
/*
|
||||
* @Author: LinkLeong link@icewhale.com
|
||||
* @Date: 2022-03-18 11:40:55
|
||||
* @LastEditors: LinkLeong
|
||||
* @LastEditTime: 2022-06-23 19:45:49
|
||||
* @FilePath: /CasaOS/service/user.go
|
||||
* @Description:
|
||||
* @Website: https://www.casaos.io
|
||||
* Copyright (c) 2022 by icewhale, All Rights Reserved.
|
||||
*/
|
||||
package service
|
||||
|
||||
import (
|
||||
@@ -6,18 +16,75 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
"github.com/IceWhaleTech/CasaOS/service/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type UserService interface {
|
||||
SetUser(username, pwd, token, email, desc, nickName string) error
|
||||
UpLoadFile(file multipart.File, name string) error
|
||||
CreateUser(m model.UserDBModel) model.UserDBModel
|
||||
GetUserCount() (userCount int64)
|
||||
UpdateUser(m model.UserDBModel)
|
||||
UpdateUserPassword(m model.UserDBModel)
|
||||
GetUserInfoById(id string) (m model.UserDBModel)
|
||||
GetUserAllInfoById(id string) (m model.UserDBModel)
|
||||
GetUserAllInfoByName(userName string) (m model.UserDBModel)
|
||||
DeleteUserById(id string)
|
||||
GetUserInfoByUserName(userName string) (m model.UserDBModel)
|
||||
GetAllUserName() (list []model.UserDBModel)
|
||||
}
|
||||
|
||||
type user struct {
|
||||
var UserRegisterHash = make(map[string]string)
|
||||
|
||||
type userService struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (u *userService) DeleteUserById(id string) {
|
||||
u.db.Where("id= ?", id).Delete(&model.UserDBModel{})
|
||||
}
|
||||
|
||||
func (u *userService) GetAllUserName() (list []model.UserDBModel) {
|
||||
u.db.Select("user_name").Find(&list)
|
||||
return
|
||||
}
|
||||
func (u *userService) CreateUser(m model.UserDBModel) model.UserDBModel {
|
||||
u.db.Create(&m)
|
||||
return m
|
||||
}
|
||||
|
||||
func (u *userService) GetUserCount() (userCount int64) {
|
||||
u.db.Find(&model.UserDBModel{}).Count(&userCount)
|
||||
return
|
||||
}
|
||||
|
||||
func (u *userService) UpdateUser(m model.UserDBModel) {
|
||||
u.db.Model(&m).Omit("password").Updates(&m)
|
||||
}
|
||||
func (u *userService) UpdateUserPassword(m model.UserDBModel) {
|
||||
u.db.Model(&m).Update("password", m.Password)
|
||||
}
|
||||
func (u *userService) GetUserAllInfoById(id string) (m model.UserDBModel) {
|
||||
u.db.Where("id= ?", id).First(&m)
|
||||
return
|
||||
}
|
||||
func (u *userService) GetUserAllInfoByName(userName string) (m model.UserDBModel) {
|
||||
u.db.Where("user_name= ?", userName).First(&m)
|
||||
return
|
||||
}
|
||||
func (u *userService) GetUserInfoById(id string) (m model.UserDBModel) {
|
||||
u.db.Select("user_name", "id", "role", "nick_name", "description", "avatar").Where("id= ?", id).First(&m)
|
||||
return
|
||||
}
|
||||
|
||||
func (u *userService) GetUserInfoByUserName(userName string) (m model.UserDBModel) {
|
||||
u.db.Select("user_name", "id", "role", "nick_name", "description", "avatar").Where("user_name= ?", userName).First(&m)
|
||||
return
|
||||
}
|
||||
|
||||
//设置用户名密码
|
||||
func (c *user) SetUser(username, pwd, token, email, desc, nickName string) error {
|
||||
func (u *userService) SetUser(username, pwd, token, email, desc, nickName string) error {
|
||||
if len(username) > 0 {
|
||||
config.Cfg.Section("user").Key("UserName").SetValue(username)
|
||||
config.UserInfo.UserName = username
|
||||
@@ -45,7 +112,7 @@ func (c *user) SetUser(username, pwd, token, email, desc, nickName string) error
|
||||
}
|
||||
|
||||
//上传文件
|
||||
func (c *user) UpLoadFile(file multipart.File, url string) error {
|
||||
func (c *userService) UpLoadFile(file multipart.File, url string) error {
|
||||
out, _ := os.OpenFile(url, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
|
||||
defer out.Close()
|
||||
io.Copy(out, file)
|
||||
@@ -53,6 +120,6 @@ func (c *user) UpLoadFile(file multipart.File, url string) error {
|
||||
}
|
||||
|
||||
//获取用户Service
|
||||
func NewUserService() UserService {
|
||||
return &user{}
|
||||
func NewUserService(db *gorm.DB) UserService {
|
||||
return &userService{db: db}
|
||||
}
|
||||
|
||||
@@ -1,258 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/IceWhaleTech/CasaOS/model"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/config"
|
||||
command2 "github.com/IceWhaleTech/CasaOS/pkg/utils/command"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
|
||||
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/disk"
|
||||
"github.com/shirou/gopsutil/v3/host"
|
||||
"github.com/shirou/gopsutil/v3/mem"
|
||||
"github.com/shirou/gopsutil/v3/net"
|
||||
)
|
||||
|
||||
//系统信息
|
||||
type ZiMaService interface {
|
||||
GetCpuPercent() float64
|
||||
GetCpuCoreNum() int
|
||||
GetMemInfo() *mem.VirtualMemoryStat
|
||||
GetDiskInfo() *disk.UsageStat
|
||||
GetNetInfo() []net.IOCountersStat
|
||||
GetNet(physics bool) []string
|
||||
GetNetState(name string) string
|
||||
GetSysInfo() host.InfoStat
|
||||
GetDirPath(path string) []model.Path
|
||||
GetDirPathOne(path string) (m model.Path)
|
||||
MkdirAll(path string) (int, error)
|
||||
CreateFile(path string) (int, error)
|
||||
RenameFile(oldF, newF string) (int, error)
|
||||
GetCpuInfo() []cpu.InfoStat
|
||||
GetDeviceTree() string
|
||||
}
|
||||
|
||||
var NetArray [][]model.IOCountersStat
|
||||
|
||||
type zima struct {
|
||||
}
|
||||
|
||||
//获取cpu占用率
|
||||
func (c *zima) GetCpuPercent() float64 {
|
||||
percent, _ := cpu.Percent(0, false)
|
||||
value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", percent[0]), 64)
|
||||
return value
|
||||
}
|
||||
|
||||
//获取物理核心数
|
||||
func (c *zima) GetCpuCoreNum() int {
|
||||
count, _ := cpu.Counts(false)
|
||||
return count
|
||||
}
|
||||
|
||||
//cpu详情
|
||||
func (c *zima) GetCpuInfo() []cpu.InfoStat {
|
||||
info, _ := cpu.Info()
|
||||
return info
|
||||
}
|
||||
|
||||
//获取内存详情
|
||||
func (c *zima) GetMemInfo() *mem.VirtualMemoryStat {
|
||||
memInfo, _ := mem.VirtualMemory()
|
||||
memInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", memInfo.UsedPercent), 64)
|
||||
return memInfo
|
||||
}
|
||||
|
||||
//获取硬盘详情
|
||||
func (c *zima) GetDiskInfo() *disk.UsageStat {
|
||||
path := "/"
|
||||
if runtime.GOOS == "windows" {
|
||||
path = "C:"
|
||||
}
|
||||
diskInfo, _ := disk.Usage(path)
|
||||
diskInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.UsedPercent), 64)
|
||||
diskInfo.InodesUsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.InodesUsedPercent), 64)
|
||||
return diskInfo
|
||||
}
|
||||
|
||||
//获取硬盘目录
|
||||
func (c *zima) GetDirPath(path string) []model.Path {
|
||||
if path == "/DATA" {
|
||||
sysType := runtime.GOOS
|
||||
if sysType == "windows" {
|
||||
path = "C:\\CasaOS\\DATA"
|
||||
}
|
||||
if sysType == "darwin" {
|
||||
path = "./CasaOS/DATA"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ls, _ := ioutil.ReadDir(path)
|
||||
dirs := []model.Path{}
|
||||
if len(path) > 0 {
|
||||
for _, l := range ls {
|
||||
filePath := filepath.Join(path, l.Name())
|
||||
link, err := filepath.EvalSymlinks(filePath)
|
||||
if err != nil {
|
||||
link = filePath
|
||||
}
|
||||
temp := model.Path{Name: l.Name(), Path: filePath, IsDir: l.IsDir(), Date: l.ModTime(), Size: l.Size()}
|
||||
if filePath != link {
|
||||
file, _ := os.Stat(link)
|
||||
temp.IsDir = file.IsDir()
|
||||
}
|
||||
dirs = append(dirs, temp)
|
||||
}
|
||||
} else {
|
||||
dirs = append(dirs, model.Path{Name: "DATA", Path: "/DATA/", IsDir: true, Date: time.Now()})
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
func (c *zima) GetDirPathOne(path string) (m model.Path) {
|
||||
|
||||
f, err := os.Stat(path)
|
||||
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.IsDir = f.IsDir()
|
||||
m.Name = f.Name()
|
||||
m.Path = path
|
||||
m.Size = f.Size()
|
||||
m.Date = f.ModTime()
|
||||
return
|
||||
}
|
||||
|
||||
//获取系统信息
|
||||
func (c *zima) GetSysInfo() host.InfoStat {
|
||||
info, _ := host.Info()
|
||||
return *info
|
||||
}
|
||||
|
||||
//shell脚本参数 {1:虚拟网卡 2:物理网卡}
|
||||
func (c *zima) GetNet(physics bool) []string {
|
||||
t := "1"
|
||||
if physics {
|
||||
t = "2"
|
||||
}
|
||||
return command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetNetCard " + t)
|
||||
}
|
||||
|
||||
func (c *zima) GetDeviceTree() string {
|
||||
return command2.ExecResultStr("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetDeviceTree")
|
||||
}
|
||||
|
||||
//shell脚本参数 { 网卡名称 }
|
||||
func (c *zima) GetNetState(name string) string {
|
||||
return command2.ExecResultStr("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;CatNetCardState " + name)
|
||||
}
|
||||
|
||||
//网络信息
|
||||
func (c *zima) GetNetInfo() []net.IOCountersStat {
|
||||
parts, _ := net.IOCounters(true)
|
||||
//fmt.Println(net.ConntrackStatsWithContext(true))
|
||||
return parts
|
||||
}
|
||||
|
||||
//mkdir
|
||||
func (c *zima) MkdirAll(path string) (int, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return oasis_err.DIR_ALREADY_EXISTS, nil
|
||||
} else {
|
||||
if os.IsNotExist(err) {
|
||||
os.MkdirAll(path, os.ModePerm)
|
||||
return oasis_err.SUCCESS, nil
|
||||
} else if strings.Contains(err.Error(), ": not a directory") {
|
||||
return oasis_err.FILE_OR_DIR_EXISTS, err
|
||||
}
|
||||
}
|
||||
return oasis_err.ERROR, err
|
||||
}
|
||||
|
||||
//create
|
||||
func (c *zima) CreateFile(path string) (int, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return oasis_err.FILE_OR_DIR_EXISTS, nil
|
||||
} else {
|
||||
if os.IsNotExist(err) {
|
||||
file.CreateFile(path)
|
||||
return oasis_err.SUCCESS, nil
|
||||
}
|
||||
}
|
||||
return oasis_err.ERROR, err
|
||||
}
|
||||
|
||||
//修改文件
|
||||
func (c *zima) RenameFile(oldF, newF string) (int, error) {
|
||||
|
||||
_, err := os.Stat(newF)
|
||||
if err == nil {
|
||||
return oasis_err.DIR_ALREADY_EXISTS, nil
|
||||
} else {
|
||||
if os.IsNotExist(err) {
|
||||
err := os.Rename(oldF, newF)
|
||||
if err != nil {
|
||||
return oasis_err.ERROR, err
|
||||
}
|
||||
return oasis_err.SUCCESS, nil
|
||||
}
|
||||
}
|
||||
return oasis_err.ERROR, err
|
||||
}
|
||||
|
||||
//获取zima服务
|
||||
func NewZiMaService() ZiMaService {
|
||||
return &zima{}
|
||||
}
|
||||
|
||||
func LoopNet() {
|
||||
netList := MyService.ZiMa().GetNetInfo()
|
||||
|
||||
nets := MyService.ZiMa().GetNet(true)
|
||||
num := 0
|
||||
for i := 0; i < len(netList); i++ {
|
||||
|
||||
for _, netCardName := range nets {
|
||||
|
||||
if netList[i].Name == netCardName {
|
||||
var netArray []model.IOCountersStat
|
||||
if len(NetArray) < (num + 1) {
|
||||
netArray = []model.IOCountersStat{}
|
||||
} else {
|
||||
netArray = NetArray[num]
|
||||
}
|
||||
item := *(*model.IOCountersStat)(unsafe.Pointer(&netList[i]))
|
||||
item.State = strings.TrimSpace(MyService.ZiMa().GetNetState(netList[i].Name))
|
||||
item.Time = time.Now().Unix()
|
||||
|
||||
if len(netArray) >= 60 {
|
||||
netArray = netArray[1:]
|
||||
}
|
||||
netArray = append(netArray, item)
|
||||
if len(NetArray) < (num + 1) {
|
||||
NetArray = append(NetArray, []model.IOCountersStat{})
|
||||
}
|
||||
|
||||
NetArray[num] = netArray
|
||||
|
||||
num++
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,3 @@
|
||||
#!/bin/bash
|
||||
|
||||
|
||||
|
||||
# add in v0.2.5
|
||||
|
||||
readonly CASA_DEPANDS="curl smartmontools parted fdisk ntfs-3g"
|
||||
|
||||
version_0_2_5() {
|
||||
install_depends "$CASA_DEPANDS"
|
||||
}
|
||||
version_0_2_11() {
|
||||
sysctl -w net.core.rmem_max=2500000
|
||||
}
|
||||
|
||||
#Install Depends
|
||||
install_depends() {
|
||||
((EUID)) && sudo_cmd="sudo"
|
||||
if [[ ! -x "$(command -v '$1')" ]]; then
|
||||
packagesNeeded=$1
|
||||
if [ -x "$(command -v apk)" ]; then
|
||||
$sudo_cmd apk add --no-cache $packagesNeeded
|
||||
elif [ -x "$(command -v apt-get)" ]; then
|
||||
$sudo_cmd apt-get -y -q install $packagesNeeded
|
||||
elif [ -x "$(command -v dnf)" ]; then
|
||||
$sudo_cmd dnf install $packagesNeeded
|
||||
elif [ -x "$(command -v zypper)" ]; then
|
||||
$sudo_cmd zypper install $packagesNeeded
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
version_0_2_5
|
||||
|
||||
version_0_2_11
|
||||
|
||||
105
shell/delete-old-service.sh
Normal file
105
shell/delete-old-service.sh
Normal file
@@ -0,0 +1,105 @@
|
||||
#!/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
|
||||
202
shell/tools.sh
202
shell/tools.sh
@@ -1,202 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
#######################################
|
||||
# Custom printing function
|
||||
# Globals:
|
||||
# None
|
||||
# Arguments:
|
||||
# $1 0:OK 1:FAILED
|
||||
# message
|
||||
# Returns:
|
||||
# None
|
||||
#######################################
|
||||
|
||||
readonly CASA_PATH=/casaOS/server
|
||||
readonly casa_bin="casaos"
|
||||
|
||||
version=""
|
||||
|
||||
usage() {
|
||||
cat <<-EOF
|
||||
Usage: tool.sh [options]
|
||||
Valid options are:
|
||||
-r <version> verison of casaos
|
||||
-h show this help message and exit
|
||||
EOF
|
||||
exit $1
|
||||
}
|
||||
|
||||
show() {
|
||||
local color=("$@") output grey green red reset
|
||||
if [[ -t 0 || -t 1 ]]; then
|
||||
output='\e[0m\r\e[J' grey='\e[90m' green='\e[32m' red='\e[31m' reset='\e[0m'
|
||||
fi
|
||||
local left="${grey}[$reset" right="$grey]$reset"
|
||||
local ok="$left$green OK $right " failed="$left${red}FAILED$right " info="$left$green INFO $right "
|
||||
# Print color array from index $1
|
||||
Print() {
|
||||
[[ $1 == 1 ]]
|
||||
for ((i = $1; i < ${#color[@]}; i++)); do
|
||||
output+=${color[$i]}
|
||||
done
|
||||
echo -ne "$output$reset"
|
||||
}
|
||||
|
||||
if (($1 == 0)); then
|
||||
output+=$ok
|
||||
color+=('\n')
|
||||
Print 1
|
||||
|
||||
elif (($1 == 1)); then
|
||||
output+=$failed
|
||||
color+=('\n')
|
||||
Print 1
|
||||
|
||||
elif (($1 == 2)); then
|
||||
output+=$info
|
||||
color+=('\n')
|
||||
Print 1
|
||||
fi
|
||||
}
|
||||
|
||||
run_external_script() {
|
||||
assist.sh
|
||||
}
|
||||
|
||||
update() {
|
||||
trap 'echo -e "Aborted, error $? in command: $BASH_COMMAND"; trap ERR; return 1' ERR
|
||||
|
||||
# Not every platform has or needs sudo (https://termux.com/linux.html)
|
||||
((EUID)) && sudo_cmd="sudo"
|
||||
|
||||
target_os="unsupported"
|
||||
target_arch="unknown"
|
||||
install_path="/usr/local/bin"
|
||||
|
||||
# Fall back to /usr/bin if necessary
|
||||
if [[ ! -d $install_path ]]; then
|
||||
install_path="/usr/bin"
|
||||
fi
|
||||
|
||||
#########################
|
||||
# Which OS and version? #
|
||||
#########################
|
||||
casa_tmp_folder="casaos"
|
||||
|
||||
casa_dl_ext=".tar.gz"
|
||||
|
||||
# NOTE: `uname -m` is more accurate and universal than `arch`
|
||||
# See https://en.wikipedia.org/wiki/Uname
|
||||
unamem="$(uname -m)"
|
||||
case $unamem in
|
||||
*aarch64*)
|
||||
target_arch="arm64"
|
||||
;;
|
||||
*64*)
|
||||
target_arch="amd64"
|
||||
;;
|
||||
*86*)
|
||||
target_arch="386"
|
||||
;;
|
||||
*armv5*)
|
||||
target_arch="arm-5"
|
||||
;;
|
||||
*armv6*)
|
||||
target_arch="arm-6"
|
||||
;;
|
||||
*armv7*)
|
||||
target_arch="arm-7"
|
||||
;;
|
||||
*)
|
||||
show 1 "Aborted, unsupported or unknown architecture: $unamem"
|
||||
return 2
|
||||
;;
|
||||
esac
|
||||
|
||||
unameu="$(tr '[:lower:]' '[:upper:]' <<<$(uname))"
|
||||
if [[ $unameu == *DARWIN* ]]; then
|
||||
target_os="darwin"
|
||||
elif [[ $unameu == *LINUX* ]]; then
|
||||
target_os="linux"
|
||||
elif [[ $unameu == *FREEBSD* ]]; then
|
||||
target_os="freebsd"
|
||||
elif [[ $unameu == *NETBSD* ]]; then
|
||||
target_os="netbsd"
|
||||
elif [[ $unameu == *OPENBSD* ]]; then
|
||||
target_os="openbsd"
|
||||
else
|
||||
show 1 "Aborted, unsupported or unknown OS: $uname"
|
||||
return 6
|
||||
fi
|
||||
|
||||
########################
|
||||
# Download and extract #
|
||||
########################
|
||||
show 2 "Downloading CasaOS for $target_os/$target_arch..."
|
||||
if type -p curl >/dev/null 2>&1; then
|
||||
net_getter="curl -fsSL"
|
||||
elif type -p wget >/dev/null 2>&1; then
|
||||
net_getter="wget -qO-"
|
||||
else
|
||||
show 1 "Aborted, could not find curl or wget"
|
||||
return 7
|
||||
fi
|
||||
|
||||
casa_file="${target_os}-$target_arch-casaos$casa_dl_ext"
|
||||
casa_tag="$(${net_getter} https://api.github.com/repos/IceWhaleTech/CasaOS/releases/latest | grep -o '"tag_name": ".*"' | sed 's/"//g' | sed 's/tag_name: //g')"
|
||||
casa_url="https://github.com/IceWhaleTech/CasaOS/releases/download/$casa_tag/$casa_file"
|
||||
show 2 "$casa_url"
|
||||
# Use $PREFIX for compatibility with Termux on Android
|
||||
rm -rf "$PREFIX/tmp/$casa_file"
|
||||
|
||||
${net_getter} "$casa_url" >"$PREFIX/tmp/$casa_file"
|
||||
|
||||
show 2 "Extracting..."
|
||||
case "$casa_file" in
|
||||
*.zip) unzip -o "$PREFIX/tmp/$casa_file" -d "$PREFIX/tmp/" ;;
|
||||
*.tar.gz) tar -xzf "$PREFIX/tmp/$casa_file" -C "$PREFIX/tmp/" ;;
|
||||
esac
|
||||
|
||||
chmod +x "$PREFIX/tmp/$casa_tmp_folder/$casa_bin"
|
||||
|
||||
#stop service
|
||||
show 2 "Putting CasaOS in $install_path (may require password)"
|
||||
$sudo_cmd mv -f "$PREFIX/tmp/$casa_tmp_folder/$casa_bin" "$install_path/"
|
||||
show 2 "Putting CasaOS Shell file in $CASA_PATH (may require password)"
|
||||
#check shell folder
|
||||
local casa_shell_path=$CASA_PATH/shell
|
||||
|
||||
if [[ -d $casa_shell_path ]]; then
|
||||
rm -rf $casa_shell_path
|
||||
fi
|
||||
|
||||
$sudo_cmd mv -f $PREFIX/tmp/$casa_tmp_folder/shell "$CASA_PATH/shell"
|
||||
|
||||
# remove tmp files
|
||||
$sudo_cmd rm -rf $PREFIX/tmp/$casa_tmp_folder
|
||||
|
||||
if type -p $casa_bin >/dev/null 2>&1; then
|
||||
trap ERR
|
||||
run_external_script
|
||||
# $sudo_cmd systemctl start casaos
|
||||
$sudo_cmd systemctl restart casaos
|
||||
show 0 "CasaOS Successfully updated."
|
||||
return 0
|
||||
else
|
||||
show 1 "Something went wrong, CasaOS is not in your path"
|
||||
trap ERR
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
while getopts ":s:l:S:L:i:e:a:b:w:p:G:D:oOuUfgrczh" arg; do
|
||||
case "$arg" in
|
||||
r)
|
||||
version=$OPTARG
|
||||
update
|
||||
;;
|
||||
h)
|
||||
usage 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user