Compare commits

..

19 Commits

Author SHA1 Message Date
link
752134942a V0.3.3 (#334)
* switch branches

* update user interface

* switch branch

* switch branch

* change branch

* submit 0.3.3

* Update UI

* update version function

* Update UI

* Update user.go

* update disk

* update person info interface

* Update main.go

* Update UI

* update alpha

* updata ui

* Update assist.sh

* Update assist.sh

* update update function

* add upload sh

* Update init.go

* upload shell script

* Update system.go

* update update.sh

* Update init.go

* update update.sh

* update update.sh

* Update update.sh

* Update system.go

* Update system.go

* update UI

* Update CHANGELOG.md
2022-07-01 15:19:16 +08:00
link
faf683a02c V0.3.3 (#331)
* switch branches

* update user interface

* switch branch

* switch branch

* change branch

* submit 0.3.3

* Update UI
2022-06-29 11:22:12 +08:00
link
f99f49dd7e V0.3.3 (#330)
* switch branches

* update user interface

* switch branch

* switch branch

* change branch

* submit 0.3.3
2022-06-29 11:09:58 +08:00
David Tippett
b0dc30277b Adding simple Developing file (#311)
* Adding developing guide with env setup

Signed-off-by: David Tippett <dtaivpp@gmail.com>

* Fixing formatting on developing guide

Signed-off-by: David Tippett <dtaivpp@gmail.com>

* Switching nav to bulleted list

Signed-off-by: David Tippett <dtaivpp@gmail.com>

* Forgot a word o_o

Signed-off-by: David Tippett <dtaivpp@gmail.com>
2022-06-21 08:57:55 +08:00
a624669980@163.com
d91fef0a19 Update route.go 2022-06-16 21:20:10 +08:00
a624669980@163.com
6bb044ab04 Update version.go 2022-06-16 20:11:11 +08:00
a624669980@163.com
78479f9604 Update file.go 2022-06-16 16:57:13 +08:00
a624669980@163.com
8fe893847f Update CHANGELOG.md 2022-06-16 15:52:50 +08:00
link
f506d6ce49 Dev (#298)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI

* fixed bug

- Fix the problem of application opening failure on non-80 ports
- Modify port failure problem
- Modify environment variables disappearing problem

* update version function

* Fix version update issues

* fixed bug

- [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)

* update UI

* Update CHANGELOG.md

* update app service

* update ui

* Fix application installation host mode error

* update ui

* Update UI
2022-06-15 19:01:26 +08:00
link
5d7c5ba120 Dev (#296)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI

* fixed bug

- Fix the problem of application opening failure on non-80 ports
- Modify port failure problem
- Modify environment variables disappearing problem

* update version function

* Fix version update issues

* fixed bug

- [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)

* update UI

* Update CHANGELOG.md

* update app service

* update ui
2022-06-15 10:22:27 +08:00
link
eedffd7c19 Dev (#292)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI

* fixed bug

- Fix the problem of application opening failure on non-80 ports
- Modify port failure problem
- Modify environment variables disappearing problem

* update version function

* Fix version update issues

* fixed bug

- [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)

* update UI

* Update CHANGELOG.md
2022-06-14 18:22:02 +08:00
link
0885c1386d Dev (#291)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI

* fixed bug

- Fix the problem of application opening failure on non-80 ports
- Modify port failure problem
- Modify environment variables disappearing problem

* update version function

* Fix version update issues

* fixed bug

- [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)

* update UI
2022-06-14 18:11:15 +08:00
link
0297fe67af Dev (#290)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI

* fixed bug

- Fix the problem of application opening failure on non-80 ports
- Modify port failure problem
- Modify environment variables disappearing problem

* update version function

* Fix version update issues

* fixed bug

- [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)

* update UI
2022-06-14 18:10:22 +08:00
link
3f53e6f33b Dev (#288)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI

* fixed bug

- Fix the problem of application opening failure on non-80 ports
- Modify port failure problem
- Modify environment variables disappearing problem

* update version function

* Fix version update issues
2022-06-14 13:24:53 +08:00
link
94d0efdb12 Dev (#285)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI

* fixed bug

- Fix the problem of application opening failure on non-80 ports
- Modify port failure problem
- Modify environment variables disappearing problem
2022-06-13 20:43:19 +08:00
link
1e821d1c10 Dev (#277)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval

* Update UI
2022-06-10 15:32:27 +08:00
link
2c80b53ee8 Dev (#276)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval
2022-06-10 15:16:56 +08:00
link
c33af66c6e Dev (#275)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution

* Update send data interval
2022-06-10 14:47:50 +08:00
link
9d47874ae3 Dev (#274)
* fix bug

* updata UI

* 0.3.2

### 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.
- [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))
### 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))

* Modify log help class

* Fix some bugs in 0.3.2

* Solve the operation file queue problem

* Exclude web folders

* update UI

* add cancel file operate

* Update UI

* Merge sockets to transfer data

* Conflict Resolution
2022-06-10 13:33:53 +08:00
135 changed files with 6518 additions and 7756 deletions

1
.gitignore vendored
View File

@@ -31,6 +31,7 @@ gen
/docs/ /docs/
/web/ /web/
/conf/conf.ini /conf/conf.ini
/conf/conf.json
__debug_bin __debug_bin
main main
CasaOS CasaOS

View File

@@ -18,7 +18,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed ### Fixed
## [0.3.2-pre] - 2022-06-08 ## [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 ### Added

33
DEVELOPING.md Normal file
View 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

Submodule UI updated: 694c60e3a1...7af1bf549d

41
alpha.md Normal file
View 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
View 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

View File

@@ -1,19 +1,20 @@
[app] [app]
PAGE_SIZE = 10 PAGE_SIZE = 10
RuntimeRootPath = runtime/ RuntimeRootPath = runtime/
LogSavePath = /casaOS/logs/server/ LogPath = /var/log/casaos/
LogSaveName = log LogSaveName = log
LogFileExt = log LogFileExt = log
DateStrFormat = 20060102 DateStrFormat = 20060102
DateTimeFormat = 2006-01-02 15:04:05 DateTimeFormat = 2006-01-02 15:04:05
TimeFormat = 15:04:05 TimeFormat = 15:04:05
DateFormat = 2006-01-02 DateFormat = 2006-01-02
ProjectPath = /casaOS/server DBPath = /var/lib/casaos
RootPath = /casaOS ShellPath = /usr/share/casaos/shell
UserDataPath = /var/lib/casaos/conf
TempPath = /var/lib/casaos/temp
[server] [server]
HttpPort = 8089 HttpPort = 80
UDPPort = UDPPort =
RunMode = release RunMode = release
ServerApi = https://api.casaos.io/casaos-api ServerApi = https://api.casaos.io/casaos-api
@@ -21,20 +22,9 @@ Handshake = socket.casaos.io
Token = Token =
USBAutoMount = USBAutoMount =
[user]
UserName =
PWD =
Email = user@gmail.com
Description = description
Initialized = false
Avatar =
NickName =
PublicKey =
[system] [system]
ConfigStr =
WidgetList = WidgetList =
Analyse =
[file] [file]

2
go.mod
View File

@@ -27,7 +27,7 @@ require (
github.com/go-openapi/spec v0.20.4 // indirect github.com/go-openapi/spec v0.20.4 // indirect
github.com/go-playground/validator/v10 v10.6.1 // indirect github.com/go-playground/validator/v10 v10.6.1 // indirect
github.com/gogo/googleapis v1.4.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/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/gomodule/redigo v1.8.5 github.com/gomodule/redigo v1.8.5
github.com/google/go-github/v36 v36.0.0 github.com/google/go-github/v36 v36.0.0

4
go.sum
View File

@@ -426,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.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= 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/v4 v4.4.1 h1:pC5DB52sCeK48Wlb9oPcdhnjkz1TKt1D/P7WKJ0kUcQ=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= 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-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 h1:C/hKUcHT483btRbeGkrRjJz+Zbcj8audldIi9tRJDCc=
github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI= github.com/golang/geo v0.0.0-20200319012246-673a6f80352d/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=

47
main.go
View File

@@ -10,7 +10,9 @@ import (
"github.com/IceWhaleTech/CasaOS/pkg/cache" "github.com/IceWhaleTech/CasaOS/pkg/cache"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/sqlite" "github.com/IceWhaleTech/CasaOS/pkg/sqlite"
"github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger" "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/pkg/utils/random"
"github.com/IceWhaleTech/CasaOS/route" "github.com/IceWhaleTech/CasaOS/route"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
@@ -23,6 +25,8 @@ var sqliteDB *gorm.DB
var configFlag = flag.String("c", "", "config address") var configFlag = flag.String("c", "", "config address")
var dbFlag = flag.String("db", "", "db path") var dbFlag = flag.String("db", "", "db path")
var showUserInfo = flag.Bool("show-user-info", false, "show user info") 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() { func init() {
flag.Parse() flag.Parse()
@@ -30,16 +34,14 @@ func init() {
config.UpdateSetup() config.UpdateSetup()
loger.LogInit() loger.LogInit()
if len(*dbFlag) == 0 { if len(*dbFlag) == 0 {
*dbFlag = config.AppInfo.ProjectPath + "/db" *dbFlag = config.AppInfo.DBPath + "/db"
} }
sqliteDB = sqlite.GetDb(*dbFlag) sqliteDB = sqlite.GetDb(*dbFlag)
//gredis.GetRedisConn(config.RedisInfo), //gredis.GetRedisConn(config.RedisInfo),
service.MyService = service.NewService(sqliteDB) service.MyService = service.NewService(sqliteDB)
service.Cache = cache.Init() service.Cache = cache.Init()
go service.UDPService() service.GetToken()
fmt.Println("t", service.GetToken())
service.UDPAddressMap = make(map[string]string) service.UDPAddressMap = make(map[string]string)
//go service.SocketConnect() //go service.SocketConnect()
service.CancelList = make(map[string]string) service.CancelList = make(map[string]string)
@@ -47,7 +49,6 @@ func init() {
service.NewVersionApp = make(map[string]string) service.NewVersionApp = make(map[string]string)
route.InitFunction() route.InitFunction()
go service.SendIPToServer()
// go service.LoopFriend() // go service.LoopFriend()
// go service.MyService.App().CheckNewImage() // go service.MyService.App().CheckNewImage()
@@ -72,7 +73,30 @@ func main() {
fmt.Println("Password:" + config.UserInfo.PWD) fmt.Println("Password:" + config.UserInfo.PWD)
return 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 route.SocketInit(service.NotifyMsg)
go func() { go func() {
for i := 0; i < 1000; i++ { for i := 0; i < 1000; i++ {
@@ -100,13 +124,14 @@ func main() {
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
err = cron2.AddFunc("0/3 * * * * *", func() { err = cron2.AddFunc("0/5 * * * * *", func() {
if service.ClientCount > 0 { if service.ClientCount > 0 {
route.SendNetINfoBySocket() //route.SendNetINfoBySocket()
route.SendCPUBySocket() //route.SendCPUBySocket()
route.SendMemBySocket() //route.SendMemBySocket()
route.SendDiskBySocket() // route.SendDiskBySocket()
route.SendUSBBySocket() //route.SendUSBBySocket()
route.SendAllHardwareStatusBySocket()
} }
}) })
if err != nil { if err != nil {

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2021-10-08 10:29:08 * @Date: 2021-10-08 10:29:08
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-05-25 19:17:45 * @LastEditTime: 2022-06-21 15:10:03
* @FilePath: /CasaOS/middleware/gin.go * @FilePath: /CasaOS/middleware/gin.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -14,7 +14,9 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap"
) )
func Cors() gin.HandlerFunc { func Cors() gin.HandlerFunc {
@@ -48,3 +50,9 @@ func Cors() gin.HandlerFunc {
c.Next() 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()
}
}

View File

@@ -6,6 +6,13 @@ import (
"time" "time"
) )
type ServerAppListCollection struct {
List []ServerAppList `json:"list"`
Recommend []ServerAppList `json:"recommend"`
Community []ServerAppList `json:"community"`
Version string `json:"version"`
}
type ServerAppList struct { type ServerAppList struct {
Id uint `gorm:"column:id;primary_key" json:"id"` Id uint `gorm:"column:id;primary_key" json:"id"`
Title string `json:"title"` Title string `json:"title"`
@@ -15,6 +22,7 @@ type ServerAppList struct {
Icon string `json:"icon"` Icon string `json:"icon"`
ScreenshotLink Strings `gorm:"type:json" json:"screenshot_link"` ScreenshotLink Strings `gorm:"type:json" json:"screenshot_link"`
Category string `json:"category"` Category string `json:"category"`
CategoryId int `json:"category_id"`
CategoryFont string `json:"category_font"` CategoryFont string `json:"category_font"`
PortMap string `json:"port_map"` PortMap string `json:"port_map"`
ImageVersion string `json:"image_version"` ImageVersion string `json:"image_version"`
@@ -38,6 +46,7 @@ type ServerAppList struct {
Plugins Strings `json:"plugins"` Plugins Strings `json:"plugins"`
Origin string `json:"origin"` Origin string `json:"origin"`
Type int `json:"type"` Type int `json:"type"`
QueryCount int `json:"query_count"`
Developer string `json:"developer"` Developer string `json:"developer"`
HostName string `json:"host_name"` HostName string `json:"host_name"`
Privileged bool `json:"privileged"` Privileged bool `json:"privileged"`

View File

@@ -1,19 +1,19 @@
/* /*
* @Author: link a624669980@163.com * @Author: link a624669980@163.com
* @Date: 2022-05-16 17:37:08 * @Date: 2022-05-16 17:37:08
* @LastEditors: link a624669980@163.com * @LastEditors: LinkLeong
* @LastEditTime: 2022-06-07 17:12:30 * @LastEditTime: 2022-06-22 17:45:53
* @FilePath: \CasaOS\model\category.go * @FilePath: /CasaOS/model/category.go
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
package model package model
// type ServerCategoryList struct {
// Version string `json:"version"`
// Item []CategoryList `json:"item"`
// }
type ServerCategoryList struct { type ServerCategoryList struct {
Version string `json:"version"`
Item []CategoryList `json:"item"`
}
type CategoryList struct {
Id uint `gorm:"column:id;primary_key" json:"id"` Id uint `gorm:"column:id;primary_key" json:"id"`
//CreatedAt time.Time `json:"created_at"` //CreatedAt time.Time `json:"created_at"`
// //

View File

@@ -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 package model
type DockerStatsModel struct { type DockerStatsModel struct {

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-20 16:27:12 * @Date: 2022-05-20 16:27:12
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-06-08 15:40:33 * @LastEditTime: 2022-06-09 18:18:46
* @FilePath: /CasaOS/model/file.go * @FilePath: /CasaOS/model/file.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -16,6 +16,8 @@ type FileOperate struct {
TotalSize int64 `json:"total_size"` TotalSize int64 `json:"total_size"`
ProcessedSize int64 `json:"processed_size"` ProcessedSize int64 `json:"processed_size"`
To string `json:"to" binding:"required"` To string `json:"to" binding:"required"`
Style string `json:"style"`
Finished bool `json:"finished"`
} }
type FileItem struct { type FileItem struct {

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-13 18:15:46 * @Date: 2022-05-13 18:15:46
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-05-30 16:43:59 * @LastEditTime: 2022-06-16 17:50:56
* @FilePath: /CasaOS/model/sys_common.go * @FilePath: /CasaOS/model/sys_common.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -46,15 +46,17 @@ type ServerModel struct {
//服务配置 //服务配置
type APPModel struct { type APPModel struct {
LogSavePath string LogPath string
LogSaveName string LogSaveName string
LogFileExt string LogFileExt string
DateStrFormat string DateStrFormat string
DateTimeFormat string DateTimeFormat string
UserDataPath string
TimeFormat string TimeFormat string
DateFormat string DateFormat string
ProjectPath string DBPath string
RootPath string ShellPath string
TempPath string
} }
//公共返回模型 //公共返回模型

View File

@@ -1 +0,0 @@
package model

View 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"`
}

View File

@@ -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 package config
const ( const (
USERCONFIGURL = "conf/conf.ini" USERCONFIGURL = "/etc/casaos.conf"
) )

View File

@@ -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 package config
import ( import (
@@ -42,6 +52,9 @@ func InitSetup(config string) {
if len(config) > 0 { if len(config) > 0 {
configDir = config configDir = config
} }
if runtime.GOOS == "darwin" {
configDir = "./conf/conf.conf"
}
var err error var err error
//读取文件 //读取文件
Cfg, err = ini.Load(configDir) Cfg, err = ini.Load(configDir)
@@ -57,6 +70,26 @@ func InitSetup(config string) {
mapTo("system", SystemConfigInfo) mapTo("system", SystemConfigInfo)
mapTo("file", FileSettingInfo) mapTo("file", FileSettingInfo)
SystemConfigInfo.ConfigPath = configDir 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() // AppInfo.ProjectPath = getCurrentDirectory() //os.Getwd()
} }

View File

@@ -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 package sqlite
import ( import (
"fmt"
"time" "time"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
model2 "github.com/IceWhaleTech/CasaOS/service/model" model2 "github.com/IceWhaleTech/CasaOS/service/model"
"go.uber.org/zap"
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -16,7 +27,7 @@ func GetDb(dbPath string) *gorm.DB {
if gdb != nil { if gdb != nil {
return gdb 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) //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{}) //db, err := gorm.Open(mysql2.Open(dsn), &gorm.Config{})
file.IsNotExistMkDir(dbPath) file.IsNotExistMkDir(dbPath)
@@ -26,14 +37,15 @@ func GetDb(dbPath string) *gorm.DB {
c.SetMaxOpenConns(100) c.SetMaxOpenConns(100)
c.SetConnMaxIdleTime(time.Second * 1000) c.SetConnMaxIdleTime(time.Second * 1000)
if err != nil { if err != nil {
fmt.Println("连接数据失败!") loger.Error("sqlite connect error", zap.Any("db connect error", err))
panic("数据库连接失败") panic("sqlite connect error")
return nil return nil
} }
gdb = db 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 { if err != nil {
fmt.Println("检查和创建数据库出错", err) loger.Error("check or create db error", zap.Any("error", err))
} }
return db return db
} }

View File

@@ -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
}

View File

@@ -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")
}
}

View File

@@ -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
}

View File

@@ -1,8 +0,0 @@
package upnp
import "testing"
func TestGateway(t *testing.T) {
Gateway()
}

View File

@@ -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
}

View File

@@ -1,7 +0,0 @@
package upnp
import "testing"
func TestAddPortMapping(t *testing.T) {
//AddPortMapping(6666,6666,"TCP","192.168.2.15000",)
}

View File

@@ -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)
}
}

View File

@@ -1,9 +0,0 @@
package upnp
import (
"testing"
)
func TestTestaaa(t *testing.T) {
(Testaaa())
}

View File

@@ -1,4 +1,4 @@
package oasis_err package common_err
const ( const (
SUCCESS = 200 SUCCESS = 200
@@ -7,20 +7,25 @@ const (
ERROR_AUTH_TOKEN = 401 ERROR_AUTH_TOKEN = 401
//user //user
PWD_INVALID = 10001 PWD_INVALID = 10001
PWD_IS_EMPTY = 10002 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 //system
DIR_ALREADY_EXISTS = 20001 DIR_ALREADY_EXISTS = 20001
FILE_ALREADY_EXISTS = 20002 FILE_ALREADY_EXISTS = 20002
FILE_OR_DIR_EXISTS = 20003 FILE_OR_DIR_EXISTS = 20003
PORT_IS_OCCUPIED = 20004 PORT_IS_OCCUPIED = 20004
COMMAND_ERROR_INVALID_OPERATION = 20005 COMMAND_ERROR_INVALID_OPERATION = 20005
VERIFICATION_FAILURE = 20006
//zerotier
GET_TOKEN_ERROR = 30001
//disk //disk
NAME_NOT_AVAILABLE = 40001 NAME_NOT_AVAILABLE = 40001
@@ -40,6 +45,7 @@ const (
FILE_READ_ERROR = 60002 FILE_READ_ERROR = 60002
FILE_DELETE_ERROR = 60003 FILE_DELETE_ERROR = 60003
DIR_NOT_EXISTS = 60004 DIR_NOT_EXISTS = 60004
SOURCE_DES_SAME = 60005
//shortcuts //shortcuts
SHORTCUTS_URL_ERROR = 70001 SHORTCUTS_URL_ERROR = 70001
@@ -60,19 +66,24 @@ var MsgFlags = map[int]string{
ERROR_AUTH_TOKEN: "Error auth token", ERROR_AUTH_TOKEN: "Error auth token",
//user //user
PWD_INVALID: "Invalid password", PWD_INVALID: "Invalid password",
PWD_IS_EMPTY: "Password is empty", PWD_IS_EMPTY: "Password is empty",
PWD_INVALID_OLD: "Invalid old password", PWD_INVALID_OLD: "Invalid old password",
ACCOUNT_LOCK: "Account is locked", 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 //system
DIR_ALREADY_EXISTS: "Folder already exists", DIR_ALREADY_EXISTS: "Folder already exists",
FILE_ALREADY_EXISTS: "File already exists", FILE_ALREADY_EXISTS: "File already exists",
FILE_OR_DIR_EXISTS: "File or folder already exists", FILE_OR_DIR_EXISTS: "File or folder already exists",
PORT_IS_OCCUPIED: "Port is occupied", PORT_IS_OCCUPIED: "Port is occupied",
VERIFICATION_FAILURE: "Verification failure",
//zerotier
GET_TOKEN_ERROR: "Get token error,Please log in to zerotier's official website to confirm whether the account is available",
//app //app
UNINSTALL_APP_ERROR: "Error uninstalling 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", 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", FILE_DOES_NOT_EXIST: "File does not exist",
DIR_NOT_EXISTS: "Directory does not exist", DIR_NOT_EXISTS: "Directory does not exist",

View 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))
}

View File

@@ -186,7 +186,7 @@ func ReadFullFile(path string) []byte {
} }
// File copies a single file from src to dst // 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 err error
var srcfd *os.File var srcfd *os.File
var dstfd *os.File var dstfd *os.File
@@ -197,20 +197,55 @@ func CopyFile(src, dst string) error {
if !strings.HasSuffix(dst, "/") { if !strings.HasSuffix(dst, "/") {
dst += "/" dst += "/"
} }
dstPath := dst
dst += lastPath dst += lastPath
for i := 0; Exists(dst); i++ { if Exists(dst) {
name := strings.Split(lastPath, ".") if style == "skip" {
nameIndex := 0 return nil
if len(name) > 2 { } else {
nameIndex = len(name) - 2 os.Remove(dst)
} }
name[nameIndex] = name[nameIndex] + "(Copy)" }
dst = dstPath
for _, v := range name { if srcfd, err = os.Open(src); err != nil {
dst += v + "." 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 { if srcfd, err = os.Open(src); err != nil {
@@ -244,7 +279,7 @@ func GetNoDuplicateFileName(fullPath string) string {
} }
// Dir copies a whole directory recursively // 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 err error
var fds []os.FileInfo var fds []os.FileInfo
var srcinfo os.FileInfo var srcinfo os.FileInfo
@@ -253,16 +288,23 @@ func CopyDir(src string, dst string) error {
return err return err
} }
if !srcinfo.IsDir() { if !srcinfo.IsDir() {
if err = CopyFile(src, dst); err != nil { if err = CopyFile(src, dst, style); err != nil {
fmt.Println(err) fmt.Println(err)
} }
return nil return nil
} }
dstPath := dst //dstPath := dst
lastPath := src[strings.LastIndex(src, "/")+1:] lastPath := src[strings.LastIndex(src, "/")+1:]
dst += "/" + lastPath dst += "/" + lastPath
for i := 0; Exists(dst); i++ { // for i := 0; Exists(dst); i++ {
dst = dstPath + "/" + lastPath + strconv.Itoa(i+1) // 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 { if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
return err return err
@@ -275,11 +317,11 @@ func CopyDir(src string, dst string) error {
dstfp := dst //path.Join(dst, fd.Name()) dstfp := dst //path.Join(dst, fd.Name())
if fd.IsDir() { if fd.IsDir() {
if err = CopyDir(srcfp, dstfp); err != nil { if err = CopyDir(srcfp, dstfp, style); err != nil {
fmt.Println(err) fmt.Println(err)
} }
} else { } else {
if err = CopyFile(srcfp, dstfp); err != nil { if err = CopyFile(srcfp, dstfp, style); err != nil {
fmt.Println(err) fmt.Println(err)
} }
} }

View File

@@ -2,9 +2,13 @@ package file
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"io" "io"
"net/http"
"os" "os"
"path/filepath"
"strings"
"github.com/disintegration/imaging" "github.com/disintegration/imaging"
"github.com/dsoprea/go-exif/v3" "github.com/dsoprea/go-exif/v3"
@@ -82,3 +86,176 @@ func GetThumbnailByWebPhoto(path string, width, height int) ([]byte, error) {
imaging.Encode(&buf, img, f) imaging.Encode(&buf, img, f)
return buf.Bytes(), nil 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")
}

View File

@@ -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 package jwt
import ( import (
"time" "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 { type Claims struct {
UserName string `json:"username"` UserName string `json:"username"`
PassWord string `json:"password"` PassWord string `json:"password"`

View File

@@ -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 package jwt
import ( import (
@@ -5,36 +15,87 @@ import (
"net/http" "net/http"
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger" loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/gin-gonic/gin" "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) { return func(c *gin.Context) {
var code int var code int
code = oasis_err2.SUCCESS code = common_err.SUCCESS
token := c.GetHeader("Authorization") token := c.GetHeader("Authorization")
if len(token) == 0 { if len(token) == 0 {
token = c.Query("token") token = c.Query("token")
} }
if token == "" { if token == "" {
code = oasis_err2.INVALID_PARAMS code = common_err.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
//}
} }
if code != oasis_err2.SUCCESS { //claims, err := ParseToken(token)
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)}) _, 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() c.Abort()
return return
} }

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2022-06-02 15:09:38 * @Date: 2022-06-02 15:09:38
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-06-02 17:43:38 * @LastEditTime: 2022-06-27 15:47:49
* @FilePath: /CasaOS/pkg/utils/loger/log.go * @FilePath: /CasaOS/pkg/utils/loger/log.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -28,11 +28,11 @@ var loggers *zap.Logger
func getFileLogWriter() (writeSyncer zapcore.WriteSyncer) { func getFileLogWriter() (writeSyncer zapcore.WriteSyncer) {
// 使用 lumberjack 实现 log rotate // 使用 lumberjack 实现 log rotate
lumberJackLogger := &lumberjack.Logger{ lumberJackLogger := &lumberjack.Logger{
Filename: filepath.Join(config.AppInfo.LogSavePath, fmt.Sprintf("%s.%s", Filename: filepath.Join(config.AppInfo.LogPath, fmt.Sprintf("%s.%s",
config.AppInfo.LogSaveName, config.AppInfo.LogSaveName,
config.AppInfo.LogFileExt, config.AppInfo.LogFileExt,
)), )),
MaxSize: 100, MaxSize: 10,
MaxBackups: 60, MaxBackups: 60,
MaxAge: 1, MaxAge: 1,
Compress: true, Compress: true,
@@ -47,8 +47,8 @@ func LogInit() {
encoder := zapcore.NewJSONEncoder(encoderConfig) encoder := zapcore.NewJSONEncoder(encoderConfig)
fileWriteSyncer := getFileLogWriter() fileWriteSyncer := getFileLogWriter()
core := zapcore.NewTee( core := zapcore.NewTee(
zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel), zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.InfoLevel),
zapcore.NewCore(encoder, fileWriteSyncer, zapcore.DebugLevel), zapcore.NewCore(encoder, fileWriteSyncer, zapcore.InfoLevel),
) )
loggers = zap.New(core) loggers = zap.New(core)

View File

@@ -47,7 +47,7 @@ const (
//日志初始化 //日志初始化
func LogSetupOld() { func LogSetupOld() {
var err error var err error
filePath := fmt.Sprintf("%s", config.AppInfo.LogSavePath) filePath := fmt.Sprintf("%s", config.AppInfo.LogPath)
fileName := fmt.Sprintf("%s.%s", fileName := fmt.Sprintf("%s.%s",
config.AppInfo.LogSaveName, config.AppInfo.LogSaveName,
config.AppInfo.LogFileExt, config.AppInfo.LogFileExt,
@@ -61,7 +61,7 @@ func LogSetupOld() {
} }
func (o *oLog) Path() string { func (o *oLog) Path() string {
filePath := fmt.Sprintf("%s", config.AppInfo.LogSavePath) filePath := fmt.Sprintf("%s", config.AppInfo.LogPath)
fileName := fmt.Sprintf("%s.%s", fileName := fmt.Sprintf("%s.%s",
config.AppInfo.LogSaveName, config.AppInfo.LogSaveName,
config.AppInfo.LogFileExt, config.AppInfo.LogFileExt,

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-13 18:15:46 * @Date: 2022-05-13 18:15:46
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-06-02 17:41:47 * @LastEditTime: 2022-06-29 14:29:34
* @FilePath: /CasaOS/pkg/utils/version/version.go * @FilePath: /CasaOS/pkg/utils/version/version.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -11,24 +11,17 @@
package version package version
import ( import (
json2 "encoding/json"
"strconv" "strconv"
"strings" "strings"
"github.com/IceWhaleTech/CasaOS/model" "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/IceWhaleTech/CasaOS/types"
"github.com/tidwall/gjson"
) )
func IsNeedUpdate() (bool, model.Version) { func IsNeedUpdate(version model.Version) (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)
v1 := strings.Split(version.Version, ".") v1 := strings.Split(version.Version, ".")
v2 := strings.Split(types.CURRENTVERSION, ".") v2 := strings.Split(types.CURRENTVERSION, ".")
for len(v1) < len(v2) { for len(v1) < len(v2) {
@@ -40,31 +33,15 @@ func IsNeedUpdate() (bool, model.Version) {
for i := 0; i < len(v1); i++ { for i := 0; i < len(v1); i++ {
a, _ := strconv.Atoi(v1[i]) a, _ := strconv.Atoi(v1[i])
b, _ := strconv.Atoi(v2[i]) b, _ := strconv.Atoi(v2[i])
if i == 0 && a > b {
continue
}
if a > b { if a > b {
return true, version return true, version
} else { }
if a < b {
return false, version return false, version
} }
} }
return false, 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
}

View File

@@ -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)
}

View File

@@ -3,6 +3,7 @@ package route
import ( import (
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strconv" "strconv"
@@ -13,6 +14,7 @@ import (
"github.com/IceWhaleTech/CasaOS/model/system_app" "github.com/IceWhaleTech/CasaOS/model/system_app"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command" "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/env_helper"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/port" "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
@@ -23,14 +25,14 @@ import (
func InitFunction() { func InitFunction() {
go checkSystemApp() go checkSystemApp()
Update2_3() ShellInit()
CheckSerialDiskMount() CheckSerialDiskMount()
CheckToken2_11() CheckToken2_11()
ImportApplications() ImportApplications()
ChangeAPIUrl() ChangeAPIUrl()
InitSystemApplication()
MoveUserToDB()
} }
var syncIsExistence = false var syncIsExistence = false
@@ -80,7 +82,7 @@ func installSyncthing(appId string) {
appInfo.Tip = env_helper.ReplaceStringDefaultENV(appInfo.Tip) appInfo.Tip = env_helper.ReplaceStringDefaultENV(appInfo.Tip)
} }
appInfo.MaxMemory = service.MyService.System().GetMemInfo().Total >> 20 appInfo.MaxMemory = service.MyService.System().GetMemInfo()["total"].(uint64) >> 20
id := uuid.NewV4().String() id := uuid.NewV4().String()
@@ -103,9 +105,10 @@ func installSyncthing(appId string) {
m.Ports = appInfo.Ports m.Ports = appInfo.Ports
m.Restart = "always" m.Restart = "always"
m.Volumes = appInfo.Volumes m.Volumes = appInfo.Volumes
m.NetworkModel = appInfo.NetworkModel
m.Label = id m.Label = id
m.CustomId = 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 { if err != nil {
fmt.Println("container create error", err) fmt.Println("container create error", err)
// create container error // create container error
@@ -195,10 +198,14 @@ func CheckSerialDiskMount() {
} }
} }
service.MyService.Disk().RemoveLSBLKCache() 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() { func ShellInit() {
command.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/assist.sh") 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() { func CheckToken2_11() {
@@ -208,16 +215,7 @@ func CheckToken2_11() {
config.Cfg.Section("server").Key("Token").SetValue(token()) config.Cfg.Section("server").Key("Token").SetValue(token())
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) 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 sysType := runtime.GOOS
if len(config.FileSettingInfo.DownloadDir) == 0 { if len(config.FileSettingInfo.DownloadDir) == 0 {
downloadPath := "/DATA/Downloads" downloadPath := "/DATA/Downloads"
@@ -244,7 +242,7 @@ func CheckToken2_11() {
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) 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().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False") service.MyService.System().ExecUSBAutoMountShell("False")
} }
@@ -275,22 +273,23 @@ func ChangeAPIUrl() {
} }
// 0.3.1 //0.3.3
func InitSystemApplication() { //Transferring user data to the database
list := service.MyService.App().GetApplicationList() func MoveUserToDB() {
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)
application.Name = "CasaConnect" if len(config.UserInfo.UserName) > 0 && service.MyService.User().GetUserInfoByUserName(config.UserInfo.UserName).Id == 0 {
application.Icon = "/ui/img/CasaConnect.svg" user := model2.UserDBModel{}
application.Type = "system" user.UserName = config.UserInfo.UserName
application.Order = 0 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)
} }
} }

View File

@@ -1,8 +1,18 @@
/*
* @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 * @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-27 15:55:36 * @Date: 2022-05-27 15:55:36
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-05-27 18:57:40 * @LastEditTime: 2022-06-29 16:47:19
* @FilePath: /CasaOS/route/periodical.go * @FilePath: /CasaOS/route/periodical.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -29,7 +39,7 @@ func SendNetINfoBySocket() {
for _, netCardName := range nets { for _, netCardName := range nets {
if n.Name == netCardName { if n.Name == netCardName {
item := *(*model.IOCountersStat)(unsafe.Pointer(&n)) 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() item.Time = time.Now().Unix()
newNet = append(newNet, item) newNet = append(newNet, item)
break break
@@ -96,16 +106,16 @@ func SendDiskBySocket() {
findSystem += 1 findSystem += 1
continue 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) temp := service.MyService.Disk().SmartCTL(list[i].Path)
if reflect.DeepEqual(temp, model.SmartctlA{}) { if reflect.DeepEqual(temp, model.SmartctlA{}) {
continue healthy = true
} else {
healthy = temp.SmartStatus.Passed
} }
//list[i].Temperature = temp.Temperature.Current //list[i].Temperature = temp.Temperature.Current
if !temp.SmartStatus.Passed {
healthy = false
}
if len(list[i].Children) > 0 { if len(list[i].Children) > 0 {
for _, v := range list[i].Children { for _, v := range list[i].Children {
s, _ := strconv.ParseUint(v.FSSize, 10, 64) s, _ := strconv.ParseUint(v.FSSize, 10, 64)
@@ -153,3 +163,123 @@ func SendUSBBySocket() {
} }
service.MyService.Notify().SendUSBInfoBySocket(usb) 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)
}

View File

@@ -8,11 +8,11 @@ import (
jwt2 "github.com/IceWhaleTech/CasaOS/pkg/utils/jwt" jwt2 "github.com/IceWhaleTech/CasaOS/pkg/utils/jwt"
v1 "github.com/IceWhaleTech/CasaOS/route/v1" v1 "github.com/IceWhaleTech/CasaOS/route/v1"
"github.com/IceWhaleTech/CasaOS/web" "github.com/IceWhaleTech/CasaOS/web"
"github.com/gin-contrib/gzip" "github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
var swagHandler gin.HandlerFunc
var OnlineDemo bool = false var OnlineDemo bool = false
func InitRouter() *gin.Engine { func InitRouter() *gin.Engine {
@@ -20,50 +20,66 @@ func InitRouter() *gin.Engine {
r := gin.Default() r := gin.Default()
r.Use(middleware.Cors()) r.Use(middleware.Cors())
r.Use(middleware.WriteLog())
r.Use(gzip.Gzip(gzip.DefaultCompression)) r.Use(gzip.Gzip(gzip.DefaultCompression))
gin.SetMode(config.ServerInfo.RunMode) gin.SetMode(config.ServerInfo.RunMode)
r.StaticFS("/ui", http.FS(web.Static)) r.StaticFS("/ui", http.FS(web.Static))
r.GET("/", WebUIHome) r.GET("/", WebUIHome)
// r.StaticFS("/assets", http.Dir("./static/assets"))
// r.StaticFile("/favicon.ico", "./static/favicon.ico")
//r.GET("/", func(c *gin.Context) { //r.GET("/", func(c *gin.Context) {
// c.Redirect(http.StatusMovedPermanently, "ui/") // 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/guide/check", v1.GetGuideCheck)
r.GET("/v1/debug", v1.GetSystemConfigDebug) r.GET("/v1/debug", v1.GetSystemConfigDebug)
//set user
r.POST("/v1/user/setusernamepwd", v1.Set_Name_Pwd) r.POST("/v1/user/setusernamepwd", v1.Set_Name_Pwd)
//get user info r.GET("/v1/user/info/:id", v1.GetUserInfo)
r.GET("/v1/user/info", v1.GetUserInfo) r.GET("/v1/user/avatar/:id", v1.GetUserAvatar)
r.GET("/v1/user/image", v1.GetUserImage)
//get user info //get user info
r.GET("/v1/person/shareid", v1.GetPersonShareId) r.GET("/v1/person/shareid", v1.GetPersonShareId)
r.GET("/v1/sys/socket/port", v1.GetSystemSocketPort) r.GET("/v1/sys/socket/port", v1.GetSystemSocketPort)
//r.POST("/v1/user/refresh/token", v1.PostUserRefreshToken)
v1Group := r.Group("/v1") v1Group := r.Group("/v1")
v1Group.Use(jwt2.JWT(swagHandler)) v1Group.Use(jwt2.JWT())
{ {
v1UserGroup := v1Group.Group("/user") v1UserGroup := v1Group.Group("/user")
v1UserGroup.Use() v1UserGroup.Use()
{ {
//chang head //****************** New version needs to be modified start ******************
v1UserGroup.POST("/head", v1.PostUserHead)
//chang user name //chang user name
v1UserGroup.PUT("/username", v1.PutUserName) v1UserGroup.PUT("/username", v1.PutUserName)
//chang pwd
v1UserGroup.PUT("/password", v1.PutUserPwd) v1UserGroup.PUT("/password", v1.PutUserPwd)
//edit user info v1UserGroup.PUT("/nick", v1.PutUserNick)
v1UserGroup.POST("/info", v1.PostUserChangeInfo) v1UserGroup.PUT("/desc", v1.PutUserDesc)
v1UserGroup.PUT("/nick", v1.PutUserChangeNick) v1UserGroup.GET("/info", v1.GetUserInfoByUserName)
v1UserGroup.PUT("/desc", v1.PutUserChangeDesc) v1UserGroup.GET("/custom/:id/:key", v1.GetUserCustomConf)
v1UserGroup.POST("/person/info", v1.PostUserPersonInfo) 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) v1UserGroup.GET("/shareid", v1.GetUserShareID)
//****************** soon to be removed end ******************
//v1UserGroup.GET("/info", v1.GetUserInfo)
v1UserGroup.PUT("/avatar", v1.PutUserAvatar)
v1UserGroup.GET("/avatar", v1.GetUserAvatar)
v1UserGroup.DELETE("/delete/:id", v1.DeleteUser)
} }
v1AppGroup := v1Group.Group("/app") v1AppGroup := v1Group.Group("/app")
@@ -81,12 +97,10 @@ func InitRouter() *gin.Engine {
v1AppGroup.GET("/port", v1.GetPort) v1AppGroup.GET("/port", v1.GetPort)
//检查端口 //检查端口
v1AppGroup.GET("/check/:port", v1.PortCheck) v1AppGroup.GET("/check/:port", v1.PortCheck)
//分类
v1AppGroup.GET("/category", v1.CategoryList) v1AppGroup.GET("/category", v1.CategoryList)
//容器相关
v1AppGroup.GET("/terminal/:id", v1.DockerTerminal) v1AppGroup.GET("/terminal/:id", v1.DockerTerminal)
v1AppGroup.GET("/order", v1.GetAppOrder)
v1AppGroup.POST("/order", v1.PostAppOrder)
//app容器详情 //app容器详情
v1AppGroup.GET("/info/:id", v1.ContainerInfo) v1AppGroup.GET("/info/:id", v1.ContainerInfo)
//app容器日志 //app容器日志
@@ -112,27 +126,25 @@ func InitRouter() *gin.Engine {
v1SysGroup := v1Group.Group("/sys") v1SysGroup := v1Group.Group("/sys")
v1SysGroup.Use() v1SysGroup.Use()
{ {
v1SysGroup.GET("/check", v1.CheckVersion) v1SysGroup.GET("/version/check", v1.GetSystemCheckVersion)
v1SysGroup.GET("/hardware/info", v1.GetSystemHardwareInfo) v1SysGroup.GET("/hardware/info", v1.GetSystemHardwareInfo)
v1SysGroup.POST("/update", v1.SystemUpdate) v1SysGroup.POST("/update", v1.SystemUpdate)
v1SysGroup.GET("/wsssh", v1.WsSsh) v1SysGroup.GET("/wsssh", v1.WsSsh)
v1SysGroup.GET("/config", v1.GetSystemConfig) v1SysGroup.GET("/config", v1.GetSystemConfig)
//v1SysGroup.POST("/config", v1.PostSetSystemConfig)
v1SysGroup.GET("/error/logs", v1.GetCasaOSErrorLogs) v1SysGroup.GET("/error/logs", v1.GetCasaOSErrorLogs)
v1SysGroup.POST("/config", v1.PostSetSystemConfig)
v1SysGroup.GET("/widget/config", v1.GetWidgetConfig) v1SysGroup.GET("/widget/config", v1.GetWidgetConfig)
v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig) v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig)
v1SysGroup.GET("/port", v1.GetCasaOSPort) v1SysGroup.GET("/port", v1.GetCasaOSPort)
v1SysGroup.PUT("/port", v1.PutCasaOSPort) v1SysGroup.PUT("/port", v1.PutCasaOSPort)
v1SysGroup.POST("/kill", v1.PostKillCasaOS) v1SysGroup.POST("/stop", v1.PostKillCasaOS)
v1SysGroup.GET("/info", v1.Info) v1SysGroup.GET("/utilization", v1.GetSystemUtilization)
v1SysGroup.PUT("/usb/off", v1.PutSystemOffUSBAutoMount) v1SysGroup.PUT("/usb/:status", v1.PutSystemUSBAutoMount)
v1SysGroup.PUT("/usb/on", v1.PutSystemOnUSBAutoMount) v1SysGroup.GET("/usb/status", v1.GetSystemUSBAutoMount)
v1SysGroup.GET("/usb", v1.GetSystemUSBAutoMount) v1SysGroup.GET("/cpu", v1.GetSystemCupInfo)
v1SysGroup.GET("/cpu", v1.CupInfo) v1SysGroup.GET("/mem", v1.GetSystemMemInfo)
v1SysGroup.GET("/mem", v1.MemInfo) v1SysGroup.GET("/disk", v1.GetSystemDiskInfo)
v1SysGroup.GET("/disk", v1.DiskInfo) v1SysGroup.GET("/network", v1.GetSystemNetInfo)
v1SysGroup.GET("/network", v1.NetInfo)
} }
v1FileGroup := v1Group.Group("/file") v1FileGroup := v1Group.Group("/file")
v1FileGroup.Use() v1FileGroup.Use()
@@ -153,7 +165,6 @@ func InitRouter() *gin.Engine {
v1FileGroup.PUT("/update", v1.PutFileContent) v1FileGroup.PUT("/update", v1.PutFileContent)
v1FileGroup.GET("/image", v1.GetFileImage) v1FileGroup.GET("/image", v1.GetFileImage)
v1FileGroup.DELETE("/operate/:id", v1.DeleteOperateFileOrDir) v1FileGroup.DELETE("/operate/:id", v1.DeleteOperateFileOrDir)
//v1FileGroup.GET("/download", v1.UserFileDownloadCommonService) //v1FileGroup.GET("/download", v1.UserFileDownloadCommonService)
} }
v1DiskGroup := v1Group.Group("/disk") v1DiskGroup := v1Group.Group("/disk")
@@ -167,10 +178,10 @@ func InitRouter() *gin.Engine {
v1DiskGroup.GET("/info", v1.GetDiskInfo) v1DiskGroup.GET("/info", v1.GetDiskInfo)
//format storage //format storage
v1DiskGroup.POST("/format", v1.FormatDisk) v1DiskGroup.POST("/format", v1.PostDiskFormat)
// add storage // add storage
v1DiskGroup.POST("/storage", v1.AddPartition) v1DiskGroup.POST("/storage", v1.PostDiskAddPartition)
//mount SATA disk //mount SATA disk
v1DiskGroup.POST("/mount", v1.PostMountDisk) v1DiskGroup.POST("/mount", v1.PostMountDisk)
@@ -186,24 +197,6 @@ func InitRouter() *gin.Engine {
v1DiskGroup.GET("/usb", v1.GetUSBList) 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)
}
v1PersonGroup := v1Group.Group("/person") v1PersonGroup := v1Group.Group("/person")
v1PersonGroup.Use() v1PersonGroup.Use()
{ {
@@ -230,14 +223,7 @@ func InitRouter() *gin.Engine {
v1PersonGroup.GET("/image/thumbnail/:shareid", v1.GetPersonImageThumbnail) 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.GET("/sync/config", v1.GetSyncConfig)
v1Group.Any("/syncthing/*url", v1.SyncToSyncthing)
} }
return r return r
} }

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2022-05-23 17:18:56 * @Date: 2022-05-23 17:18:56
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-06-08 16:31:24 * @LastEditTime: 2022-06-09 21:48:10
* @FilePath: /CasaOS/route/socket.go * @FilePath: /CasaOS/route/socket.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -49,7 +49,7 @@ func SocketInit(msg chan notify.Message) {
go func(msg chan notify.Message) { go func(msg chan notify.Message) {
for v := range msg { for v := range msg {
f.Broadcast("", v.Path, &v.Msg) f.Broadcast("", v.Path, &v.Msg)
time.Sleep(time.Millisecond * 300) time.Sleep(time.Millisecond * 100)
} }
}(msg) }(msg)

View File

@@ -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 package route
import ( import (
"html/template"
"github.com/IceWhaleTech/CasaOS/web" "github.com/IceWhaleTech/CasaOS/web"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"html/template"
) )
func WebUIHome(c *gin.Context) { func WebUIHome(c *gin.Context) {

View File

@@ -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)})
}

View File

@@ -7,8 +7,9 @@ import (
"strconv" "strconv"
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file" "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" port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -35,8 +36,11 @@ func AppList(c *gin.Context) {
t := c.DefaultQuery("type", "rank") t := c.DefaultQuery("type", "rank")
categoryId := c.DefaultQuery("category_id", "0") categoryId := c.DefaultQuery("category_id", "0")
key := c.DefaultQuery("key", "") key := c.DefaultQuery("key", "")
language := c.GetHeader("Language") if len(index) == 0 || len(size) == 0 || len(t) == 0 || len(categoryId) == 0 {
recommend, list, community := service.MyService.Casa().GetServerList(index, size, t, categoryId, key, language) 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++ { // for i := 0; i < len(recommend); i++ {
// ct, _ := service.MyService.Docker().DockerListByImage(recommend[i].Image, recommend[i].ImageVersion) // ct, _ := service.MyService.Docker().DockerListByImage(recommend[i].Image, recommend[i].ImageVersion)
// if ct != nil { // if ct != nil {
@@ -56,11 +60,11 @@ func AppList(c *gin.Context) {
// } // }
// } // }
data := make(map[string]interface{}, 3) data := make(map[string]interface{}, 3)
data["recommend"] = recommend data["recommend"] = collection.Recommend
data["list"] = list data["list"] = collection.List
data["community"] = community 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 获取一个可用端口 // @Summary 获取一个可用端口
@@ -79,7 +83,7 @@ func GetPort(c *gin.Context) {
p, _ = port2.GetAvailablePort(t) p, _ = port2.GetAvailablePort(t)
ok = !port2.IsPortAvailable(p, 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 检查端口是否可用 // @Summary 检查端口是否可用
@@ -94,7 +98,7 @@ func GetPort(c *gin.Context) {
func PortCheck(c *gin.Context) { func PortCheck(c *gin.Context) {
p, _ := strconv.Atoi(c.Param("port")) p, _ := strconv.Atoi(c.Param("port"))
t := c.DefaultQuery("type", "tcp") 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 我的应用列表 // @Summary 我的应用列表
@@ -112,12 +116,11 @@ func MyAppList(c *gin.Context) {
size, _ := strconv.Atoi(c.DefaultQuery("size", "0")) size, _ := strconv.Atoi(c.DefaultQuery("size", "0"))
position, _ := strconv.ParseBool(c.DefaultQuery("position", "true")) position, _ := strconv.ParseBool(c.DefaultQuery("position", "true"))
list, unTranslation := service.MyService.App().GetMyList(index, size, position) list, unTranslation := service.MyService.App().GetMyList(index, size, position)
data := make(map[string]interface{}, 2) data := make(map[string]interface{}, 2)
data["list"] = list data["list"] = list
data["local"] = unTranslation 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 // @Summary my app hardware usage list
@@ -129,7 +132,7 @@ func MyAppList(c *gin.Context) {
// @Router /app/usage [get] // @Router /app/usage [get]
func AppUsageList(c *gin.Context) { func AppUsageList(c *gin.Context) {
list := service.MyService.App().GetHardwareUsage() 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 应用详情 // @Summary 应用详情
@@ -209,9 +212,9 @@ func AppInfo(c *gin.Context) {
// sort.VolSort(volOrder).Sort(info.Volumes.([]model.PathMap)) // sort.VolSort(volOrder).Sort(info.Volumes.([]model.PathMap))
// sort.DevSort(devOrder).Sort(info.Devices) // sort.DevSort(devOrder).Sort(info.Devices)
info.MaxMemory = service.MyService.System().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 获取远程分类列表 // @Summary 获取远程分类列表
@@ -228,10 +231,10 @@ func CategoryList(c *gin.Context) {
count += category.Count count += category.Count
} }
rear := append([]model.ServerCategoryList{}, list[0:]...) rear := append([]model.CategoryList{}, list[0:]...)
list = append(list[:0], model.ServerCategoryList{Count: count, Name: "All", Font: "apps"}) list = append(list[:0], model.CategoryList{Count: count, Name: "All", Font: "apps"})
list = append(list, rear...) 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 分享该应用配置 // @Summary 分享该应用配置

View File

@@ -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})
}

View File

@@ -10,8 +10,8 @@ import (
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "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/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model" model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -111,7 +111,7 @@ func GetDiskList(c *gin.Context) {
continue 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) temp := service.MyService.Disk().SmartCTL(list[i].Path)
if reflect.DeepEqual(temp, model.SmartctlA{}) { if reflect.DeepEqual(temp, model.SmartctlA{}) {
temp.SmartStatus.Passed = true temp.SmartStatus.Passed = true
@@ -154,7 +154,7 @@ func GetDiskList(c *gin.Context) {
data["storage"] = storage data["storage"] = storage
data["avail"] = avail 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 // @Summary get disk list
@@ -171,7 +171,7 @@ func GetPlugInDisks(c *gin.Context) {
for _, item := range list { for _, item := range list {
result = append(result, service.MyService.Disk().GetDiskInfoByPath(item.Path)) 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 // @Summary disk detail
@@ -185,10 +185,10 @@ func GetPlugInDisks(c *gin.Context) {
func GetDiskInfo(c *gin.Context) { func GetDiskInfo(c *gin.Context) {
path := c.Query("path") path := c.Query("path")
if len(path) == 0 { 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) 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 // @Summary format storage
@@ -201,37 +201,37 @@ func GetDiskInfo(c *gin.Context) {
// @Param volume formData string true "mount point" // @Param volume formData string true "mount point"
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /disk/format [post] // @Router /disk/format [post]
func FormatDisk(c *gin.Context) { func PostDiskFormat(c *gin.Context) {
path := c.PostForm("path") path := c.PostForm("path")
t := "ext4" t := "ext4"
pwd := c.PostForm("pwd") pwd := c.PostForm("pwd")
volume := c.PostForm("volume") volume := c.PostForm("volume")
if pwd != config.UserInfo.PWD { 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 return
} }
if len(path) == 0 || len(t) == 0 { 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 return
} }
if _, ok := diskMap[path]; ok { 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 return
} }
diskMap[path] = "busying" diskMap[path] = "busying"
service.MyService.Disk().UmountPointAndRemoveDir(path) service.MyService.Disk().UmountPointAndRemoveDir(path)
format := service.MyService.Disk().FormatDisk(path, t) format := service.MyService.Disk().FormatDisk(path, t)
if len(format) == 0 { 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) delete(diskMap, path)
return return
} }
service.MyService.Disk().MountDisk(path, volume) service.MyService.Disk().MountDisk(path, volume)
service.MyService.Disk().RemoveLSBLKCache() service.MyService.Disk().RemoveLSBLKCache()
delete(diskMap, path) 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 获取支持的格式 // @Summary 获取支持的格式
@@ -243,7 +243,7 @@ func FormatDisk(c *gin.Context) {
// @Router /disk/type [get] // @Router /disk/type [get]
func FormatDiskType(c *gin.Context) { func FormatDiskType(c *gin.Context) {
var strArr = [4]string{"fat32", "ntfs", "ext4", "exfat"} 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") path := c.PostForm("path")
if len(path) == 0 { 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 p = path[:len(path)-1]
var n = path[len(path)-1:] var n = path[len(path)-1:]
service.MyService.Disk().DelPartition(p, n) 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 // @Summary add storage
@@ -278,28 +278,30 @@ func RemovePartition(c *gin.Context) {
// @Param format formData bool true "need format(true)" // @Param format formData bool true "need format(true)"
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /disk/storage [post] // @Router /disk/storage [post]
func AddPartition(c *gin.Context) { func PostDiskAddPartition(c *gin.Context) {
name := c.PostForm("name") name := c.PostForm("name")
path := c.PostForm("path") path := c.PostForm("path")
format, _ := strconv.ParseBool(c.PostForm("format")) format, _ := strconv.ParseBool(c.PostForm("format"))
if len(name) == 0 || len(path) == 0 { 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 return
} }
if _, ok := diskMap[path]; ok { 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 return
} }
if !file.CheckNotExist("/DATA/" + name) { if !file.CheckNotExist("/DATA/" + name) {
// /mnt/name exist // /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 return
} }
diskMap[path] = "busying" diskMap[path] = "busying"
currentDisk := service.MyService.Disk().GetDiskInfo(path) currentDisk := service.MyService.Disk().GetDiskInfo(path)
if !format { if !format {
if len(currentDisk.Children) != 1 || !(len(currentDisk.Children) > 0 && currentDisk.Children[0].FsType == "ext4") { 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) delete(diskMap, path)
return return
} }
@@ -319,7 +321,7 @@ func AddPartition(c *gin.Context) {
} }
currentDisk = service.MyService.Disk().GetDiskInfo(path) currentDisk = service.MyService.Disk().GetDiskInfo(path)
if len(currentDisk.Children) != 1 { 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 return
} }
@@ -338,7 +340,7 @@ func AddPartition(c *gin.Context) {
service.MyService.Disk().RemoveLSBLKCache() service.MyService.Disk().RemoveLSBLKCache()
delete(diskMap, path) 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 // @Summary add mount point
@@ -378,7 +380,7 @@ func PostMountDisk(c *gin.Context) {
m.UUID = serial m.UUID = serial
m.State = 0 m.State = 0
//service.MyService.Disk().SaveMountPoint(m) //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 // @Summary remove mount point
@@ -398,16 +400,16 @@ func PostDiskUmount(c *gin.Context) {
pwd := c.PostForm("pwd") pwd := c.PostForm("pwd")
if len(path) == 0 || len(mountPoint) == 0 { 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 return
} }
if pwd != config.UserInfo.PWD { 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 return
} }
if _, ok := diskMap[path]; ok { 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 return
} }
@@ -415,7 +417,7 @@ func PostDiskUmount(c *gin.Context) {
//delete data //delete data
service.MyService.Disk().DeleteMountPoint(path, mountPoint) service.MyService.Disk().DeleteMountPoint(path, mountPoint)
service.MyService.Disk().RemoveLSBLKCache() 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 // @Summary confirm delete disk
@@ -429,7 +431,7 @@ func PostDiskUmount(c *gin.Context) {
func DeleteDisk(c *gin.Context) { func DeleteDisk(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
service.MyService.Disk().DeleteMount(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 // @Summary check mount point
@@ -453,12 +455,12 @@ func GetDiskCheck(c *gin.Context) {
for _, v := range dbList { for _, v := range dbList {
if _, ok := mapList[v.UUID]; !ok { if _, ok := mapList[v.UUID]; !ok {
//disk undefind //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 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 // @Summary check mount point
@@ -493,5 +495,5 @@ func GetUSBList(c *gin.Context) {
data = append(data, temp) 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})
} }

View File

@@ -2,7 +2,6 @@ package v1
import ( import (
"bytes" "bytes"
"encoding/json"
json2 "encoding/json" json2 "encoding/json"
"net/http" "net/http"
"path/filepath" "path/filepath"
@@ -14,11 +13,8 @@ import (
"github.com/IceWhaleTech/CasaOS/model/notify" "github.com/IceWhaleTech/CasaOS/model/notify"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/docker" "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" "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" port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
"github.com/IceWhaleTech/CasaOS/pkg/utils/random" "github.com/IceWhaleTech/CasaOS/pkg/utils/random"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
@@ -45,14 +41,14 @@ func DockerTerminal(c *gin.Context) {
row := c.DefaultQuery("rows", "30") row := c.DefaultQuery("rows", "30")
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != 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 return
} }
defer conn.Close() defer conn.Close()
container := c.Param("id") container := c.Param("id")
hr, err := service.Exec(container, row, col) hr, err := service.Exec(container, row, col)
if err != 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 return
} }
// 关闭I/O流 // 关闭I/O流
@@ -118,7 +114,7 @@ func WsSsh(c *gin.Context) {
func SpeedPush(c *gin.Context) { func SpeedPush(c *gin.Context) {
//token := c.Query("token") //token := c.Query("token")
//if len(token) == 0 || token != config.UserInfo.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 // return
//} //}
@@ -170,7 +166,7 @@ func InstallApp(c *gin.Context) {
} }
} else { } else {
if _, err := service.MyService.Docker().DockerListByName(m.Label); err == nil { 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 return
} }
@@ -178,10 +174,10 @@ func InstallApp(c *gin.Context) {
//check port //check port
if len(m.PortMap) > 0 && m.PortMap != "0" { 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) portMap, _ := strconv.Atoi(m.PortMap)
if !port2.IsPortAvailable(portMap, "tcp") { 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 return
} }
} }
@@ -203,34 +199,33 @@ func InstallApp(c *gin.Context) {
if u.Protocol == "udp" { if u.Protocol == "udp" {
t, _ := strconv.Atoi(u.CommendPort) t, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(t, "udp") { 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 return
} }
} else if u.Protocol == "tcp" { } else if u.Protocol == "tcp" {
te, _ := strconv.Atoi(u.CommendPort) te, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(te, "tcp") { 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 return
} }
} else if u.Protocol == "both" { } else if u.Protocol == "both" {
t, _ := strconv.Atoi(u.CommendPort) t, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(t, "udp") { 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 return
} }
te, _ := strconv.Atoi(u.CommendPort) te, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(te, "tcp") { 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 return
} }
} }
} }
if m.Origin == "custom" { if m.Origin == "custom" {
for _, device := range m.Devices { for _, device := range m.Devices {
if file.CheckNotExist(device.Path) { 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 return
} }
@@ -327,7 +322,7 @@ func InstallApp(c *gin.Context) {
time.Sleep(time.Second) time.Sleep(time.Second)
} }
_, err = service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m, appInfo.NetworkModel) _, err = service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m)
if err != nil { if err != nil {
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":80}", 100) //service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":80}", 100)
notify := notify.Application{} notify := notify.Application{}
@@ -376,53 +371,6 @@ func InstallApp(c *gin.Context) {
// service.MyService.Notify().UpdateLog(installLog) // service.MyService.Notify().UpdateLog(installLog)
} }
if m.Origin != CUSTOM {
//step:enable 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)
// }
}
}
//step: 启动成功 检查容器状态确认启动成功 //step: 启动成功 检查容器状态确认启动成功
container, err := service.MyService.Docker().DockerContainerInfo(m.Label) container, err := service.MyService.Docker().DockerContainerInfo(m.Label)
if err != nil && container.ContainerJSONBase.State.Running { if err != nil && container.ContainerJSONBase.State.Running {
@@ -457,7 +405,7 @@ func InstallApp(c *gin.Context) {
}() }()
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})
} }
@@ -481,7 +429,7 @@ func InstallApp(c *gin.Context) {
// c.BindJSON(&m) // c.BindJSON(&m)
// //检查端口 // //检查端口
// if len(m.PortMap) == 0 || m.PortMap == "0" { // 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 // return
// } // }
// if len(m.Port) == 0 || m.Port == "0" { // if len(m.Port) == 0 || m.Port == "0" {
@@ -490,14 +438,14 @@ func InstallApp(c *gin.Context) {
// //
// portMap, _ := strconv.Atoi(m.PortMap) // portMap, _ := strconv.Atoi(m.PortMap)
// if !port2.IsPortAvailable(portMap, "tcp") { // 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 // return
// } // }
// //
// for _, u := range m.Udp { // for _, u := range m.Udp {
// t, _ := strconv.Atoi(u.CommendPort) // t, _ := strconv.Atoi(u.CommendPort)
// if !port2.IsPortAvailable(t, "udp") { // 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 // return
// } // }
// } // }
@@ -505,7 +453,7 @@ func InstallApp(c *gin.Context) {
// for _, t := range m.Tcp { // for _, t := range m.Tcp {
// te, _ := strconv.Atoi(t.CommendPort) // te, _ := strconv.Atoi(t.CommendPort)
// if !port2.IsPortAvailable(te, "tcp") { // 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 // return
// } // }
// } // }
@@ -522,7 +470,7 @@ func InstallApp(c *gin.Context) {
// //
// err := service.MyService.Docker().DockerPullImage(m.Image) // err := service.MyService.Docker().DockerPullImage(m.Image)
// if err != nil { // 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() // id := uuid.NewV4().String()
@@ -639,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})
// //
//} //}
@@ -655,27 +603,27 @@ func UnInstallApp(c *gin.Context) {
appId := c.Param("id") appId := c.Param("id")
if len(appId) == 0 { 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 return
} }
//info := service.MyService.App().GetUninstallInfo(appId) //info := service.MyService.App().GetUninstallInfo(appId)
info, err := service.MyService.Docker().DockerContainerInfo(appId) info, err := service.MyService.Docker().DockerContainerInfo(appId)
if err != 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 return
} }
//step停止容器 //step停止容器
err = service.MyService.Docker().DockerContainerStop(appId) err = service.MyService.Docker().DockerContainerStop(appId)
if err != nil { 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 return
} }
err = service.MyService.Docker().DockerContainerRemove(appId, false) err = service.MyService.Docker().DockerContainerRemove(appId, false)
if err != nil { 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 return
} }
@@ -740,7 +688,7 @@ func UnInstallApp(c *gin.Context) {
notify.Success = true notify.Success = true
notify.Finished = true notify.Finished = true
service.MyService.Notify().SendUninstallAppBySocket(notify) service.MyService.Notify().SendUninstallAppBySocket(notify)
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)})
} }
@@ -766,15 +714,15 @@ func ChangAppState(c *gin.Context) {
err = service.MyService.Docker().DockerContainerStart(appId) err = service.MyService.Docker().DockerContainerStart(appId)
} }
if err != 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 return
} }
info, err := service.MyService.App().GetContainerInfo(appId) info, err := service.MyService.App().GetContainerInfo(appId)
if err != 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 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 查看容器日志 // @Summary 查看容器日志
@@ -788,7 +736,7 @@ func ChangAppState(c *gin.Context) {
func ContainerLog(c *gin.Context) { func ContainerLog(c *gin.Context) {
appId := c.Param("id") appId := c.Param("id")
log, _ := service.MyService.Docker().DockerContainerLog(appId) 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}) c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: log})
} }
// @Summary 获取容器状态 // @Summary 获取容器状态
@@ -805,7 +753,7 @@ func GetContainerState(c *gin.Context) {
t := c.DefaultQuery("type", "0") t := c.DefaultQuery("type", "0")
containerInfo, e := service.MyService.App().GetSimpleContainerInfo(id) containerInfo, e := service.MyService.App().GetSimpleContainerInfo(id)
if e != nil { 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 return
} }
@@ -818,7 +766,7 @@ func GetContainerState(c *gin.Context) {
data["app"] = appInfo 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 更新设置 // @Summary 更新设置
@@ -841,7 +789,7 @@ func UpdateSetting(c *gin.Context) {
c.BindJSON(&m) c.BindJSON(&m)
if len(id) == 0 { 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 return
} }
//var cpd model.CustomizationPostData //var cpd model.CustomizationPostData
@@ -853,7 +801,7 @@ func UpdateSetting(c *gin.Context) {
// //check app name is exist // //check app name is exist
// if _, err := service.MyService.Docker().DockerListByName(m.Label); err == nil { // 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 // return
// } // }
@@ -861,7 +809,7 @@ func UpdateSetting(c *gin.Context) {
portMap, _ := strconv.Atoi(m.PortMap) portMap, _ := strconv.Atoi(m.PortMap)
if !port2.IsPortAvailable(portMap, "tcp") { if !port2.IsPortAvailable(portMap, "tcp") {
service.MyService.Docker().DockerContainerStart(id) 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 return
} }
@@ -871,28 +819,28 @@ func UpdateSetting(c *gin.Context) {
t, _ := strconv.Atoi(u.CommendPort) t, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(t, "udp") { if !port2.IsPortAvailable(t, "udp") {
service.MyService.Docker().DockerContainerStart(id) 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 return
} }
} else if u.Protocol == "tcp" { } else if u.Protocol == "tcp" {
te, _ := strconv.Atoi(u.CommendPort) te, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(te, "tcp") { if !port2.IsPortAvailable(te, "tcp") {
service.MyService.Docker().DockerContainerStart(id) 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 return
} }
} else if u.Protocol == "both" { } else if u.Protocol == "both" {
t, _ := strconv.Atoi(u.CommendPort) t, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(t, "udp") { if !port2.IsPortAvailable(t, "udp") {
service.MyService.Docker().DockerContainerStart(id) 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 return
} }
te, _ := strconv.Atoi(u.CommendPort) te, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(te, "tcp") { if !port2.IsPortAvailable(te, "tcp") {
service.MyService.Docker().DockerContainerStart(id) 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 return
} }
} }
@@ -901,11 +849,11 @@ func UpdateSetting(c *gin.Context) {
service.MyService.Docker().DockerContainerUpdateName(id, id) service.MyService.Docker().DockerContainerUpdateName(id, id)
//service.MyService.Docker().DockerContainerRemove(id, true) //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 { if err != nil {
service.MyService.Docker().DockerContainerUpdateName(m.Label, id) service.MyService.Docker().DockerContainerUpdateName(m.Label, id)
service.MyService.Docker().DockerContainerStart(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 return
} }
// echo -e "hellow\nworld" >> // echo -e "hellow\nworld" >>
@@ -914,7 +862,7 @@ func UpdateSetting(c *gin.Context) {
err = service.MyService.Docker().DockerContainerStart(containerId) err = service.MyService.Docker().DockerContainerStart(containerId)
if err != nil { 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 return
} }
service.MyService.Docker().DockerContainerRemove(id, true) service.MyService.Docker().DockerContainerRemove(id, true)
@@ -985,7 +933,7 @@ func UpdateSetting(c *gin.Context) {
//service.MyService.App().UpdateApp(appInfo) //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 // @Summary update app version
@@ -1000,20 +948,20 @@ func PutAppUpdate(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
if len(id) == 0 { 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 return
} }
inspect, err := service.MyService.Docker().DockerContainerInfo(id) inspect, err := service.MyService.Docker().DockerContainerInfo(id)
if err != 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 return
} }
imageLatest := strings.Split(inspect.Config.Image, ":")[0] + ":latest" imageLatest := strings.Split(inspect.Config.Image, ":")[0] + ":latest"
err = service.MyService.Docker().DockerPullImage(imageLatest, "", "") err = service.MyService.Docker().DockerPullImage(imageLatest, "", "")
if err != 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 return
} }
@@ -1026,7 +974,7 @@ func PutAppUpdate(c *gin.Context) {
if err != nil { if err != nil {
service.MyService.Docker().DockerContainerUpdateName(inspect.Name, id) service.MyService.Docker().DockerContainerUpdateName(inspect.Name, id)
service.MyService.Docker().DockerContainerStart(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 return
} }
@@ -1034,43 +982,13 @@ func PutAppUpdate(c *gin.Context) {
err = service.MyService.Docker().DockerContainerStart(containerId) err = service.MyService.Docker().DockerContainerStart(containerId)
if err != nil { 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 return
} }
service.MyService.Docker().DockerContainerRemove(id, true) service.MyService.Docker().DockerContainerRemove(id, true)
delete(service.NewVersionApp, id) delete(service.NewVersionApp, 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 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),
})
} }
// @Summary 获取容器详情 // @Summary 获取容器详情
@@ -1086,7 +1004,7 @@ func ContainerInfo(c *gin.Context) {
appInfo := service.MyService.App().GetAppDBInfo(appId) appInfo := service.MyService.App().GetAppDBInfo(appId)
containerInfo, _ := service.MyService.Docker().DockerContainerStats(appId) containerInfo, _ := service.MyService.Docker().DockerContainerStats(appId)
var cpuModel = "arm" 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 { if strings.Count(strings.ToLower(strings.TrimSpace(cpu[0].ModelName)), "intel") > 0 {
cpuModel = "intel" cpuModel = "intel"
} else if strings.Count(strings.ToLower(strings.TrimSpace(cpu[0].ModelName)), "amd") > 0 { } else if strings.Count(strings.ToLower(strings.TrimSpace(cpu[0].ModelName)), "amd") > 0 {
@@ -1097,7 +1015,7 @@ func ContainerInfo(c *gin.Context) {
info, err := service.MyService.Docker().DockerContainerInfo(appId) info, err := service.MyService.Docker().DockerContainerInfo(appId)
if err != nil { if err != nil {
//todo 需要自定义错误 //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 return
} }
con := struct { con := struct {
@@ -1110,10 +1028,10 @@ func ContainerInfo(c *gin.Context) {
data := make(map[string]interface{}, 5) data := make(map[string]interface{}, 5)
data["app"] = appInfo data["app"] = appInfo
data["cpu"] = cpuModel data["cpu"] = cpuModel
data["memory"] = service.MyService.System().GetMemInfo().Total data["memory"] = service.MyService.System().GetMemInfo()["total"]
data["container"] = json2.RawMessage(containerInfo) data["container"] = json2.RawMessage(containerInfo)
data["info"] = con 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 获取安装所需要的数据 // @Summary 获取安装所需要的数据
@@ -1134,7 +1052,7 @@ func GetDockerInstallConfig(c *gin.Context) {
} }
data["networks"] = list data["networks"] = list
data["memory"] = service.MyService.System().GetMemInfo() data["memory"] = service.MyService.System().GetMemInfo()
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 获取依赖数据 // @Summary 获取依赖数据
@@ -1148,7 +1066,7 @@ func GetDockerInstallConfig(c *gin.Context) {
func ContainerRelyInfo(c *gin.Context) { func ContainerRelyInfo(c *gin.Context) {
id := c.Param("id") id := c.Param("id")
appInfo := service.MyService.Rely().GetInfo(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 获取可更新数据 // @Summary 获取可更新数据
@@ -1165,7 +1083,7 @@ func ContainerUpdateInfo(c *gin.Context) {
info, err := service.MyService.Docker().DockerContainerInfo(appId) info, err := service.MyService.Docker().DockerContainerInfo(appId)
if err != nil { if err != nil {
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 return
} }
var port model.PortArray var port model.PortArray
@@ -1184,14 +1102,24 @@ func ContainerUpdateInfo(c *gin.Context) {
var envs model.EnvArray var envs model.EnvArray
// json2.Unmarshal([]byte(appInfo.Envs), &envs) // json2.Unmarshal([]byte(appInfo.Envs), &envs)
for _, v := range info.Config.Env { showENV := info.Config.Labels["show_env"]
showENV := info.Config.Labels["show_env"] showENVList := strings.Split(showENV, ",")
showENVList := strings.Split(showENV, ",") showENVMap := make(map[string]string)
showENVMap := make(map[string]string) if len(showENVList) > 1 {
for _, name := range showENVList { for _, name := range showENVList {
showENVMap[name] = "1" showENVMap[name] = "1"
} }
if _, ok := showENVMap[v]; ok { }
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{ temp := model.Env{
Name: strings.Split(v, "=")[0], Name: strings.Split(v, "=")[0],
Value: strings.Split(v, "=")[1], Value: strings.Split(v, "=")[1],
@@ -1259,7 +1187,7 @@ func ContainerUpdateInfo(c *gin.Context) {
m.Protocol = "http" m.Protocol = "http"
} }
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: m}) c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m})
} }
////准备安装(暂时不需要) ////准备安装(暂时不需要)
@@ -1310,5 +1238,5 @@ func ContainerUpdateInfo(c *gin.Context) {
// } // }
// data["udp"] = inarr // 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})
//} //}

View File

@@ -19,9 +19,8 @@ import (
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "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/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid" uuid "github.com/satori/go.uuid"
@@ -65,15 +64,15 @@ func GetFilerContent(c *gin.Context) {
filePath := c.Query("path") filePath := c.Query("path")
if len(filePath) == 0 { if len(filePath) == 0 {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.INVALID_PARAMS, Success: common_err.INVALID_PARAMS,
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS), Message: common_err.GetMsg(common_err.INVALID_PARAMS),
}) })
return return
} }
if !file.Exists(filePath) { if !file.Exists(filePath) {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.FILE_DOES_NOT_EXIST, Success: common_err.FILE_DOES_NOT_EXIST,
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST), Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
}) })
return return
} }
@@ -81,8 +80,8 @@ func GetFilerContent(c *gin.Context) {
info, err := ioutil.ReadFile(filePath) info, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.FILE_READ_ERROR, Success: common_err.FILE_READ_ERROR,
Message: oasis_err2.GetMsg(oasis_err2.FILE_READ_ERROR), Message: common_err.GetMsg(common_err.FILE_READ_ERROR),
Data: err.Error(), Data: err.Error(),
}) })
return return
@@ -91,8 +90,8 @@ func GetFilerContent(c *gin.Context) {
//返回结果 //返回结果
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: result, Data: result,
}) })
} }
@@ -101,15 +100,15 @@ func GetLocalFile(c *gin.Context) {
path := c.Query("path") path := c.Query("path")
if len(path) == 0 { if len(path) == 0 {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.INVALID_PARAMS, Success: common_err.INVALID_PARAMS,
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS), Message: common_err.GetMsg(common_err.INVALID_PARAMS),
}) })
return return
} }
if !file.Exists(path) { if !file.Exists(path) {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.FILE_DOES_NOT_EXIST, Success: common_err.FILE_DOES_NOT_EXIST,
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST), Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
}) })
return return
} }
@@ -134,8 +133,8 @@ func GetDownloadFile(c *gin.Context) {
if len(files) == 0 { if len(files) == 0 {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.INVALID_PARAMS, Success: common_err.INVALID_PARAMS,
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS), Message: common_err.GetMsg(common_err.INVALID_PARAMS),
}) })
return return
} }
@@ -143,8 +142,8 @@ func GetDownloadFile(c *gin.Context) {
for _, v := range list { for _, v := range list {
if !file.Exists(v) { if !file.Exists(v) {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.FILE_DOES_NOT_EXIST, Success: common_err.FILE_DOES_NOT_EXIST,
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST), Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
}) })
return return
} }
@@ -159,8 +158,8 @@ func GetDownloadFile(c *gin.Context) {
info, err := os.Stat(filePath) info, err := os.Stat(filePath)
if err != nil { if err != nil {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.FILE_DOES_NOT_EXIST, Success: common_err.FILE_DOES_NOT_EXIST,
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST), Message: common_err.GetMsg(common_err.FILE_DOES_NOT_EXIST),
}) })
return return
} }
@@ -181,8 +180,8 @@ func GetDownloadFile(c *gin.Context) {
extension, ar, err := file.GetCompressionAlgorithm(t) extension, ar, err := file.GetCompressionAlgorithm(t)
if err != nil { if err != nil {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.INVALID_PARAMS, Success: common_err.INVALID_PARAMS,
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS), Message: common_err.GetMsg(common_err.INVALID_PARAMS),
}) })
return return
} }
@@ -190,8 +189,8 @@ func GetDownloadFile(c *gin.Context) {
err = ar.Create(c.Writer) err = ar.Create(c.Writer)
if err != nil { if err != nil {
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err.ERROR, Success: common_err.ERROR,
Message: oasis_err2.GetMsg(oasis_err2.ERROR), Message: common_err.GetMsg(common_err.ERROR),
Data: err.Error(), Data: err.Error(),
}) })
return return
@@ -199,7 +198,6 @@ func GetDownloadFile(c *gin.Context) {
defer ar.Close() defer ar.Close()
commonDir := file.CommonPrefix(filepath.Separator, list...) commonDir := file.CommonPrefix(filepath.Separator, list...)
currentPath := filepath.Base(commonDir) currentPath := filepath.Base(commonDir)
name := "_" + currentPath name := "_" + currentPath
@@ -235,7 +233,7 @@ func GetDownloadSingleFile(c *gin.Context) {
// @Router /file/dirpath [get] // @Router /file/dirpath [get]
func DirPath(c *gin.Context) { func DirPath(c *gin.Context) {
path := c.DefaultQuery("path", "") path := c.DefaultQuery("path", "")
info := service.MyService.ZiMa().GetDirPath(path) info := service.MyService.System().GetDirPath(path)
if path == "/DATA/AppData" { if path == "/DATA/AppData" {
list := service.MyService.Docker().DockerContainerList() list := service.MyService.Docker().DockerContainerList()
apps := make(map[string]string, len(list)) apps := make(map[string]string, len(list))
@@ -278,17 +276,20 @@ func DirPath(c *gin.Context) {
//Hide the files or folders in operation //Hide the files or folders in operation
fileQueue := make(map[string]string) fileQueue := make(map[string]string)
for _, v := range service.OpStrArr { if len(service.OpStrArr) > 0 {
v, ok := service.FileQueue.Load(v) for _, v := range service.OpStrArr {
if !ok { v, ok := service.FileQueue.Load(v)
continue if !ok {
} continue
vt := v.(model.FileOperate) }
for _, i := range vt.Item { vt := v.(model.FileOperate)
lastPath := i.From[strings.LastIndex(i.From, "/")+1:] for _, i := range vt.Item {
fileQueue[vt.To+"/"+lastPath] = i.From lastPath := i.From[strings.LastIndex(i.From, "/")+1:]
fileQueue[vt.To+"/"+lastPath] = i.From
}
} }
} }
pathList := []model.Path{} pathList := []model.Path{}
for i := 0; i < len(info); i++ { for i := 0; i < len(info); i++ {
if _, ok := fileQueue[info[i].Path]; !ok { if _, ok := fileQueue[info[i].Path]; !ok {
@@ -296,7 +297,7 @@ func DirPath(c *gin.Context) {
} }
} }
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: pathList}) c.JSON(http.StatusOK, model.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: pathList})
} }
// @Summary rename file or dir // @Summary rename file or dir
@@ -314,11 +315,11 @@ func RenamePath(c *gin.Context) {
op := json["oldpath"] op := json["oldpath"]
np := json["newpath"] np := json["newpath"]
if len(op) == 0 || len(np) == 0 { 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 return
} }
success, err := service.MyService.ZiMa().RenameFile(op, np) success, err := service.MyService.System().RenameFile(op, np)
c.JSON(http.StatusOK, model.Result{Success: success, Message: oasis_err2.GetMsg(success), Data: err}) c.JSON(http.StatusOK, model.Result{Success: success, Message: common_err.GetMsg(success), Data: err})
} }
// @Summary create folder // @Summary create folder
@@ -335,16 +336,16 @@ func MkdirAll(c *gin.Context) {
path := json["path"] path := json["path"]
var code int var code int
if len(path) == 0 { 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 return
} }
// decodedPath, err := url.QueryUnescape(path) // decodedPath, err := url.QueryUnescape(path)
// if err != nil { // 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 // return
// } // }
code, _ = service.MyService.ZiMa().MkdirAll(path) code, _ = service.MyService.System().MkdirAll(path)
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)}) c.JSON(http.StatusOK, model.Result{Success: code, Message: common_err.GetMsg(code)})
} }
// @Summary create file // @Summary create file
@@ -361,16 +362,16 @@ func PostCreateFile(c *gin.Context) {
path := json["path"] path := json["path"]
var code int var code int
if len(path) == 0 { 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 return
} }
// decodedPath, err := url.QueryUnescape(path) // decodedPath, err := url.QueryUnescape(path)
// if err != nil { // 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 // return
// } // }
code, _ = service.MyService.ZiMa().CreateFile(path) code, _ = service.MyService.System().CreateFile(path)
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)}) c.JSON(http.StatusOK, model.Result{Success: code, Message: common_err.GetMsg(code)})
} }
// @Summary upload file // @Summary upload file
@@ -391,7 +392,7 @@ func GetFileUpload(c *gin.Context) {
path := c.Query("path") path := c.Query("path")
dirPath := "" dirPath := ""
hash := file.GetHashByContent([]byte(fileName)) 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 { if fileName != relative {
dirPath = strings.TrimSuffix(relative, fileName) dirPath = strings.TrimSuffix(relative, fileName)
tempDir += dirPath tempDir += dirPath
@@ -399,11 +400,11 @@ func GetFileUpload(c *gin.Context) {
} }
tempDir += chunkNumber tempDir += chunkNumber
if !file.CheckNotExist(tempDir) { 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 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 // @Summary upload file
@@ -427,10 +428,10 @@ func PostFileUpload(c *gin.Context) {
hash := file.GetHashByContent([]byte(fileName)) hash := file.GetHashByContent([]byte(fileName))
if len(path) == 0 { 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 return
} }
tempDir := config.AppInfo.RootPath + "/temp/" + hash + strconv.Itoa(totalChunks) + "/" tempDir := config.AppInfo.TempPath + "/" + hash + strconv.Itoa(totalChunks) + "/"
if fileName != relative { if fileName != relative {
dirPath = strings.TrimSuffix(relative, fileName) dirPath = strings.TrimSuffix(relative, fileName)
@@ -451,7 +452,7 @@ func PostFileUpload(c *gin.Context) {
defer out.Close() defer out.Close()
_, err := io.Copy(out, f) _, err := io.Copy(out, f)
if err != nil { 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 return
} }
} else { } else {
@@ -459,15 +460,15 @@ func PostFileUpload(c *gin.Context) {
defer out.Close() defer out.Close()
_, err := io.Copy(out, f) _, err := io.Copy(out, f)
if err != nil { 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 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 return
} }
fileNum, err := ioutil.ReadDir(tempDir) fileNum, err := ioutil.ReadDir(tempDir)
if err != nil { 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 return
} }
if totalChunks == len(fileNum) { if totalChunks == len(fileNum) {
@@ -475,7 +476,7 @@ func PostFileUpload(c *gin.Context) {
file.RMDir(tempDir) 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 // @Summary copy or move file
@@ -492,9 +493,14 @@ func PostOperateFileOrDir(c *gin.Context) {
c.BindJSON(&list) c.BindJSON(&list)
if len(list.Item) == 0 { if len(list.Item) == 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 return
} }
if list.To == list.Item[0].From[:strings.LastIndex(list.Item[0].From, "/")] {
c.JSON(http.StatusOK, model.Result{Success: common_err.SOURCE_DES_SAME, Message: common_err.GetMsg(common_err.SOURCE_DES_SAME)})
return
}
var total int64 = 0 var total int64 = 0
for i := 0; i < len(list.Item); i++ { for i := 0; i < len(list.Item); i++ {
@@ -521,7 +527,7 @@ func PostOperateFileOrDir(c *gin.Context) {
} }
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 file // @Summary delete file
@@ -537,7 +543,7 @@ func DeleteFile(c *gin.Context) {
paths := []string{} paths := []string{}
c.BindJSON(&paths) c.BindJSON(&paths)
if len(paths) == 0 { if len(paths) == 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 return
} }
// path := c.Query("path") // path := c.Query("path")
@@ -547,12 +553,12 @@ func DeleteFile(c *gin.Context) {
for _, v := range paths { for _, v := range paths {
err := os.RemoveAll(v) err := os.RemoveAll(v)
if err != nil { if err != nil {
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 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 update file // @Summary update file
@@ -572,21 +578,21 @@ func PutFileContent(c *gin.Context) {
// path := c.PostForm("path") // path := c.PostForm("path")
// content := c.PostForm("content") // content := c.PostForm("content")
if !file.Exists(fi.FilePath) { if !file.Exists(fi.FilePath) {
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 return
} }
//err := os.Remove(path) //err := os.Remove(path)
err := os.RemoveAll(fi.FilePath) err := os.RemoveAll(fi.FilePath)
if err != nil { if err != nil {
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 return
} }
err = file.CreateFileAndWriteContent(fi.FilePath, fi.FileContent) err = file.CreateFileAndWriteContent(fi.FilePath, fi.FileContent)
if err != nil { if err != nil {
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 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 // @Summary image thumbnail/original image
@@ -602,13 +608,13 @@ func GetFileImage(c *gin.Context) {
t := c.Query("type") t := c.Query("type")
path := c.Query("path") path := c.Query("path")
if !file.Exists(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 return
} }
if t == "thumbnail" { if t == "thumbnail" {
f, err := file.GetImage(path, 100, 0) f, err := file.GetImage(path, 100, 0)
if err != nil { 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 return
} }
c.Writer.WriteString(string(f)) c.Writer.WriteString(string(f))
@@ -616,13 +622,13 @@ func GetFileImage(c *gin.Context) {
} }
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { 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 return
} }
defer f.Close() defer f.Close()
data, err := ioutil.ReadAll(f) data, err := ioutil.ReadAll(f)
if err != nil { 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 return
} }
c.Writer.WriteString(string(data)) c.Writer.WriteString(string(data))
@@ -647,5 +653,5 @@ func DeleteOperateFileOrDir(c *gin.Context) {
} }
go service.MyService.Notify().SendFileOperateNotify(true) go service.MyService.Notify().SendFileOperateNotify(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)})
} }

View File

@@ -1,5 +0,0 @@
package v1
func aaa() {
}

View File

@@ -17,9 +17,10 @@ import (
natType "github.com/Curtis-Milo/nat-type-identifier-go" natType "github.com/Curtis-Milo/nat-type-identifier-go"
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "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/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper" "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model" model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/IceWhaleTech/CasaOS/types" "github.com/IceWhaleTech/CasaOS/types"
@@ -40,18 +41,18 @@ func GetPersonReFile(c *gin.Context) {
uid := c.Param("uuid") uid := c.Param("uuid")
_, err := uuid.FromString(uid) _, err := uuid.FromString(uid)
if err != nil { 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 return
} }
task := service.MyService.Download().GetDownloadById(uid) task := service.MyService.Download().GetDownloadById(uid)
if reflect.DeepEqual(task, model2.PersonDownloadDBModel{}) { 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 return
} }
token := task.From token := task.From
if _, ok := service.UDPAddressMap[token]; !ok { 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 return
} }
@@ -63,7 +64,7 @@ func GetPersonReFile(c *gin.Context) {
m.UUId = uid m.UUId = uid
go service.Dial(m, false) 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 // @Summary download file
@@ -85,20 +86,20 @@ func GetPersonFile(c *gin.Context) {
fileName := c.Query("file_name") fileName := c.Query("file_name")
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
if len(path) == 0 || err != nil || len(localPath) == 0 || len(fileName) == 0 { 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 return
} }
if file.CheckNotExist(localPath) { 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 return
} }
if _, ok := service.UDPAddressMap[token]; !ok { 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 return
} }
if _, ok := service.UDPAddressMap[token]; !ok { 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 return
} }
@@ -117,7 +118,7 @@ func GetPersonFile(c *gin.Context) {
task.Type = types.PERSONFILEDOWNLOAD task.Type = types.PERSONFILEDOWNLOAD
task.LocalPath = localPath task.LocalPath = localPath
if service.MyService.Download().GetDownloadListByPath(task) > 0 { 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 return
} }
service.MyService.Download().AddDownloadTask(task) service.MyService.Download().AddDownloadTask(task)
@@ -130,7 +131,7 @@ func GetPersonFile(c *gin.Context) {
m.UUId = uuid m.UUId = uuid
go service.Dial(m, false) 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 // @Summary delete download file records
@@ -146,7 +147,7 @@ func DeletePersonDownloadFile(c *gin.Context) {
id := c.Param("uuid") id := c.Param("uuid")
_, err := uuid.FromString(id) _, err := uuid.FromString(id)
if err != nil { 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 return
} }
@@ -163,7 +164,7 @@ func DeletePersonDownloadFile(c *gin.Context) {
} }
service.MyService.Download().DelDownload(id) 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 // @Summary Get file download list
@@ -180,7 +181,7 @@ func GetPersonDownloadList(c *gin.Context) {
//if it is downloading, it need to add 'already' //if it is downloading, it need to add 'already'
for i := 0; i < len(list); i++ { for i := 0; i < len(list); i++ {
if list[i].State == types.DOWNLOADING { 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) files, err := ioutil.ReadDir(tempDir)
if err == nil { if err == nil {
list[i].Already = len(files) list[i].Already = len(files)
@@ -188,7 +189,7 @@ func GetPersonDownloadList(c *gin.Context) {
} }
list[i].Duration = time.Now().Unix() - list[i].Created 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 // @Summary edit friend's remarks
@@ -204,14 +205,14 @@ func PutPersonRemarks(c *gin.Context) {
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
mark := c.PostForm("remarks") mark := c.PostForm("remarks")
if err != nil || len(mark) == 0 { 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 return
} }
friend := model2.FriendModel{} friend := model2.FriendModel{}
friend.Token = token friend.Token = token
friend.Mark = mark friend.Mark = mark
service.MyService.Friend().EditFriendMark(friend) 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 // @Summary edit friend's
@@ -226,7 +227,7 @@ func PutPersonWrite(c *gin.Context) {
token := c.Param("shareid") token := c.Param("shareid")
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
if err != nil { 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 return
} }
write, _ := strconv.ParseBool(c.PostForm("write")) write, _ := strconv.ParseBool(c.PostForm("write"))
@@ -234,7 +235,7 @@ func PutPersonWrite(c *gin.Context) {
friend.Token = token friend.Token = token
friend.Write = write friend.Write = write
service.MyService.Friend().EditFriendMark(friend) 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 // @Summary image thumbnail
@@ -250,7 +251,7 @@ func GetPersonImageThumbnail(c *gin.Context) {
path := c.Query("path") path := c.Query("path")
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
if err != nil || len(path) == 0 { 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 return
} }
uuid := uuid.NewV4().String() uuid := uuid.NewV4().String()
@@ -263,7 +264,7 @@ func GetPersonImageThumbnail(c *gin.Context) {
img, err := service.Dial(m, false) img, err := service.Dial(m, false)
if err != nil { 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 return
} }
@@ -271,20 +272,20 @@ func GetPersonImageThumbnail(c *gin.Context) {
//err = gob.NewEncoder(&buf).Encode(img.Data) //err = gob.NewEncoder(&buf).Encode(img.Data)
if err != nil { 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 return
} }
var buf bytes.Buffer var buf bytes.Buffer
err = gob.NewEncoder(&buf).Encode(img.Data) err = gob.NewEncoder(&buf).Encode(img.Data)
if err != nil { 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 return
} }
imageBuffer, _ := base64.StdEncoding.DecodeString(img.Data.(string)) imageBuffer, _ := base64.StdEncoding.DecodeString(img.Data.(string))
c.Writer.WriteString(string(imageBuffer)) c.Writer.WriteString(string(imageBuffer))
// c.String(http.StatusOK, "data:image/"+filesuffix+";base64,"+img.Data.(string)) // 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 // @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 // @Summary network type detection
@@ -325,11 +326,11 @@ func GetPersonDetection(c *gin.Context) {
result, err := natType.GetDeterminedNatType(true, 5, "stun.l.google.com") result, err := natType.GetDeterminedNatType(true, 5, "stun.l.google.com")
if err != 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 return
} }
//result := service.MyService.Person().GetPersionNetWorkTypeDetection() //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 // @Summary add friend
@@ -346,24 +347,24 @@ func PostAddPersonFriend(c *gin.Context) {
for _, v := range tokenList { for _, v := range tokenList {
_, err := uuid.FromString(v) _, err := uuid.FromString(v)
if err != nil { 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 return
} }
if v == config.ServerInfo.Token { 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 return
} }
udb := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: v}) udb := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: v})
if !reflect.DeepEqual(udb, 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 return
} }
user := service.MyService.Casa().GetUserInfoByShareId(v) user := service.MyService.Casa().GetUserInfoByShareId(v)
if reflect.DeepEqual(user, model.UserInfo{}) { 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 return
} }
@@ -396,7 +397,7 @@ func PostAddPersonFriend(c *gin.Context) {
service.MyService.Friend().AddFriend(friend) 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 // @Summary Get a list of directories
@@ -413,11 +414,11 @@ func GetPersonDirectory(c *gin.Context) {
token := c.Query("share_id") token := c.Query("share_id")
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
if len(path) == 0 || err != nil { 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 return
} }
if _, ok := service.UDPAddressMap[token]; !ok { 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 return
} }
uuid := uuid.NewV4().String() uuid := uuid.NewV4().String()
@@ -429,7 +430,7 @@ func GetPersonDirectory(c *gin.Context) {
m.UUId = uuid m.UUId = uuid
result, err := service.Dial(m, false) result, err := service.Dial(m, false)
if err != 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 return
} }
dataModel := []model.Path{} dataModel := []model.Path{}
@@ -437,11 +438,11 @@ func GetPersonDirectory(c *gin.Context) {
dataModelByte, _ := json.Marshal(result.Data) dataModelByte, _ := json.Marshal(result.Data)
err := json.Unmarshal(dataModelByte, &dataModel) err := json.Unmarshal(dataModelByte, &dataModel)
if err != 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 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 // @Summary Modify the download storage directory
@@ -457,17 +458,17 @@ func PostPersonDownDir(c *gin.Context) {
downPath := c.PostForm("path") downPath := c.PostForm("path")
if len(downPath) == 0 { 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 return
} }
if file.CheckNotExist(downPath) { 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 return
} }
config.Cfg.Section("file").Key("DownloadDir").SetValue(downPath) config.Cfg.Section("file").Key("DownloadDir").SetValue(downPath)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
config.FileSettingInfo.DownloadDir = downPath 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 // @Summary Get the download storage directory
@@ -478,7 +479,7 @@ func PostPersonDownDir(c *gin.Context) {
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /person/down/dir [get] // @Router /person/down/dir [get]
func GetPersonDownDir(c *gin.Context) { 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 // @Summary Modify the shared directory
@@ -494,7 +495,7 @@ func PostPersonShare(c *gin.Context) {
share := c.PostForm("share") share := c.PostForm("share")
if len(share) == 0 { 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 return
} }
@@ -502,12 +503,12 @@ func PostPersonShare(c *gin.Context) {
json.Unmarshal([]byte(share), &list) json.Unmarshal([]byte(share), &list)
if len(list) == 0 { 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 return
} }
for _, v := range list { for _, v := range list {
if !file.Exists(v) { 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 return
} }
} }
@@ -515,7 +516,7 @@ func PostPersonShare(c *gin.Context) {
config.Cfg.Section("file").Key("ShareDir").SetValue(strings.Join(list, "|")) config.Cfg.Section("file").Key("ShareDir").SetValue(strings.Join(list, "|"))
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
config.FileSettingInfo.ShareDir = list 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 // @Summary Get the shared directory
@@ -526,7 +527,7 @@ func PostPersonShare(c *gin.Context) {
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /person/share [get] // @Router /person/share [get]
func GetPersonShare(c *gin.Context) { 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 // @Summary Get the shareid
@@ -537,7 +538,7 @@ func GetPersonShare(c *gin.Context) {
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /person/shareid [get] // @Router /person/shareid [get]
func GetPersonShareId(c *gin.Context) { 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 // @Summary Modify disabled status
@@ -553,14 +554,14 @@ func PutPersonBlock(c *gin.Context) {
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
block, _ := strconv.ParseBool(c.PostForm("block")) block, _ := strconv.ParseBool(c.PostForm("block"))
if err != nil { 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 return
} }
friend := model2.FriendModel{} friend := model2.FriendModel{}
friend.Token = token friend.Token = token
friend.Block = block friend.Block = block
service.MyService.Friend().EditFriendBlock(friend) 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 // @Summary Delete my friend
@@ -574,14 +575,14 @@ func DeletePersonFriend(c *gin.Context) {
token := c.Param("shareid") token := c.Param("shareid")
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
if err != nil { 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 return
} }
friend := model2.FriendModel{} friend := model2.FriendModel{}
friend.Token = token friend.Token = token
service.MyService.Friend().DeleteFriend(friend) 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 // @Summary Get public person
@@ -593,7 +594,7 @@ func DeletePersonFriend(c *gin.Context) {
// @Router /person/public [get] // @Router /person/public [get]
func GetPersonPublic(c *gin.Context) { func GetPersonPublic(c *gin.Context) {
list := service.MyService.Casa().GetPersonPublic() 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 // @Summary upload file to friend
@@ -611,11 +612,11 @@ func PostPersonFile(c *gin.Context) {
path := c.PostForm("path") path := c.PostForm("path")
localPath := c.PostForm("local_path") localPath := c.PostForm("local_path")
if err != nil { 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 return
} }
if !file.Exists(localPath) { 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 return
} }
uuid := uuid.NewV4().String() uuid := uuid.NewV4().String()
@@ -641,12 +642,12 @@ func PostPersonFile(c *gin.Context) {
task.Type = types.PERSONFILEUPLOAD task.Type = types.PERSONFILEUPLOAD
task.LocalPath = localPath task.LocalPath = localPath
if service.MyService.Download().GetDownloadListByPath(task) > 0 { 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 return
} }
service.MyService.Download().AddDownloadTask(task) 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 // @Summary agree add friend
@@ -660,14 +661,14 @@ func PutPersonAgreeFriend(c *gin.Context) {
token := c.Param("shareid") token := c.Param("shareid")
_, err := uuid.FromString(token) _, err := uuid.FromString(token)
if err != nil { 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 return
} }
user := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: token}) user := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: token})
if user.State != types.FRIENDSTATEREQUEST { 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 return
} }
service.MyService.Friend().AgreeFrined(user.Token) service.MyService.Friend().AgreeFrined(user.Token)
@@ -681,7 +682,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
m.UUId = uuid m.UUId = uuid
go service.Dial(m, true) 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 // // @Summary upload file
@@ -699,7 +700,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
// _, err := uuid.FromString(token) // _, err := uuid.FromString(token)
// path := c.Query("path") // path := c.Query("path")
// if err != nil { // 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 // return
// } // }
@@ -717,11 +718,11 @@ func PutPersonAgreeFriend(c *gin.Context) {
// } // }
// tempDir += chunkNumber // tempDir += chunkNumber
// if !file.CheckNotExist(tempDir) { // 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 // 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 // // @Summary upload file
@@ -737,7 +738,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
// token := c.Param("shareid") // token := c.Param("shareid")
// _, err := uuid.FromString(token) // _, err := uuid.FromString(token)
// if err != nil { // 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 // return
// } // }
// f, _, _ := c.Request.FormFile("file") // f, _, _ := c.Request.FormFile("file")
@@ -751,7 +752,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
// hash := file.GetHashByContent([]byte(fileName)) // hash := file.GetHashByContent([]byte(fileName))
// if len(path) == 0 { // 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 // return
// } // }
// tempDir := "/casaOS/temp/" + hash + strconv.Itoa(totalChunks) + "/" // tempDir := "/casaOS/temp/" + hash + strconv.Itoa(totalChunks) + "/"
@@ -775,7 +776,7 @@ func PutPersonAgreeFriend(c *gin.Context) {
// defer out.Close() // defer out.Close()
// _, err := io.Copy(out, f) // _, err := io.Copy(out, f)
// if err != nil { // 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 // return
// } // }
// } else { // } else {
@@ -783,21 +784,21 @@ func PutPersonAgreeFriend(c *gin.Context) {
// defer out.Close() // defer out.Close()
// _, err := io.Copy(out, f) // _, err := io.Copy(out, f)
// if err != nil { // 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 // 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 // return
// } // }
// fileNum, err := ioutil.ReadDir(tempDir) // fileNum, err := ioutil.ReadDir(tempDir)
// if err != nil { // 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 // return
// } // }
// if totalChunks == len(fileNum) { // if totalChunks == len(fileNum) {
// file.RMDir(tempDir) // 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)})
// } // }

View File

@@ -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})
}

View File

@@ -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)})
}

View File

@@ -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 package v1
import ( import (
"net/http"
"net/url"
"github.com/IceWhaleTech/CasaOS/model" "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" "github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model" model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http"
"net/url"
) )
// @Summary 获取短链列表 // @Summary 获取短链列表
@@ -21,7 +32,7 @@ import (
// @Router /shortcuts/list [get] // @Router /shortcuts/list [get]
func GetShortcutsList(c *gin.Context) { func GetShortcutsList(c *gin.Context) {
list := service.MyService.Shortcuts().GetList() 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 // @Summary 添加shortcuts
@@ -38,17 +49,17 @@ func PostShortcutsAdd(c *gin.Context) {
c.BindJSON(&m) c.BindJSON(&m)
if len(m.Url) == 0 || len(m.Title) == 0 { 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 return
} }
u, err := url.Parse(m.Url) u, err := url.Parse(m.Url)
if err != nil { 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 return
} }
m.Icon = "https://api.faviconkit.com/" + u.Host + "/57" m.Icon = "https://api.faviconkit.com/" + u.Host + "/57"
service.MyService.Shortcuts().AddData(m) 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") id := c.Param("id")
service.MyService.Shortcuts().DeleteData(id) service.MyService.Shortcuts().DeleteData(id)
c.JSON(http.StatusOK, model.Result{ c.JSON(http.StatusOK, model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: "", Data: "",
}) })
} }
@@ -82,15 +93,15 @@ func PutShortcutsEdit(c *gin.Context) {
var m model2.ShortcutsDBModel var m model2.ShortcutsDBModel
c.BindJSON(&m) c.BindJSON(&m)
if len(m.Url) == 0 || len(m.Title) == 0 { 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 return
} }
u, err := url.Parse(m.Url) u, err := url.Parse(m.Url)
if err != nil { 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 return
} }
m.Icon = "https://api.faviconkit.com/" + u.Host + "/57" m.Icon = "https://api.faviconkit.com/" + u.Host + "/57"
service.MyService.Shortcuts().EditData(m) 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: ""})
} }

View File

@@ -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 package v1
import ( import (
"net/http" "net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "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" "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) { func GetSyncConfig(c *gin.Context) {
data := make(map[string]string) data := make(map[string]string)
data["key"] = config.SystemConfigInfo.SyncKey data["key"] = config.SystemConfigInfo.SyncKey
data["port"] = config.SystemConfigInfo.SyncPort 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})
} }

View File

@@ -13,14 +13,16 @@ import (
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err" "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err" "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port" port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
"github.com/IceWhaleTech/CasaOS/pkg/utils/version" "github.com/IceWhaleTech/CasaOS/pkg/utils/version"
"github.com/IceWhaleTech/CasaOS/service" "github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model" model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/IceWhaleTech/CasaOS/types" "github.com/IceWhaleTech/CasaOS/types"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
"go.uber.org/zap"
) )
// @Summary check version // @Summary check version
@@ -29,9 +31,9 @@ import (
// @Tags sys // @Tags sys
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /sys/check [get] // @Router /sys/version/check [get]
func CheckVersion(c *gin.Context) { func GetSystemCheckVersion(c *gin.Context) {
need, version := version.IsNeedUpdate() need, version := version.IsNeedUpdate(service.MyService.Casa().GetCasaosVersion())
if need { if need {
installLog := model2.AppNotify{} installLog := model2.AppNotify{}
installLog.State = 0 installLog.State = 0
@@ -42,12 +44,11 @@ func CheckVersion(c *gin.Context) {
installLog.Name = "CasaOS System" installLog.Name = "CasaOS System"
service.MyService.Notify().AddLog(installLog) service.MyService.Notify().AddLog(installLog)
} }
data := make(map[string]interface{}, 1) data := make(map[string]interface{}, 3)
data["is_need"] = need data["is_need"] = need
data["version"] = version data["version"] = version
data["current_version"] = types.CURRENTVERSION 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})
return
} }
// @Summary 系统信息 // @Summary 系统信息
@@ -58,16 +59,16 @@ func CheckVersion(c *gin.Context) {
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /sys/update [post] // @Router /sys/update [post]
func SystemUpdate(c *gin.Context) { func SystemUpdate(c *gin.Context) {
need, version := version.IsNeedUpdate() need, version := version.IsNeedUpdate(service.MyService.Casa().GetCasaosVersion())
if need { if need {
service.MyService.System().UpdateSystemVersion(version.Version) 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) { 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 // @Summary get logs
@@ -79,7 +80,7 @@ func GetSystemConfig(c *gin.Context) {
// @Router /sys/error/logs [get] // @Router /sys/error/logs [get]
func GetCasaOSErrorLogs(c *gin.Context) { func GetCasaOSErrorLogs(c *gin.Context) {
line, _ := strconv.Atoi(c.DefaultQuery("line", "100")) 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 修改配置文件 // @Summary 修改配置文件
@@ -97,8 +98,8 @@ func PostSetSystemConfig(c *gin.Context) {
service.MyService.System().UpSystemConfig(string(buf[0:n]), "") service.MyService.System().UpSystemConfig(string(buf[0:n]), "")
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: json.RawMessage(config.SystemConfigInfo.ConfigStr), Data: json.RawMessage(config.SystemConfigInfo.ConfigStr),
}) })
} }
@@ -107,8 +108,8 @@ func PostSetSystemConfig(c *gin.Context) {
func GetSystemConfigDebug(c *gin.Context) { func GetSystemConfigDebug(c *gin.Context) {
array := service.MyService.System().GetSystemConfigDebug() array := service.MyService.System().GetSystemConfigDebug()
disk := service.MyService.ZiMa().GetDiskInfo() disk := service.MyService.System().GetDiskInfo()
sys := service.MyService.ZiMa().GetSysInfo() sys := service.MyService.System().GetSysInfo()
//todo 准备sync需要显示的数据(镜像,容器) //todo 准备sync需要显示的数据(镜像,容器)
var systemAppStatus string var systemAppStatus string
images := service.MyService.Docker().IsExistImage("linuxserver/syncthing") images := service.MyService.Docker().IsExistImage("linuxserver/syncthing")
@@ -134,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)) // 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配置 //widget配置
func GetWidgetConfig(c *gin.Context) { 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 修改组件配置文件 // @Summary 修改组件配置文件
@@ -155,8 +156,8 @@ func PostSetWidgetConfig(c *gin.Context) {
service.MyService.System().UpSystemConfig("", string(buf[0:n])) service.MyService.System().UpSystemConfig("", string(buf[0:n]))
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: json.RawMessage(config.SystemConfigInfo.WidgetList), Data: json.RawMessage(config.SystemConfigInfo.WidgetList),
}) })
} }
@@ -171,8 +172,8 @@ func PostSetWidgetConfig(c *gin.Context) {
func GetCasaOSPort(c *gin.Context) { func GetCasaOSPort(c *gin.Context) {
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: config.ServerInfo.HttpPort, Data: config.ServerInfo.HttpPort,
}) })
} }
@@ -182,15 +183,18 @@ func GetCasaOSPort(c *gin.Context) {
// @Accept application/json // @Accept application/json
// @Tags sys // @Tags sys
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Param port formData string true "port" // @Param port json string true "port"
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /sys/port [put] // @Router /sys/port [put]
func PutCasaOSPort(c *gin.Context) { 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 { if err != nil {
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.ERROR, Success: common_err.ERROR,
Message: err.Error(), Message: err.Error(),
}) })
return return
@@ -200,16 +204,16 @@ func PutCasaOSPort(c *gin.Context) {
if !isAvailable { if !isAvailable {
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.PORT_IS_OCCUPIED, Success: common_err.PORT_IS_OCCUPIED,
Message: oasis_err.GetMsg(oasis_err.PORT_IS_OCCUPIED), Message: common_err.GetMsg(common_err.PORT_IS_OCCUPIED),
}) })
return return
} }
service.MyService.System().UpSystemPort(strconv.Itoa(port)) service.MyService.System().UpSystemPort(strconv.Itoa(port))
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
}) })
} }
@@ -219,18 +223,23 @@ func PutCasaOSPort(c *gin.Context) {
// @Tags sys // @Tags sys
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /guide/check [get] // @Router /sys/init/check [get]
func GetGuideCheck(c *gin.Context) { func GetSystemInitCheck(c *gin.Context) {
initUser := false data := make(map[string]interface{}, 2)
if !config.UserInfo.Initialized {
initUser = true 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, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: data, Data: data,
}) })
} }
@@ -241,7 +250,7 @@ func GetGuideCheck(c *gin.Context) {
// @Tags sys // @Tags sys
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /sys/kill [post] // @Router /sys/restart [post]
func PostKillCasaOS(c *gin.Context) { func PostKillCasaOS(c *gin.Context) {
os.Exit(0) os.Exit(0)
} }
@@ -253,13 +262,20 @@ func PostKillCasaOS(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /sys/usb/off [put] // @Router /sys/usb/off [put]
func PutSystemOffUSBAutoMount(c *gin.Context) { func PutSystemUSBAutoMount(c *gin.Context) {
service.MyService.System().UpdateUSBAutoMount("False") status := c.Param("status")
service.MyService.System().ExecUSBAutoMountShell("False") 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, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
}) })
} }
@@ -278,8 +294,8 @@ func GetSystemUSBAutoMount(c *gin.Context) {
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: state, Data: state,
}) })
} }
@@ -294,40 +310,23 @@ func GetSystemUSBAutoMount(c *gin.Context) {
func GetSystemHardwareInfo(c *gin.Context) { func GetSystemHardwareInfo(c *gin.Context) {
data := make(map[string]string, 1) data := make(map[string]string, 1)
data["drive_model"] = service.MyService.ZiMa().GetDeviceTree() data["drive_model"] = service.MyService.System().GetDeviceTree()
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: data, Data: data,
}) })
} }
// @Summary Turn off usb auto-mount // @Summary system utilization
// @Produce application/json // @Produce application/json
// @Accept application/json // @Accept application/json
// @Tags sys // @Tags sys
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /sys/usb/on [put] // @Router /sys/utilization [get]
func PutSystemOnUSBAutoMount(c *gin.Context) { func GetSystemUtilization(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) {
var data = make(map[string]interface{}, 6) var data = make(map[string]interface{}, 6)
list := service.MyService.Disk().LSBLK(true) list := service.MyService.Disk().LSBLK(true)
@@ -347,6 +346,8 @@ func Info(c *gin.Context) {
s, _ := strconv.ParseUint(v.FSSize, 10, 64) s, _ := strconv.ParseUint(v.FSSize, 10, 64)
a, _ := strconv.ParseUint(v.FSAvail, 10, 64) a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
u, _ := strconv.ParseUint(v.FSUsed, 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.Size += s
summary.Avail += a summary.Avail += a
summary.Used += u summary.Used += u
@@ -359,6 +360,8 @@ func Info(c *gin.Context) {
s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64) s, _ := strconv.ParseUint(list[i].Children[j].FSSize, 10, 64)
a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64) a, _ := strconv.ParseUint(list[i].Children[j].FSAvail, 10, 64)
u, _ := strconv.ParseUint(list[i].Children[j].FSUsed, 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.Size += s
summary.Avail += a summary.Avail += a
summary.Used += u summary.Used += u
@@ -373,21 +376,20 @@ func Info(c *gin.Context) {
findSystem += 1 findSystem += 1
continue 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) temp := service.MyService.Disk().SmartCTL(list[i].Path)
if reflect.DeepEqual(temp, model.SmartctlA{}) { if reflect.DeepEqual(temp, model.SmartctlA{}) {
continue healthy = true
} } else {
healthy = temp.SmartStatus.Passed
//list[i].Temperature = temp.Temperature.Current
if !temp.SmartStatus.Passed {
healthy = false
} }
if len(list[i].Children) > 0 { if len(list[i].Children) > 0 {
for _, v := range list[i].Children { for _, v := range list[i].Children {
s, _ := strconv.ParseUint(v.FSSize, 10, 64) s, _ := strconv.ParseUint(v.FSSize, 10, 64)
a, _ := strconv.ParseUint(v.FSAvail, 10, 64) a, _ := strconv.ParseUint(v.FSAvail, 10, 64)
u, _ := strconv.ParseUint(v.FSUsed, 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.Size += s
summary.Avail += a summary.Avail += a
summary.Used += u summary.Used += u
@@ -442,7 +444,7 @@ func Info(c *gin.Context) {
for _, netCardName := range nets { for _, netCardName := range nets {
if n.Name == netCardName { if n.Name == netCardName {
item := *(*model.IOCountersStat)(unsafe.Pointer(&n)) 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() item.Time = time.Now().Unix()
newNet = append(newNet, item) newNet = append(newNet, item)
break break
@@ -452,7 +454,7 @@ func Info(c *gin.Context) {
data["net"] = newNet 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 // @Summary Get notification port
@@ -466,8 +468,98 @@ func GetSystemSocketPort(c *gin.Context) {
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: config.ServerInfo.SocketPort, 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,
})
}

View File

@@ -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)})
}

View File

@@ -1,225 +1,281 @@
package v1 package v1
import ( import (
"fmt" json2 "encoding/json"
"io/ioutil"
"net/http" "net/http"
url2 "net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
jwt2 "github.com/IceWhaleTech/CasaOS/pkg/utils/jwt" "github.com/IceWhaleTech/CasaOS/pkg/utils/common_err"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err" "github.com/IceWhaleTech/CasaOS/pkg/utils/encryption"
"github.com/IceWhaleTech/CasaOS/service" "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/IceWhaleTech/CasaOS/types"
"github.com/tidwall/gjson"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
var user_service service.UserService // @Summary register user
// @Router /user/register/ [post]
func init() { func PostUserRegister(c *gin.Context) {
user_service = service.NewUserService() json := make(map[string]string)
} c.BindJSON(&json)
username := json["user_name"]
// @Summary 设置用户名和密码 pwd := json["password"]
// @Produce application/json key := c.Param("key")
// @Accept multipart/form-data if _, ok := service.UserRegisterHash[key]; !ok {
// @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 {
c.JSON(http.StatusOK, 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 return
} }
//开始设置
err := user_service.SetUser(username, pwd, "", "", "", "") if len(username) == 0 || len(pwd) == 0 {
if err != nil { c.JSON(http.StatusOK,
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: fmt.Sprintf("%v", err)}) model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
return
} else {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
return 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 // @Produce application/json
// @Accept multipart/form-data // @Accept application/json
// @Tags user // @Tags user
// @Param username formData string true "User name" // @Param user_name query string true "User name"
// @Param pwd formData string true "password" // @Param pwd query string true "password"
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/login [post] // @Router /user/login [post]
func Login(c *gin.Context) { func PostUserLogin(c *gin.Context) {
username := c.PostForm("username") json := make(map[string]string)
pwd := c.PostForm("pwd") c.BindJSON(&json)
//检查参数是否正确
username := json["username"]
pwd := json["pwd"]
//check params is empty
if len(username) == 0 || len(pwd) == 0 { if len(username) == 0 || len(pwd) == 0 {
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err2.ERROR, Success: common_err.ERROR,
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS), Message: common_err.GetMsg(common_err.INVALID_PARAMS),
}) })
return return
} }
user := service.MyService.User().GetUserAllInfoByName(username)
if config.UserInfo.UserName == username && config.UserInfo.PWD == pwd { if user.Id == 0 {
//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, "", "")
c.JSON(http.StatusOK, c.JSON(http.StatusOK,
model.Result{ model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
Success: oasis_err2.SUCCESS,
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS),
Data: data,
})
return 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, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err2.ERROR, Success: common_err.SUCCESS,
Message: oasis_err2.GetMsg(oasis_err2.ERROR), Message: common_err.GetMsg(common_err.SUCCESS),
Data: data,
}) })
} }
// @Summary 修改头像 // @Summary edit user head
// @Produce application/json // @Produce application/json
// @Accept multipart/form-data // @Accept multipart/form-data
// @Tags user // @Tags user
// @Param file formData file true "用户头像" // @Param file formData file true "用户头像"
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/changhead [post] // @Router /user/avatar [put]
func PostUserHead(c *gin.Context) { func PutUserAvatar(c *gin.Context) {
file, _, _ := c.Request.FormFile("file") id := c.GetHeader("user_id")
user_service.UpLoadFile(file, config.UserInfo.Head) 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, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err2.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: config.UserInfo.Head, 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 // @Produce application/json
// @Accept multipart/form-data // @Accept application/json
// @Tags user // @Tags user
// @Param username formData string true "User name" // @Param old_name query string true "Old user name"
// @Param oldname formData string true "Old user name"
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/username [put] // @Router /user/name/:id [put]
func PutUserName(c *gin.Context) { func PutUserName(c *gin.Context) {
if config.ServerInfo.LockAccount { //id := c.GetHeader("user_id")
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ACCOUNT_LOCK, Message: oasis_err2.GetMsg(oasis_err2.ACCOUNT_LOCK)}) 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 return
} }
oldname := c.PostForm("oldname") user := service.MyService.User().GetUserInfoById(id)
username := c.PostForm("username")
if len(username) == 0 || config.UserInfo.UserName != oldname { if user.Id == 0 {
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.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
return return
} }
user_service.SetUser(username, "", "", "", "", "") user.UserName = username
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)}) 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 // @Produce application/json
// @Accept multipart/form-data // @Accept application/json
// @Tags user // @Tags user
// @Param pwd formData string true "Password"
// @Param old_pwd formData string true "Old password"
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/password [put] // @Router /user/password/:id [put]
func PutUserPwd(c *gin.Context) { func PutUserPwd(c *gin.Context) {
oldPwd := c.PostForm("old_pwd") //id := c.GetHeader("user_id")
pwd := c.PostForm("pwd") json := make(map[string]string)
if config.UserInfo.PWD != oldPwd { c.BindJSON(&json)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PWD_INVALID_OLD, Message: oasis_err2.GetMsg(oasis_err2.PWD_INVALID_OLD)}) 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 return
} }
if config.ServerInfo.LockAccount { user := service.MyService.User().GetUserAllInfoById(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ACCOUNT_LOCK, Message: oasis_err2.GetMsg(oasis_err2.ACCOUNT_LOCK)}) 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 return
} }
if len(pwd) == 0 { if user.Password != encryption.GetMD5ByStr(oldPwd) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PWD_IS_EMPTY, Message: oasis_err2.GetMsg(oasis_err2.PWD_IS_EMPTY)}) c.JSON(http.StatusOK, model.Result{Success: common_err.PWD_INVALID_OLD, Message: common_err.GetMsg(common_err.PWD_INVALID_OLD)})
return return
} }
user_service.SetUser("", pwd, "", "", "", "") user.Password = encryption.GetMD5ByStr(pwd)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)}) 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 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})
} }
// @Summary edit user nick // @Summary edit user nick
// @Produce application/json // @Produce application/json
// @Accept multipart/form-data // @Accept application/json
// @Tags user // @Tags user
// @Param nick_name formData string false "nick name" // @Param nick_name query string false "nick name"
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/nick [put] // @Router /user/nick [put]
func PutUserChangeNick(c *gin.Context) { func PutUserNick(c *gin.Context) {
nickName := c.PostForm("nick_name")
//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 { 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 return
} }
user_service.SetUser("", "", "", "", "", nickName) user := service.MyService.User().GetUserInfoById(id)
data := make(map[string]string, 1) if user.Id == 0 {
data["nick_name"] = config.UserInfo.NickName 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() 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 // @Summary edit user description
@@ -230,18 +286,27 @@ func PutUserChangeNick(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/desc [put] // @Router /user/desc [put]
func PutUserChangeDesc(c *gin.Context) { func PutUserDesc(c *gin.Context) {
desc := c.PostForm("description") // id := c.GetHeader("user_id")
json := make(map[string]string)
c.BindJSON(&json)
id := json["user_id"]
desc := json["description"]
if len(desc) == 0 { 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 return
} }
user_service.SetUser("", "", "", "", desc, "") user := service.MyService.User().GetUserInfoById(id)
data := make(map[string]string, 1) if user.Id == 0 {
data["description"] = config.UserInfo.Description c.JSON(http.StatusOK,
go service.MyService.Casa().PushUserInfo() model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)})
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data}) 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) // @Summary Modify user person information (Initialization use)
@@ -254,38 +319,85 @@ func PutUserChangeDesc(c *gin.Context) {
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/person/info [post] // @Router /user/person/info [post]
func PostUserPersonInfo(c *gin.Context) { func PostUserPersonInfo(c *gin.Context) {
desc := c.PostForm("description") json := make(map[string]string)
nickName := c.PostForm("nick_name") c.BindJSON(&json)
desc := json["description"]
nickName := json["nick_name"]
id := json["user_id"]
if len(desc) == 0 || len(nickName) == 0 { 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 return
} }
user_service.SetUser("", "", "", "", desc, nickName) user := service.MyService.User().GetUserInfoById(id)
data := make(map[string]string, 2) if user.Id == 0 {
data["description"] = config.UserInfo.Description c.JSON(http.StatusOK,
data["nick_name"] = config.UserInfo.NickName 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() 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 // @Summary get user info
// @Produce application/json // @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 // @Tags user
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/info [get] // @Router /user/info [get]
func GetUserInfo(c *gin.Context) { func GetUserInfoByUserName(c *gin.Context) {
var u = make(map[string]string, 5) json := make(map[string]string)
u["user_name"] = config.UserInfo.UserName c.BindJSON(&json)
u["head"] = config.UserInfo.Head userName := json["user_name"]
u["email"] = config.UserInfo.Email if len(userName) == 0 {
u["description"] = config.UserInfo.Description c.JSON(http.StatusOK, model.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
u["nick_name"] = config.UserInfo.NickName 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, c.JSON(http.StatusOK,
model.Result{ model.Result{
Success: oasis_err2.SUCCESS, Success: common_err.SUCCESS,
Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Message: common_err.GetMsg(common_err.SUCCESS),
Data: u, Data: user,
}) })
} }
@@ -297,5 +409,327 @@ func GetUserInfo(c *gin.Context) {
// @Success 200 {string} string "ok" // @Success 200 {string} string "ok"
// @Router /user/shareid [get] // @Router /user/shareid [get]
func GetUserShareID(c *gin.Context) { 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})
} }

View File

@@ -1,106 +0,0 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2021-09-30 18:18:14
* @LastEditors: LinkLeong
* @LastEditTime: 2022-05-27 18:07:13
* @FilePath: /CasaOS/route/v1/zima_info.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
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.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: 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.System().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.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.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})
}

View File

@@ -7,7 +7,6 @@ import (
"io" "io"
"io/ioutil" "io/ioutil"
"runtime" "runtime"
"strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -27,12 +26,7 @@ import (
) )
type AppService interface { 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) GetMyList(index, size int, position bool) (*[]model2.MyAppList, *[]model2.MyAppList)
GetCasaOSCount() int
SaveContainer(m model2.AppListDBModel) SaveContainer(m model2.AppListDBModel)
GetUninstallInfo(id string) model2.AppListDBModel GetUninstallInfo(id string) model2.AppListDBModel
DeleteApp(id string) DeleteApp(id string)
@@ -54,24 +48,6 @@ type appStruct struct {
db *gorm.DB db *gorm.DB
} }
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
}
func (a *appStruct) CheckNewImage() { func (a *appStruct) CheckNewImage() {
list := MyService.Docker().DockerContainerList() list := MyService.Docker().DockerContainerList()
for _, v := range list { for _, v := range list {
@@ -155,28 +131,6 @@ func (a *appStruct) ImportApplications(casaApp bool) {
// } // }
// MyService.Docker().DockerContainerStart(container_id) // MyService.Docker().DockerContainerStart(container_id)
//} //}
}
func (a *appStruct) GetCasaOSCount() int {
cli, err := client2.NewClientWithOpts(client2.FromEnv, client2.WithTimeout(time.Second*5))
if err != nil {
loger.Error("Failed to init client", zap.Any("err", 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 {
loger.Error("failed to get container_list", zap.Any("err", err))
return 0
}
systemApp := MyService.App().GetApplicationList()
return len(containers) + len(systemApp)
} }
//获取我的应用列表 //获取我的应用列表
@@ -200,25 +154,6 @@ func (a *appStruct) GetMyList(index, size int, position bool) (*[]model2.MyAppLi
list := []model2.MyAppList{} 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,
Host: "",
Protocol: "",
NewVersion: false,
})
}
for _, m := range containers { for _, m := range containers {
if m.Labels["casaos"] == "casaos" { if m.Labels["casaos"] == "casaos" {
if m.Labels["origin"] == "system" { if m.Labels["origin"] == "system" {
@@ -403,7 +338,7 @@ func (a *appStruct) UpdateApp(m model2.AppListDBModel) {
} }
func (a *appStruct) DelAppConfigDir(path string) { 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) { func (a *appStruct) DeleteApp(id string) {
@@ -464,12 +399,8 @@ func (a *appStruct) GetHardwareUsageSteam() {
fts := filters.NewArgs() fts := filters.NewArgs()
fts.Add("label", "casaos=casaos") fts.Add("label", "casaos=casaos")
//fts.Add("label", "casaos") //fts.Add("status", "running")
//fts.Add("casaos", "casaos")
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true, Filters: fts})
if err != nil {
loger.Error("Failed to get container_list", zap.Any("err", err))
}
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
if config.CasaOSGlobalVariables.AppChange { if config.CasaOSGlobalVariables.AppChange {
config.CasaOSGlobalVariables.AppChange = false config.CasaOSGlobalVariables.AppChange = false
@@ -479,8 +410,16 @@ func (a *appStruct) GetHardwareUsageSteam() {
return true 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 var wg sync.WaitGroup
for _, v := range containers { for _, v := range containers {
if v.State != "running" {
continue
}
wg.Add(1) wg.Add(1)
go func(v types.Container, i int) { go func(v types.Container, i int) {
defer wg.Done() defer wg.Done()
@@ -501,15 +440,18 @@ func (a *appStruct) GetHardwareUsageSteam() {
dockerStats.Data = data dockerStats.Data = data
dockerStats.Icon = v.Labels["icon"] dockerStats.Icon = v.Labels["icon"]
dockerStats.Title = strings.ReplaceAll(v.Names[0], "/", "") dockerStats.Title = strings.ReplaceAll(v.Names[0], "/", "")
dataStats.Store(v.ID, dockerStats)
temp.Store(v.ID, dockerStats)
if i == 99 { if i == 99 {
stats.Body.Close() stats.Body.Close()
} }
}(v, i) }(v, i)
} }
wg.Wait() wg.Wait()
dataStats = temp
isFinish = true isFinish = true
time.Sleep(time.Second * 3)
time.Sleep(time.Second * 1)
} }
isFinish = false isFinish = false
cancel() cancel()

View File

@@ -4,29 +4,34 @@ import (
"encoding/json" "encoding/json"
json2 "encoding/json" json2 "encoding/json"
"fmt" "fmt"
"sort"
"strconv" "strconv"
"time" "time"
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "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" httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
model2 "github.com/IceWhaleTech/CasaOS/service/model" "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"go.uber.org/zap"
) )
type CasaService interface { type CasaService interface {
GetServerList(index, size, tp, categoryId, key, language string) (recommend, list, community []model.ServerAppList) GetServerList(index, size, tp, categoryId, key string) model.ServerAppListCollection
GetServerCategoryList() []model.ServerCategoryList GetServerCategoryList() []model.CategoryList
GetTaskList(size int) []model2.TaskDBModel
GetServerAppInfo(id, t string, language string) model.ServerAppList GetServerAppInfo(id, t string, language string) model.ServerAppList
ShareAppFile(body []byte) string ShareAppFile(body []byte) string
PushHeart(id, t string, language string) PushHeart(id, t string, language string)
PushAppAnalyse(uuid, t string, name, language string)
PushConnectionStatus(uuid, err string, from, to, event string) PushConnectionStatus(uuid, err string, from, to, event string)
PushUserInfo() PushUserInfo()
GetUserInfoByShareId(shareId string) model.UserInfo GetUserInfoByShareId(shareId string) model.UserInfo
GetPersonPublic() (list []model.FriendsModel) GetPersonPublic() (list []model.FriendsModel)
GetCasaosVersion() model.Version
AsyncGetServerList() (collection model.ServerAppListCollection)
AsyncGetServerCategoryList() []model.CategoryList
} }
type casaService struct { type casaService struct {
@@ -41,108 +46,186 @@ func (o *casaService) ShareAppFile(body []byte) string {
return content return content
} }
func (o *casaService) GetTaskList(size int) []model2.TaskDBModel { func (o *casaService) GetServerList(index, size, tp, categoryId, key string) model.ServerAppListCollection {
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)
keyName := fmt.Sprintf("list_%s_%s_%s_%s_%s", index, size, tp, categoryId, "en")
collection := model.ServerAppListCollection{}
if result, ok := Cache.Get(keyName); ok { if result, ok := Cache.Get(keyName); ok {
res, ok := result.(string) res, ok := result.(string)
if ok { if ok {
json2.Unmarshal([]byte(gjson.Get(res, "data.list").String()), &list) json2.Unmarshal([]byte(res), &collection)
json2.Unmarshal([]byte(gjson.Get(res, "data.recommend").String()), &recommend) return collection
json2.Unmarshal([]byte(gjson.Get(res, "data.community").String()), &community)
return
} }
} }
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 := make(map[string]string)
head["Authorization"] = GetToken() 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) if len(listModel) > 0 {
json2.Unmarshal([]byte(gjson.Get(listS, "data.recommend").String()), &recommend) collection.Community = communityModel
json2.Unmarshal([]byte(gjson.Get(listS, "data.community").String()), &community) collection.List = listModel
collection.Recommend = recommendModel
if len(list) > 0 { collection.Version = o.GetCasaosVersion().Version
Cache.Set(keyName, listS, time.Hour*24) 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 return
} }
func (o *casaService) GetServerCategoryList() (list []model.ServerCategoryList) { // func (o *casaService) GetServerCategoryList() (list []model.ServerCategoryList) {
keyName := fmt.Sprintf("category_list") // keyName := fmt.Sprintf("category_list")
if result, ok := Cache.Get(keyName); ok { // if result, ok := Cache.Get(keyName); ok {
res, ok := result.(string) // res, ok := result.(string)
if ok { // if ok {
json2.Unmarshal([]byte(gjson.Get(res, "data").String()), &list) // json2.Unmarshal([]byte(gjson.Get(res, "data").String()), &list)
return list // return list
} // }
} // }
head := make(map[string]string) // head := make(map[string]string)
head["Authorization"] = GetToken() // head["Authorization"] = GetToken()
listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/category", head) // listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/category", head)
json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list) // json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &list)
if len(list) > 0 { // if len(list) > 0 {
Cache.Set(keyName, listS, time.Hour*24) // Cache.Set(keyName, listS, time.Hour*24)
}
return list
}
// func (o *casaService) GetServerCategoryList() (list model.ServerCategoryList) {
// results := file.ReadFullFile(config.AppInfo.ProjectPath + "/conf/app_category.json")
// err := json2.Unmarshal(results, &list)
// if err != nil {
// loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(results)))
// } // }
// return list // return list
// } // }
// func (o *casaService) AsyncGetServerCategoryList() { func (o *casaService) GetServerCategoryList() (list []model.CategoryList) {
// list := model.ServerCategoryList{} category := model.ServerCategoryList{}
// results := file.ReadFullFile(config.AppInfo.ProjectPath + "/conf/app_category.json") results := file.ReadFullFile(config.AppInfo.DBPath + "/app_category.json")
// err := json2.Unmarshal(results, &list) err := json2.Unmarshal(results, &category)
// if err != nil { if err != nil {
// loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(results))) loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(results)))
// } return o.AsyncGetServerCategoryList()
}
go o.AsyncGetServerCategoryList()
return category.Item
}
// if list.Version == GetAppVersion() { func (o *casaService) AsyncGetServerCategoryList() []model.CategoryList {
// return list := model.ServerCategoryList{}
// } results := file.ReadFullFile(config.AppInfo.DBPath + "/app_category.json")
// item := []model.CategoryList{} err := json2.Unmarshal(results, &list)
// head := make(map[string]string) if err != nil {
// head["Authorization"] = GetToken() loger.Error("marshal error", zap.Any("err", err), zap.Any("content", string(results)))
// listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/category", head) }
// json2.Unmarshal([]byte(gjson.Get(listS, "data").String()), &item)
// if len(item) > 0 { if list.Version == o.GetCasaosVersion().Version {
// list.Version = GetAppVersion() return nil
// list.Item = item }
// by, err := json.Marshal(list) item := []model.CategoryList{}
// if err != nil { head := make(map[string]string)
// loger.Error("marshal error", zap.Any("err", err)) head["Authorization"] = GetToken()
// } listS := httper2.Get(config.ServerInfo.ServerApi+"/v2/app/category", head)
// file.WriteToPath(by, config.AppInfo.ProjectPath+"/conf", "app_category.json") 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 { func (o *casaService) GetServerAppInfo(id, t string, language string) model.ServerAppList {
@@ -178,6 +261,34 @@ func GetToken() string {
return auth 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) { func (o *casaService) PushHeart(id, t string, language string) {
m := model.CasaOSHeart{} m := model.CasaOSHeart{}
@@ -196,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) { func (o *casaService) PushConnectionStatus(uuid, err string, from, to, event string) {
m := model.ConnectionStatus{} m := model.ConnectionStatus{}

View File

@@ -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)
}
}

View File

@@ -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)
}

View File

@@ -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")
}

View File

@@ -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()
}

View File

@@ -67,38 +67,38 @@ func (d *diskService) SmartCTL(path string) model.SmartctlA {
loger.Error("Failed to unmarshal json", zap.Any("err", err)) loger.Error("Failed to unmarshal json", zap.Any("err", err))
} }
if !reflect.DeepEqual(m, model.SmartctlA{}) { if !reflect.DeepEqual(m, model.SmartctlA{}) {
Cache.Add(key, m, time.Second*10) Cache.Add(key, m, time.Hour*24)
} }
return m return m
} }
//通过脚本获取外挂磁盘 //通过脚本获取外挂磁盘
func (d *diskService) GetPlugInDisk() []string { 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 { 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 return r
} }
//移除挂载点,删除目录 //移除挂载点,删除目录
func (d *diskService) UmountPointAndRemoveDir(path string) []string { 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 return r
} }
//删除分区 //删除分区
func (d *diskService) DelPartition(path, num string) string { 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) fmt.Println(r)
return "" return ""
} }
//part //part
func (d *diskService) AddPartition(path string) string { 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 "" return ""
} }
@@ -152,7 +152,7 @@ func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {
fsused = 0 fsused = 0
for _, child := range i.Children { for _, child := range i.Children {
if child.RM { 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" { if strings.ToLower(strings.TrimSpace(child.State)) != "ok" {
health = false health = false
} }
@@ -163,7 +163,7 @@ func (d *diskService) LSBLK(isUseCache bool) []model.LSBLKModel {
} }
c = append(c, child) 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 { if health {
i.Health = "OK" i.Health = "OK"
} }
@@ -208,7 +208,7 @@ func (d *diskService) GetDiskInfo(path string) model.LSBLKModel {
return m return m
// 下面为计算是否可以继续分区的部分,暂时不需要 // 下面为计算是否可以继续分区的部分,暂时不需要
chiArr := make(map[string]string) 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 { if len(chiList) == 0 {
loger.Error("chiList length error", zap.Any("err", "chiList length error")) loger.Error("chiList length error", zap.Any("err", "chiList length error"))
} }
@@ -226,7 +226,7 @@ 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 { if len(diskEndSector) < 2 {
loger.Error("diskEndSector length error", zap.Any("err", "diskEndSector length error")) loger.Error("diskEndSector length error", zap.Any("err", "diskEndSector length error"))
@@ -242,7 +242,7 @@ func (d *diskService) GetDiskInfo(path string) model.LSBLKModel {
} }
func (d *diskService) MountDisk(path, volume string) { 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) fmt.Print(r)
} }
@@ -264,7 +264,7 @@ func (d *diskService) DeleteMountPoint(path, mountPoint string) {
d.db.Where("path = ? AND mount_point = ?", path, mountPoint).Delete(&model2.SerialDisk{}) 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 { func (d *diskService) GetSerialAll() []model2.SerialDisk {

View File

@@ -45,7 +45,7 @@ import (
type DockerService interface { type DockerService interface {
DockerPullImage(imageName string, icon, name string) error DockerPullImage(imageName string, icon, name string) error
IsExistImage(imageName string) bool 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) DockerContainerCopyCreate(info *types.ContainerJSON) (containerId string, err error)
DockerContainerStart(name string) error DockerContainerStart(name string) error
DockerContainerStats(name string) (string, error) DockerContainerStats(name string) (string, error)
@@ -376,9 +376,9 @@ func (ds *dockerService) DockerContainerCopyCreate(info *types.ContainerJSON) (c
//param mapPort 容器主端口映射到外部的端口 //param mapPort 容器主端口映射到外部的端口
//param tcp 容器其他tcp端口 //param tcp 容器其他tcp端口
//param udp 容器其他udp端口 //param udp 容器其他udp端口
func (ds *dockerService) DockerContainerCreate(imageName string, m model.CustomizationPostData, net string) (containerId string, err error) { func (ds *dockerService) DockerContainerCreate(imageName string, m model.CustomizationPostData) (containerId string, err error) {
if len(net) == 0 { if len(m.NetworkModel) == 0 {
net = "bridge" m.NetworkModel = "bridge"
} }
cli, err := client2.NewClientWithOpts(client2.FromEnv) cli, err := client2.NewClientWithOpts(client2.FromEnv)
@@ -402,7 +402,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
tContainer, _ := strconv.Atoi(portMap.ContainerPort) tContainer, _ := strconv.Atoi(portMap.ContainerPort)
if tContainer > 0 { if tContainer > 0 {
ports[nat.Port(portMap.ContainerPort+"/tcp")] = struct{}{} 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}} portMaps[nat.Port(portMap.ContainerPort+"/tcp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
} }
} }
@@ -411,7 +411,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
tContainer, _ := strconv.Atoi(portMap.ContainerPort) tContainer, _ := strconv.Atoi(portMap.ContainerPort)
if tContainer > 0 { if tContainer > 0 {
ports[nat.Port(portMap.ContainerPort+"/tcp")] = struct{}{} 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}} portMaps[nat.Port(portMap.ContainerPort+"/tcp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
} }
} }
@@ -419,7 +419,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
uContainer, _ := strconv.Atoi(portMap.ContainerPort) uContainer, _ := strconv.Atoi(portMap.ContainerPort)
if uContainer > 0 { if uContainer > 0 {
ports[nat.Port(portMap.ContainerPort+"/udp")] = struct{}{} 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}} portMaps[nat.Port(portMap.ContainerPort+"/udp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
} }
} }
@@ -428,7 +428,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
uContainer, _ := strconv.Atoi(portMap.ContainerPort) uContainer, _ := strconv.Atoi(portMap.ContainerPort)
if uContainer > 0 { if uContainer > 0 {
ports[nat.Port(portMap.ContainerPort+"/udp")] = struct{}{} 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}} portMaps[nat.Port(portMap.ContainerPort+"/udp")] = []nat.PortBinding{{HostPort: portMap.CommendPort}}
} }
} }
@@ -438,13 +438,14 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
var envArr []string var envArr []string
var showENV []string var showENV []string
showENV = append(showENV, "casaos")
for _, e := range m.Envs { for _, e := range m.Envs {
showENV = append(showENV, e.Name)
if strings.HasPrefix(e.Value, "$") { if strings.HasPrefix(e.Value, "$") {
envArr = append(envArr, e.Name+"="+env_helper.ReplaceDefaultENV(e.Value, MyService.System().GetTimeZone())) envArr = append(envArr, e.Name+"="+env_helper.ReplaceDefaultENV(e.Value, MyService.System().GetTimeZone()))
continue continue
} }
if len(e.Value) > 0 { if len(e.Value) > 0 {
showENV = append(showENV, e.Name)
if e.Value == "port_map" { if e.Value == "port_map" {
envArr = append(envArr, e.Name+"="+m.PortMap) envArr = append(envArr, e.Name+"="+m.PortMap)
continue continue
@@ -539,8 +540,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
config.Labels["show_env"] = strings.Join(showENV, ",") config.Labels["show_env"] = strings.Join(showENV, ",")
config.Labels["protocol"] = m.Protocol config.Labels["protocol"] = m.Protocol
config.Labels["host"] = m.Host config.Labels["host"] = m.Host
//config.Labels["order"] = strconv.Itoa(MyService.App().GetCasaOSCount() + 1) hostConfig := &container.HostConfig{Resources: res, Mounts: volumes, RestartPolicy: rp, NetworkMode: container.NetworkMode(m.NetworkModel), Privileged: m.Privileged, CapAdd: m.CapAdd}
hostConfig := &container.HostConfig{Resources: res, Mounts: volumes, RestartPolicy: rp, NetworkMode: container.NetworkMode(net), Privileged: m.Privileged, CapAdd: m.CapAdd}
//if net != "host" { //if net != "host" {
config.ExposedPorts = ports config.ExposedPorts = ports
hostConfig.PortBindings = portMaps hostConfig.PortBindings = portMaps
@@ -549,7 +549,7 @@ func (ds *dockerService) DockerContainerCreate(imageName string, m model.Customi
containerDb, err := cli.ContainerCreate(context.Background(), containerDb, err := cli.ContainerCreate(context.Background(),
config, config,
hostConfig, 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, nil,
m.Label) m.Label)
if err != nil { if err != nil {

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2021-12-20 14:15:46 * @Date: 2021-12-20 14:15:46
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-06-08 15:46:36 * @LastEditTime: 2022-06-16 16:47:46
* @FilePath: /CasaOS/service/file.go * @FilePath: /CasaOS/service/file.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -21,6 +21,8 @@ import (
"github.com/IceWhaleTech/CasaOS/model" "github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file" "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"go.uber.org/zap"
) )
var FileQueue sync.Map var FileQueue sync.Map
@@ -87,26 +89,36 @@ func FileOperate(k string) {
if temp.ProcessedSize > 0 { if temp.ProcessedSize > 0 {
return return
} }
for _, v := range temp.Item { for i := 0; i < len(temp.Item); i++ {
v := temp.Item[i]
if temp.Type == "move" { if temp.Type == "move" {
lastPath := v.From[strings.LastIndex(v.From, "/")+1:] lastPath := v.From[strings.LastIndex(v.From, "/")+1:]
if !file.CheckNotExist(temp.To + "/" + lastPath) { if !file.CheckNotExist(temp.To + "/" + lastPath) {
continue if temp.Style == "skip" {
temp.Item[i].Finished = true
continue
} else {
os.RemoveAll(temp.To + "/" + lastPath)
}
} }
err := os.Rename(v.From, temp.To+"/"+lastPath) err := os.Rename(v.From, temp.To+"/"+lastPath)
if err != nil { if err != nil {
loger.Debug("file move error", zap.Any("err", err))
continue continue
} }
} else if temp.Type == "copy" { } else if temp.Type == "copy" {
err := file.CopyDir(v.From, temp.To) err := file.CopyDir(v.From, temp.To, temp.Style)
if err != nil { if err != nil {
continue continue
} }
} else { } else {
continue continue
} }
}
}
temp.Finished = true
FileQueue.Store(k, temp)
} }
func ExecOpFile() { func ExecOpFile() {

View File

@@ -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}
}

View File

@@ -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"
}

View File

@@ -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:"-"`
}

View File

@@ -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"
}

View File

@@ -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"
}

View File

@@ -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
View 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"
}

View File

@@ -12,7 +12,6 @@ import (
"github.com/ambelovsky/gosf" "github.com/ambelovsky/gosf"
socketio "github.com/googollee/go-socket.io" socketio "github.com/googollee/go-socket.io"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/shirou/gopsutil/v3/mem"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -31,18 +30,45 @@ type NotifyServer interface {
SendUninstallAppBySocket(app notify.Application) SendUninstallAppBySocket(app notify.Application)
SendNetInfoBySocket(netList []model2.IOCountersStat) SendNetInfoBySocket(netList []model2.IOCountersStat)
SendCPUInfoBySocket(cpu map[string]interface{}) SendCPUInfoBySocket(cpu map[string]interface{})
SendMemInfoBySocket(mem *mem.VirtualMemoryStat) SendMemInfoBySocket(mem map[string]interface{})
SendUSBInfoBySocket(list []model2.DriveUSB) SendUSBInfoBySocket(list []model2.DriveUSB)
SendDiskInfoBySocket(disk model2.Summary) SendDiskInfoBySocket(disk model2.Summary)
SendPersonStatusBySocket(status notify.Person) SendPersonStatusBySocket(status notify.Person)
SendFileOperateNotify(nowSend bool) SendFileOperateNotify(nowSend bool)
SendInstallAppBySocket(app notify.Application) 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 { type notifyServer struct {
db *gorm.DB 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 // Send periodic broadcast messages
func (i *notifyServer) SendFileOperateNotify(nowSend bool) { func (i *notifyServer) SendFileOperateNotify(nowSend bool) {
@@ -94,7 +120,7 @@ func (i *notifyServer) SendFileOperateNotify(nowSend bool) {
task.Status = "PROCESSING" task.Status = "PROCESSING"
} }
if temp.ProcessedSize >= temp.TotalSize { if temp.Finished || temp.ProcessedSize >= temp.TotalSize {
task.Finished = true task.Finished = true
task.Status = "FINISHED" task.Status = "FINISHED"
@@ -160,7 +186,8 @@ func (i *notifyServer) SendFileOperateNotify(nowSend bool) {
} else { } else {
task.Status = "PROCESSING" task.Status = "PROCESSING"
} }
if temp.ProcessedSize >= temp.TotalSize { if temp.Finished || temp.ProcessedSize >= temp.TotalSize {
task.Finished = true task.Finished = true
task.Status = "FINISHED" task.Status = "FINISHED"
FileQueue.Delete(v) FileQueue.Delete(v)
@@ -245,7 +272,7 @@ func (i *notifyServer) SendUSBInfoBySocket(list []model2.DriveUSB) {
NotifyMsg <- notify NotifyMsg <- notify
} }
func (i *notifyServer) SendMemInfoBySocket(mem *mem.VirtualMemoryStat) { func (i *notifyServer) SendMemInfoBySocket(mem map[string]interface{}) {
body := make(map[string]interface{}) body := make(map[string]interface{})
body["data"] = mem body["data"] = mem

View File

@@ -198,11 +198,11 @@ func ProcessingContent(stream quic.Stream) {
if m.Data.(string) == "" || m.Data.(string) == "/" { if m.Data.(string) == "" || m.Data.(string) == "/" {
for _, v := range config.FileSettingInfo.ShareDir { for _, v := range config.FileSettingInfo.ShareDir {
//tempList := MyService.ZiMa().GetDirPath(v) //tempList := MyService.ZiMa().GetDirPath(v)
temp := MyService.ZiMa().GetDirPathOne(v) temp := MyService.System().GetDirPathOne(v)
list = append(list, temp) list = append(list, temp)
} }
} else { } else {
list = MyService.ZiMa().GetDirPath(m.Data.(string)) list = MyService.System().GetDirPath(m.Data.(string))
} }
} else { } else {
list = []model.Path{} list = []model.Path{}

View File

@@ -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
}

View File

@@ -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{}
}

View File

@@ -16,20 +16,14 @@ var SocketRun bool
type Repository interface { type Repository interface {
App() AppService App() AppService
DDNS() DDNSService
User() UserService User() UserService
Docker() DockerService Docker() DockerService
//Redis() RedisService
ZiMa() ZiMaService
Casa() CasaService Casa() CasaService
Disk() DiskService Disk() DiskService
Notify() NotifyServer Notify() NotifyServer
ShareDirectory() ShareDirService
Task() TaskService
Rely() RelyService Rely() RelyService
System() SystemService System() SystemService
Shortcuts() ShortcutsService Shortcuts() ShortcutsService
Search() SearchService
Person() PersonService Person() PersonService
Friend() FriendService Friend() FriendService
Download() DownloadService Download() DownloadService
@@ -39,47 +33,37 @@ type Repository interface {
func NewService(db *gorm.DB) Repository { func NewService(db *gorm.DB) Repository {
return &store{ return &store{
app: NewAppService(db), app: NewAppService(db),
user: NewUserService(), user: NewUserService(db),
docker: NewDockerService(), docker: NewDockerService(),
//redis: NewRedisService(rp), casa: NewCasaService(),
zima: NewZiMaService(), disk: NewDiskService(db),
casa: NewCasaService(), notify: NewNotifyService(db),
disk: NewDiskService(db), rely: NewRelyService(db),
notify: NewNotifyService(db), system: NewSystemService(),
shareDirectory: NewShareDirService(db), shortcuts: NewShortcutsService(db),
task: NewTaskService(db), person: NewPersonService(db),
rely: NewRelyService(db), friend: NewFriendService(db),
system: NewSystemService(), download: NewDownloadService(db),
shortcuts: NewShortcutsService(db), downrecord: NewDownRecordService(db),
search: NewSearchService(),
person: NewPersonService(db),
friend: NewFriendService(db),
download: NewDownloadService(db),
downrecord: NewDownRecordService(db),
} }
} }
type store struct { type store struct {
db *gorm.DB db *gorm.DB
app AppService app AppService
ddns DDNSService user UserService
user UserService docker DockerService
docker DockerService casa CasaService
zima ZiMaService disk DiskService
casa CasaService notify NotifyServer
disk DiskService rely RelyService
notify NotifyServer system SystemService
shareDirectory ShareDirService shortcuts ShortcutsService
task TaskService person PersonService
rely RelyService friend FriendService
system SystemService download DownloadService
shortcuts ShortcutsService downrecord DownRecordService
search SearchService
person PersonService
friend FriendService
download DownloadService
downrecord DownRecordService
} }
func (c *store) DownRecord() DownRecordService { func (c *store) DownRecord() DownRecordService {
@@ -113,10 +97,6 @@ func (c *store) App() AppService {
return c.app return c.app
} }
func (c *store) DDNS() DDNSService {
return c.ddns
}
func (c *store) User() UserService { func (c *store) User() UserService {
return c.user return c.user
} }
@@ -125,9 +105,6 @@ func (c *store) Docker() DockerService {
return c.docker return c.docker
} }
func (c *store) ZiMa() ZiMaService {
return c.zima
}
func (c *store) Casa() CasaService { func (c *store) Casa() CasaService {
return c.casa return c.casa
} }
@@ -135,12 +112,3 @@ func (c *store) Casa() CasaService {
func (c *store) Disk() DiskService { func (c *store) Disk() DiskService {
return c.disk 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
}

View File

@@ -1,324 +0,0 @@
package service
import (
"os"
"strconv"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/service/model"
"go.uber.org/zap"
"gorm.io/gorm"
)
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
}
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 {
loger.Error("Failed to create file", zap.Any("err", err))
} 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) ShareDirService {
return &shareDirService{db: db}
}

View File

@@ -5,13 +5,20 @@ import (
"io/ioutil" "io/ioutil"
net2 "net" net2 "net"
"os" "os"
"path/filepath"
"runtime"
"strconv" "strconv"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
command2 "github.com/IceWhaleTech/CasaOS/pkg/utils/command" 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/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/shirou/gopsutil/v3/cpu" "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/mem"
"github.com/shirou/gopsutil/v3/net" "github.com/shirou/gopsutil/v3/net"
) )
@@ -26,22 +33,155 @@ type SystemService interface {
GetTimeZone() string GetTimeZone() string
UpdateUSBAutoMount(state string) UpdateUSBAutoMount(state string)
ExecUSBAutoMountShell(state string) ExecUSBAutoMountShell(state string)
UpAppOrderFile(str string) UpAppOrderFile(str, id string)
GetAppOrderFile() []byte GetAppOrderFile(id string) []byte
GetNet(physics bool) []string GetNet(physics bool) []string
GetNetInfo() []net.IOCountersStat GetNetInfo() []net.IOCountersStat
GetCpuCoreNum() int GetCpuCoreNum() int
GetCpuPercent() float64 GetCpuPercent() float64
GetMemInfo() *mem.VirtualMemoryStat 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 { type systemService struct {
log loger.OLog
} }
func (c *systemService) GetMemInfo() *mem.VirtualMemoryStat { 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, _ := mem.VirtualMemory()
memInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", memInfo.UsedPercent), 64) memInfo.UsedPercent, _ = strconv.ParseFloat(fmt.Sprintf("%.1f", memInfo.UsedPercent), 64)
return memInfo 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 { func (c *systemService) GetCpuPercent() float64 {
@@ -64,34 +204,33 @@ func (c *systemService) GetNet(physics bool) []string {
if physics { if physics {
t = "2" t = "2"
} }
return command2.ExecResultStrArray("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;GetNetCard " + t) return command2.ExecResultStrArray("source " + config.AppInfo.ShellPath + "/helper.sh ;GetNetCard " + t)
} }
func (s *systemService) UpdateSystemVersion(version string) { 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(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)) //s.log.Error(command2.ExecResultStr(config.AppInfo.ProjectPath + "/shell/tool.sh -r " + version))
} }
func (s *systemService) UpdateAssist() { 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 { 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) { func (s *systemService) ExecUSBAutoMountShell(state string) {
if state == "False" { 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 { } 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 { 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) { func (s *systemService) UpSystemConfig(str string, widget string) {
if len(str) > 0 && str != config.SystemConfigInfo.ConfigStr { if len(str) > 0 && str != config.SystemConfigInfo.ConfigStr {
@@ -104,11 +243,11 @@ func (s *systemService) UpSystemConfig(str string, widget string) {
} }
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
} }
func (s *systemService) UpAppOrderFile(str string) { func (s *systemService) UpAppOrderFile(str, id string) {
file.WriteToPath([]byte(str), config.AppInfo.ProjectPath+"/conf", "app_order.json") file.WriteToPath([]byte(str), config.AppInfo.DBPath+"/"+id, "app_order.json")
} }
func (s *systemService) GetAppOrderFile() []byte { func (s *systemService) GetAppOrderFile(id string) []byte {
return file.ReadFullFile(config.AppInfo.ProjectPath + "/conf/app_order.json") return file.ReadFullFile(config.AppInfo.UserDataPath + "/" + id + "/app_order.json")
} }
func (s *systemService) UpdateUSBAutoMount(state string) { func (s *systemService) UpdateUSBAutoMount(state string) {
config.ServerInfo.USBAutoMount = state config.ServerInfo.USBAutoMount = state
@@ -123,7 +262,10 @@ func (s *systemService) UpSystemPort(port string) {
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath) config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
} }
func (s *systemService) GetCasaOSLogs(lineNumber int) string { 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 { if err != nil {
return err.Error() return err.Error()
} }

View File

@@ -1,144 +0,0 @@
package service
import (
json2 "encoding/json"
"strconv"
"github.com/IceWhaleTech/CasaOS/pkg/config"
httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
"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
}
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) TaskService {
return &taskService{db: db}
}

View File

@@ -186,7 +186,7 @@ func ReadContent(stream quic.Stream) {
fmt.Println(err) fmt.Println(err)
time.Sleep(time.Second * 1) time.Sleep(time.Second * 1)
for k, v := range CancelList { for k, v := range CancelList {
tempPath := config.AppInfo.RootPath + "/temp" + "/" + v tempPath := config.AppInfo.TempPath + "/" + v
fmt.Println(file.RMDir(tempPath)) fmt.Println(file.RMDir(tempPath))
delete(CancelList, k) delete(CancelList, k)
} }
@@ -445,7 +445,7 @@ func SaveFile(m model.MessageModel, stream quic.Stream) bool {
fmt.Println("hash不匹配", hash, dataModel.Hash) fmt.Println("hash不匹配", hash, dataModel.Hash)
return false return false
} }
tempPath := config.AppInfo.RootPath + "/temp" + "/" + m.UUId tempPath := config.AppInfo.TempPath + "/" + m.UUId
file.IsNotExistMkDir(tempPath) file.IsNotExistMkDir(tempPath)
filepath := tempPath + "/" + strconv.Itoa(dataModel.Index) filepath := tempPath + "/" + strconv.Itoa(dataModel.Index)
_, err = os.Stat(filepath) _, err = os.Stat(filepath)

View File

@@ -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 package service
import ( import (
@@ -6,18 +16,75 @@ import (
"os" "os"
"github.com/IceWhaleTech/CasaOS/pkg/config" "github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/service/model"
"gorm.io/gorm"
) )
type UserService interface { type UserService interface {
SetUser(username, pwd, token, email, desc, nickName string) error SetUser(username, pwd, token, email, desc, nickName string) error
UpLoadFile(file multipart.File, name 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 { if len(username) > 0 {
config.Cfg.Section("user").Key("UserName").SetValue(username) config.Cfg.Section("user").Key("UserName").SetValue(username)
config.UserInfo.UserName = 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) out, _ := os.OpenFile(url, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
defer out.Close() defer out.Close()
io.Copy(out, file) io.Copy(out, file)
@@ -53,6 +120,6 @@ func (c *user) UpLoadFile(file multipart.File, url string) error {
} }
//获取用户Service //获取用户Service
func NewUserService() UserService { func NewUserService(db *gorm.DB) UserService {
return &user{} return &userService{db: db}
} }

View File

@@ -1,215 +0,0 @@
package service
import (
"fmt"
"io/ioutil"
"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/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"
)
//系统信息
type ZiMaService interface {
GetDiskInfo() *disk.UsageStat
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) GetCpuInfo() []cpu.InfoStat {
info, _ := cpu.Info()
return info
}
//获取硬盘详情
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
}
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)
}
//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
// }
// }
// }
// }

View File

@@ -1,35 +1,3 @@
#!/bin/bash #!/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
View 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

View File

@@ -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

268
shell/update.sh Normal file
View File

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

View File

@@ -2,7 +2,7 @@
* @Author: LinkLeong link@icewhale.com * @Author: LinkLeong link@icewhale.com
* @Date: 2022-02-17 18:53:22 * @Date: 2022-02-17 18:53:22
* @LastEditors: LinkLeong * @LastEditors: LinkLeong
* @LastEditTime: 2022-06-02 20:40:36 * @LastEditTime: 2022-07-01 15:15:09
* @FilePath: /CasaOS/types/system.go * @FilePath: /CasaOS/types/system.go
* @Description: * @Description:
* @Website: https://www.casaos.io * @Website: https://www.casaos.io
@@ -10,6 +10,6 @@
*/ */
package types package types
const CURRENTVERSION = "0.3.2" const CURRENTVERSION = "0.3.3"
const BODY = "<li></li>" const BODY = ""

View File

@@ -1,11 +0,0 @@
<svg width="72" height="72" viewBox="0 0 72 72" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect opacity="0.32" x="0.435625" y="0.435625" width="71.1288" height="71.1288" rx="7.56437" fill="white" stroke="url(#paint0_linear_812_2050)" stroke-width="0.87125"/>
<path d="M36.0606 22L36.0239 50" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M22 36H50" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<defs>
<linearGradient id="paint0_linear_812_2050" x1="77.6757" y1="64.5405" x2="35.9839" y2="53.5747" gradientUnits="userSpaceOnUse">
<stop stop-color="#CBEFFF" stop-opacity="0.16"/>
<stop offset="1" stop-color="white" stop-opacity="0"/>
</linearGradient>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 752 B

View File

@@ -1,25 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 18.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve">
<g>
<g>
<g>
<path fill="#A4C639" d="M32,0c17.7,0,32,14.3,32,32S49.7,64,32,64S0,49.7,0,32S14.3,0,32,0z"/>
</g>
</g>
<g>
<g>
<path fill="#FFFFFF" d="M16.6,24.6c-1.4,0-2.6,1.2-2.6,2.6L14,38c0,1.4,1.2,2.6,2.6,2.6c1.5,0,2.6-1.2,2.6-2.6l0-10.9
C19.3,25.7,18.1,24.6,16.6,24.6 M37.8,14.8l1.8-3.3c0.1-0.2,0-0.4-0.1-0.5c-0.2-0.1-0.4,0-0.5,0.1l-1.9,3.3
c-1.6-0.7-3.3-1.1-5.1-1.1c-1.8,0-3.6,0.4-5.1,1.1L25,11.2C24.9,11,24.7,11,24.5,11c-0.2,0.1-0.2,0.3-0.1,0.5l1.8,3.3
c-3.6,1.8-6,5.3-6,9.3l23.6,0C43.8,20.2,41.4,16.7,37.8,14.8 M26.6,19.9c-0.5,0-1-0.4-1-1c0-0.5,0.4-1,1-1c0.5,0,1,0.4,1,1
C27.6,19.5,27.2,19.9,26.6,19.9 M37.4,19.9c-0.5,0-1-0.4-1-1c0-0.5,0.4-1,1-1c0.5,0,1,0.4,1,1C38.4,19.5,37.9,19.9,37.4,19.9
M20.3,25.1l0,16.8c0,1.5,1.3,2.8,2.8,2.8l1.9,0l0,5.7c0,1.4,1.2,2.6,2.6,2.6c1.5,0,2.6-1.2,2.6-2.6l0-5.7l3.5,0l0,5.7
c0,1.4,1.2,2.6,2.6,2.6c1.5,0,2.6-1.2,2.6-2.6l0-5.7l1.9,0c1.5,0,2.8-1.2,2.8-2.8l0-16.8L20.3,25.1z M50,27.2
c0-1.4-1.2-2.6-2.6-2.6c-1.4,0-2.6,1.2-2.6,2.6l0,10.9c0,1.4,1.2,2.6,2.6,2.6c1.4,0,2.6-1.2,2.6-2.6L50,27.2z"/>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 64 64" style="enable-background:new 0 0 64 64;" xml:space="preserve">
<style type="text/css">
.st0{fill:#F4F4F4;}
.st1{opacity:0.1;fill-rule:evenodd;clip-rule:evenodd;fill:url(#SVGID_1_);enable-background:new ;}
.st2{fill:#999999;}
</style>
<g id="图层_1">
<g transform="scale(.26458)">
<path class="st0" d="M49.1,15.1h143.6c10.4,0,18.9,8.5,18.9,18.9v173.9c0,10.4-8.5,18.9-18.9,18.9H49.1
c-10.4,0-18.9-8.5-18.9-18.9V34C30.2,23.6,38.7,15.1,49.1,15.1z"/>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="-957.3084" y1="2609.5137" x2="-955.1654" y2="2607.3706" gradientTransform="matrix(2.3333 0 0 -2.3333 2411.3325 6281.5693)">
<stop offset="0" style="stop-color:#000000"/>
<stop offset="1" style="stop-color:#000000;stop-opacity:0"/>
</linearGradient>
<path class="st1" d="M211.7,173.9l-52.9,52.9h34c10.5,0,18.9-8.4,18.9-18.9V173.9z"/>
</g>
</g>
<g id="图层_2">
<path class="st2" d="M41.1,31.4c0-4.2,3.4-6.2,3.6-6.3c-2-2.9-5-3.3-6.1-3.3c-2.6-0.3-5.1,1.5-6.4,1.5c-1.3,0-3.3-1.5-5.5-1.4
c-2.8,0-5.4,1.6-6.9,4.2c-2.9,5.1-0.8,12.6,2.1,16.8c1.4,2,3.1,4.3,5.3,4.2c2.1-0.1,2.9-1.4,5.4-1.4c2.5,0,3.3,1.4,5.5,1.3
c2.3,0,3.7-2.1,5.1-4.1c1.6-2.3,2.3-4.6,2.3-4.7C45.5,38.1,41.1,36.4,41.1,31.4L41.1,31.4z M36.9,19c1.2-1.4,1.9-3.4,1.7-5.3
c-1.7,0.1-3.7,1.1-4.9,2.5c-1.1,1.2-2,3.2-1.8,5.1C33.8,21.5,35.7,20.5,36.9,19L36.9,19z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 449 KiB

Some files were not shown because too many files have changed in this diff Show More