Compare commits

...

263 Commits

Author SHA1 Message Date
link
6bd41ad016 fix bug (#198) 2022-05-17 12:57:34 +08:00
link
05425d638f Update CHANGELOG.md 2022-05-16 20:45:38 +08:00
link
bd5a2e35d4 update ui (#192) 2022-05-16 15:57:54 +08:00
link
123e7e8758 Merge pull request #183 from IceWhaleTech/dev
Update UI
2022-05-13 20:27:53 +08:00
LinkLeong
1ec3e2e9fb Update UI 2022-05-13 20:27:26 +08:00
link
0719c3cc0c Merge pull request #182 from IceWhaleTech/dev
update api url
2022-05-13 19:11:28 +08:00
LinkLeong
0a4ceb7c4c update api url 2022-05-13 19:09:35 +08:00
link
655f59f00a Merge pull request #181 from IceWhaleTech/dev
Dev
2022-05-13 18:56:35 +08:00
LinkLeong
5289f471d6 Update .gitignore 2022-05-13 18:55:52 +08:00
LinkLeong
59597befb6 delete github.com 2022-05-13 18:55:34 +08:00
link
df2477a12f Merge pull request #179 from IceWhaleTech/dev
Dev
2022-05-13 18:21:44 +08:00
LinkLeong
b709abe682 Merge branch 'main' into dev 2022-05-13 18:15:56 +08:00
LinkLeong
d0f3dc806e New Feature
- [Apps] This is a feature that has been highly requested by the community. Import the original Docker application into CasaOS. Now it's easy to import with just a few clicks!
- [Apps] App list supports a custom sorting function! You can arrange apps in different orders by dragging the icons.
- [Apps] App custom installation supports Docker Compose configuration import in YAML format.
- [Files] Added thumbnail preview function for image files.
- [Connect] Multiple CasaConenct devices in the LAN will be transmitted through the LAN network.
- [System] Added a switch for auto-mounting USB disk devices.

🎈 Enhancement
- [System] Optimized the system update alert, you will see the new version update log from the next version.
- [Apps] Added live preview for icons in custom installed apps.
- [Apps] Optimized the input of WebUI.
- [Files] Completely updated the image preview, now it supports switching all images in the same folder, as well as dragging, zooming, rotating and resetting.
- [Widgets] Added color levels for CPU and RAM charts.
- [Conenct] Optimized the display of the right-click menu of the Connect friends list.

🎈 Changed
- [Files] Change the initial display directory to /DATA

🐞 Fixed
- [System] Fixed an issue with Raspberry Pi devices failing to boot using USB disks. (Achieved by disabling USB disk auto-mount)
- [Apps] Fixed the issue that some Docker CLI commands failed to import.
- [Apps] Fixed the issue that the app is not easily recognized in /DATA/AppData directory and docker command line after installation, it will be shown as the app name. (Newly installed apps only)
- [Apps] Fixed the issue that Pi-hole cannot be launched after installation in the app store.
- [Apps] Fixed the issue that apps cannot be updated with WatchTower.
- [Files] Fixed the issue that when there is an upload task, the task status is lost after closing Files.
2022-05-13 18:12:26 +08:00
LinkLeong
92d085acf9 update changelog 2022-05-05 13:46:55 +08:00
link
20dbae21c8 Update github.go 2022-04-24 17:53:57 +08:00
link
9258cb4b9e Merge pull request #151 from IceWhaleTech/dev
Update UI
2022-04-08 14:44:28 +08:00
link
d9794851f9 Update UI 2022-04-08 14:44:02 +08:00
link
1fcb530ff2 Merge pull request #149 from IceWhaleTech/dev
Update UI
2022-04-07 16:20:19 +08:00
link
364d411438 Update UI 2022-04-07 16:17:47 +08:00
link
0dacc5db12 Merge pull request #141 from igorpecovnik/patch-1
Tested on Rockpro64, Odroid C2, Neo2, Cubox-i, amd64
2022-04-06 12:14:38 +08:00
link
fcbff194d2 Merge branch 'main' into patch-1 2022-04-06 12:14:31 +08:00
link
04e93b0e3c Merge pull request #138 from alvarosamudio/main
add a new OS to systems
2022-04-06 12:12:07 +08:00
link
2eff7fa8bc Merge pull request #148 from IceWhaleTech/dev
Dev
2022-04-06 12:11:39 +08:00
link
dd0645ee0f Add CasaConnect function 2022-04-06 12:10:51 +08:00
Igor Pečovnik
c93aa6286e Tested on Rockpro64, Odroid C2, Neo2, Cubox-i, x86
Basically it should work on all.
https://www.armbian.com/download/
https://docs.armbian.com/#what-is-the-difference-between-armbian-and-debianubuntu
2022-03-29 15:57:16 +02:00
Alvaro Samudio
bf7b32309f add Elementary OS 6.1 Jólnir to systems 2022-03-25 14:49:21 +00:00
Alvaro Samudio
cd779448ce add Deepin to systems 2022-03-25 14:41:05 +00:00
link
c3b2c1d599 Merge branch 'main' into dev 2022-03-18 11:41:04 +08:00
link
b7949e100f Merge Branches 2022-03-18 11:40:38 +08:00
link
80d24570d6 Merge pull request #130 from IceWhaleTech/Adding-ipv6-Support
fixed
2022-03-18 11:31:05 +08:00
link
539b72a388 fixed 2022-03-18 11:30:06 +08:00
link
a7d15a896e Need to fix bugs 2022-03-18 11:13:07 +08:00
link
9796c5aad7 prepare for test 2022-03-16 15:41:14 +08:00
link
892cd99eb3 Add some acquaintance network interface 2022-03-11 18:01:09 +08:00
link
02cb4cd392 Merge pull request #126 from IceWhaleTech/dev
fixed file upload bug
2022-03-10 16:26:00 +08:00
link
9213f9e379 fixed file upload bug 2022-03-10 16:25:33 +08:00
link
4473056d5c Merge pull request #125 from IceWhaleTech/dev
upload file manage
2022-03-10 13:41:15 +08:00
link
07e96511cd upload file manage 2022-03-10 13:40:42 +08:00
link
ce1dc52bc2 Merge pull request #123 from IceWhaleTech/dev
update file
2022-03-09 19:44:47 +08:00
link
d890b16644 update file 2022-03-09 19:44:08 +08:00
link
5737936318 Merge pull request #122 from IceWhaleTech/dev
Dev
2022-03-09 16:38:18 +08:00
link
33acfababd new file manager
Added CasaOS own file manager, now you can browse, upload, download files from the system, even edit code online, preview photos and videos through it. It will appear in the first position of Apps.
Added CPU core count display and memory capacity display.
2022-03-09 16:37:03 +08:00
link
28c1a52171 Determine the hole punching technique 2022-02-28 14:14:39 +08:00
link
892eef424c Merge branch 'main' into dev 2022-02-18 19:14:30 +08:00
link
f3c73ba79b Update usb-mount.sh 2022-02-18 19:14:11 +08:00
link
c6928c333d Add websocket 2022-02-18 19:06:03 +08:00
link
63c6c2cebb Merge pull request #111 from IceWhaleTech/dev
Delete CasaOS-linux-amd64
2022-02-17 19:22:14 +08:00
link
6cba025679 Delete CasaOS-linux-amd64 2022-02-17 19:21:19 +08:00
link
d25b93c972 Merge pull request #110 from IceWhaleTech/dev
Dev
2022-02-17 18:53:54 +08:00
link
b14861703c Merge branch 'dev' of ssh://github.com/IceWhaleTech/CasaOS into dev 2022-02-17 18:53:29 +08:00
link
32604225ce update ui 2022-02-17 18:52:14 +08:00
link
f623b29c38 Merge pull request #109 from IceWhaleTech/dev
Dev
2022-02-17 18:47:44 +08:00
link
94ae6ee8ec Merge branch 'main' into dev 2022-02-17 18:47:36 +08:00
link
5115bf72e1 update desc 2022-02-17 18:44:51 +08:00
link
e1a928cd78 Fixed issues 2022-02-17 18:43:25 +08:00
link
3977519c43 Update assist.sh 2022-01-30 11:21:24 +08:00
link
2f87834ac9 Merge pull request #93 from IceWhaleTech/dev
Update route.go
2022-01-28 16:25:01 +08:00
link
53335012d8 Update route.go 2022-01-28 16:24:28 +08:00
link
9d6302f7e3 Merge pull request #92 from IceWhaleTech/dev
Update UI
2022-01-28 16:14:59 +08:00
link
20950e2a60 Update UI 2022-01-28 16:14:35 +08:00
link
0e0e507f8f Merge pull request #91 from IceWhaleTech/dev
update ui
2022-01-28 15:35:15 +08:00
link
46e14617b6 update ui 2022-01-28 15:34:32 +08:00
link
903c73fafb Merge pull request #90 from IceWhaleTech/dev
update web
2022-01-28 14:33:40 +08:00
link
42a56df4a5 update web 2022-01-28 14:32:49 +08:00
link
493dc5c032 Merge pull request #89 from IceWhaleTech/dev
Compatible with more types of disks
2022-01-28 14:06:58 +08:00
link
9a73bc2a18 Compatible with more types of disks
Add usb display
2022-01-28 14:06:27 +08:00
link
55a9acd9f6 Merge pull request #85 from IceWhaleTech/dev
Apply multilingual support
2022-01-26 18:51:14 +08:00
link
d060968b7a Apply multilingual support 2022-01-26 18:50:34 +08:00
link
88a7f53130 Merge pull request #82 from IceWhaleTech/dev
Dev
2022-01-26 11:33:33 +08:00
link
26e5b18a5d Merge branch 'dev' of ssh://github.com/IceWhaleTech/CasaOS into dev 2022-01-26 11:33:02 +08:00
link
011ace96f6 update ui 2022-01-26 11:32:57 +08:00
link
5c00655d14 Merge pull request #81 from IceWhaleTech/dev
Dev
2022-01-26 10:46:50 +08:00
link
eb36c262db Merge branch 'main' into dev 2022-01-26 10:46:43 +08:00
link
29d1861545 Merge branch 'main' into dev 2022-01-26 10:45:11 +08:00
link
3c9b410693 update dependency 2022-01-26 10:44:55 +08:00
link
4c3b41433b Update assist.sh 2022-01-24 22:06:31 +08:00
link
1fd13668c0 Merge pull request #78 from IceWhaleTech/dev
Dev
2022-01-24 17:22:48 +08:00
link
d1ab7261a6 Update usb-mount.sh 2022-01-24 17:21:43 +08:00
link
0fc65bcb3a update mount path 2022-01-24 17:08:28 +08:00
link
f1ce8bfd99 Merge pull request #77 from IceWhaleTech/dev
update disk
2022-01-24 11:19:47 +08:00
link
3f472f1864 update disk 2022-01-24 11:19:04 +08:00
link
229d94cae7 Merge pull request #74 from IceWhaleTech/dev
Fixed Storage Panel
2022-01-21 17:50:44 +08:00
link
c28e1bbf93 Fixed Storage Panel 2022-01-21 17:50:12 +08:00
link
a840029000 Merge pull request #73 from IceWhaleTech/dev
update UI
2022-01-20 18:45:54 +08:00
link
aad2646cf2 Merge branch 'dev' of ssh://github.com/IceWhaleTech/CasaOS into dev 2022-01-20 18:45:17 +08:00
link
ca1f8ad73e Update UI 2022-01-20 18:44:55 +08:00
link
dea02763a2 Update UI 2022-01-20 18:44:40 +08:00
link
ea67385a64 Merge pull request #72 from IceWhaleTech/dev
Storage Manager
2022-01-20 18:41:56 +08:00
link
fa2daa2767 Merge branch 'main' into dev 2022-01-20 18:41:49 +08:00
link
fcb906aa85 Storage Manager
Fix the app store classification problem
Fix the application market classification problem
2022-01-20 18:38:59 +08:00
老竭力
489a617126 Update casa.yml 2022-01-04 16:22:38 +08:00
老竭力
601e7ce10b Update casa.yml 2022-01-04 14:51:09 +08:00
老竭力
4a6fc9a945 Update system.go 2022-01-04 14:47:46 +08:00
老竭力
b377af1d24 Update casa.yml 2021-12-30 19:17:11 +08:00
老竭力
3fc00f8da7 Update casa.yml 2021-12-30 19:13:40 +08:00
老竭力
6e39fe5f8c Update casa.yml 2021-12-30 19:04:37 +08:00
老竭力
20c240a123 Update casa.yml 2021-12-30 19:00:11 +08:00
老竭力
3ea9fc0de0 Update casa.yml 2021-12-30 18:52:37 +08:00
老竭力
b80b08ef07 Update casa.yml 2021-12-30 18:50:45 +08:00
老竭力
505af8d101 Update casa.yml 2021-12-30 18:46:17 +08:00
老竭力
ae35a6d291 Update casa.yml 2021-12-30 18:44:07 +08:00
John Guan
2b95c07a47 Update casa.yml 2021-12-30 18:16:19 +08:00
John Guan
27a011e715 Update casa.yml 2021-12-30 18:01:01 +08:00
link
476831a12f Merge pull request #65 from IceWhaleTech/dev
update action system
2021-12-30 16:59:05 +08:00
link
9675eff69e update action system 2021-12-30 16:58:24 +08:00
link
85a044246e Merge pull request #64 from IceWhaleTech/dev
update action system
2021-12-30 16:53:32 +08:00
link
5c41fbcf3d update action system 2021-12-30 16:52:58 +08:00
link
6baab7a525 Merge pull request #63 from IceWhaleTech/dev
update action system
2021-12-30 16:42:39 +08:00
link
ab3b5a9077 update action system 2021-12-30 16:41:16 +08:00
link
5811c271b2 Merge pull request #62 from IceWhaleTech/dev
update web
2021-12-30 16:20:50 +08:00
link
cf5387346d update web 2021-12-30 16:20:30 +08:00
link
8df63c6c5c Merge pull request #60 from IceWhaleTech/dev
New App Store
2021-12-29 16:42:56 +08:00
link
1d17d27c96 New App Store 2021-12-29 16:42:20 +08:00
John Guan
bdcbae69a5 Update README.md 2021-12-14 11:41:42 +08:00
John Guan
cdbc3437be Update README.md 2021-12-14 10:40:17 +08:00
link
8940b520e0 Merge pull request #53 from IceWhaleTech/dev
update ui
2021-12-11 15:44:55 +08:00
link
1d62fbd670 update ui 2021-12-11 15:44:17 +08:00
link
a0b56d809e Merge pull request #52 from IceWhaleTech/dev
update cpu changes when the application is removed
2021-12-10 18:08:49 +08:00
link
f1f6d33e26 update cpu changes when the application is removed 2021-12-10 18:08:02 +08:00
link
f292edd2ba Merge pull request #51 from IceWhaleTech/dev
update app.go
2021-12-10 17:14:46 +08:00
link
caa9b50b65 update app.go 2021-12-10 17:14:01 +08:00
link
61b824065b Merge pull request #50 from IceWhaleTech/dev
update stats steam
2021-12-10 16:34:29 +08:00
link
9a900b2ca0 update stats steam 2021-12-10 16:33:39 +08:00
link
4c1cbc98a4 Merge pull request #49 from IceWhaleTech/dev
fixed bug
2021-12-10 14:18:01 +08:00
link
8660b95756 fixed bug 2021-12-10 14:17:36 +08:00
link
e7ebdc040f Merge pull request #48 from IceWhaleTech/dev
feat: Multiple updates
2021-12-09 19:03:45 +08:00
link
6c235d3f2a feat: Multiple updates
1.Add the function of modifying the WebUI port.
2.Add the function to modify the search engine.
3.Add the multi-language function and add Chinese translation.
4.Add detailed CPU and memory statistics.
2021-12-09 19:02:41 +08:00
link
997d912f4d Merge branch 'main' into dev 2021-12-06 17:12:53 +08:00
link
2508a4e07d Pull Submit 2021-12-06 17:08:36 +08:00
link
90b997337c Merge pull request #42 from xuchaoa/main
format code and fix wrong spell
2021-12-06 03:07:48 -06:00
xuc2
0bb3c92335 format code and fix wrong spell 2021-12-03 16:48:07 +08:00
link
7fd539c57e Merge pull request #40 from IceWhaleTech/dev
update volume path
2021-12-01 20:49:48 -06:00
link
52bd22ab2b update volume path 2021-12-02 10:49:02 +08:00
John Guan
46e9458e82 Update demo.yml 2021-12-01 21:58:57 +08:00
John Guan
3f5595e794 Update demo.yml 2021-12-01 21:54:02 +08:00
John Guan
d22cc7d3f6 Update demo.yml 2021-12-01 21:49:23 +08:00
John Guan
eb03a3e6c7 Update demo.yml 2021-12-01 21:46:34 +08:00
John Guan
65cc1f4752 Update demo.yml 2021-12-01 21:36:44 +08:00
John Guan
99db197a39 Update demo.yml 2021-12-01 21:31:17 +08:00
John Guan
7e2a5d553c Update demo.yml 2021-12-01 21:14:34 +08:00
John Guan
f02337b83b Update demo.yml 2021-12-01 21:09:18 +08:00
John Guan
f66b67b0c9 Update demo.yml 2021-12-01 21:05:52 +08:00
John Guan
91087b5341 Update demo.yml 2021-12-01 21:01:40 +08:00
John Guan
c67191d8c2 Update demo.yml 2021-12-01 20:45:36 +08:00
John Guan
0fac461783 Update demo.yml 2021-12-01 20:11:32 +08:00
John Guan
ec5bc922e7 Update demo.yml 2021-12-01 20:07:44 +08:00
John Guan
7194792c3f Update demo.yml 2021-12-01 19:51:36 +08:00
John Guan
76c8bade7f Update demo.yml 2021-12-01 19:50:30 +08:00
John Guan
126857fab0 Create demo.yml 2021-12-01 19:43:50 +08:00
link
9ca57e105e Merge pull request #38 from IceWhaleTech/dev
add uninstall.sh
2021-12-01 02:50:01 -06:00
link
2651140095 add uninstall.sh 2021-12-01 16:48:38 +08:00
link
14175bc438 Merge pull request #37 from IceWhaleTech/dev
fixed bug
2021-12-01 02:39:22 -06:00
link
956328da86 fixed bug 2021-12-01 16:25:56 +08:00
link
cc46a96a75 Merge pull request #27 from IceWhaleTech/v0.2.1
fixed path error
2021-11-25 05:44:33 -06:00
link
049090444e fixed path error 2021-11-25 19:41:25 +08:00
link
796c25b7a5 Merge pull request #26 from IceWhaleTech/v0.2.1
add sync function
2021-11-25 03:35:47 -06:00
link
9057290188 add sync function 2021-11-25 17:35:01 +08:00
John Guan
fcc57bb734 Update README.md 2021-11-24 18:35:14 +08:00
link
a98f5e087c Merge pull request #24 from IceWhaleTech/add-license-1
Create LICENSE
2021-11-19 03:34:09 -06:00
link
403d563869 Create LICENSE 2021-11-19 17:33:57 +08:00
John Guan
88c15104b4 update README.md 2021-11-12 17:52:16 +08:00
link
6176289b88 Merge pull request #23 from IceWhaleTech/v0.2.1
update volumes
2021-11-10 03:51:14 -06:00
link
5cfd44da79 update volumes 2021-11-10 17:50:46 +08:00
link
2437da33a6 Merge pull request #21 from IceWhaleTech/v0.2.1
Update system.go
2021-11-09 05:11:58 -06:00
link
49ca0af746 Update system.go 2021-11-09 19:10:18 +08:00
link
9440b89fab Merge pull request #20 from IceWhaleTech/v0.2.1
Fixing bugs
2021-11-09 04:58:59 -06:00
link
f020c1162d Fixing bugs
Resolve application installation path errors
2021-11-09 18:57:50 +08:00
link
120fb2cea2 Merge pull request #19 from IceWhaleTech/v0.2.1
update ui
2021-11-04 03:04:37 -05:00
link
37130966cf update ui 2021-11-04 16:03:33 +08:00
link
795b82c42c Update issue templates 2021-11-04 15:26:36 +08:00
link
57ad33d53a Merge pull request #17 from IceWhaleTech/v0.2.1
update ui
2021-11-03 06:06:21 -05:00
link
a6ceee7bc0 update ui 2021-11-03 19:05:41 +08:00
link
44bb05fad0 Merge pull request #16 from IceWhaleTech/v0.2.1
New App Store
2021-11-03 04:08:45 -05:00
link
a5fee0ee97 New App Store
Add App Store for installation
Fix favicon display in dark mode
2021-11-03 17:07:46 +08:00
John Guan
da99b2d01a Update README.md 2021-11-03 10:51:32 +08:00
link
1433e3297b Merge pull request #15 from IceWhaleTech/v0.2.1
Update UI
2021-10-29 06:36:37 -05:00
link
cad7af13af Update UI 2021-10-29 19:35:51 +08:00
link
39cb8904a3 Merge pull request #14 from IceWhaleTech/v0.2.1
V0.2.1
2021-10-29 05:39:54 -05:00
link
2ed372b3cd Update system.go 2021-10-29 18:39:07 +08:00
link
8bca76b78b Add new features
add casaOS logs
add application  terminal
add application  logs
2021-10-29 18:37:27 +08:00
link
595e0f28af Merge pull request #13 from IceWhaleTech/v0.2.1
update disk display
2021-10-27 06:04:34 -05:00
link
4939fe10aa update disk display
add casaos logs api
update ui
2021-10-27 19:03:59 +08:00
link
d2962a8e70 Merge pull request #12 from IceWhaleTech/v0.2.1
Add some features
2021-10-27 04:29:44 -05:00
link
d7d53d639b Add some features
Add terminal
Improve single user management function
2021-10-27 17:27:46 +08:00
link
d2ff1b0506 Merge pull request #10 from IceWhaleTech/v0.2.1
update UI
2021-10-22 05:28:34 -05:00
link
7191735737 update UI 2021-10-22 18:28:00 +08:00
link
21f3fd85d9 Merge pull request #9 from IceWhaleTech/v0.2.1
update initialization config
2021-10-22 04:59:00 -05:00
link
ba77e07e36 update initialization config
initialization user config
2021-10-22 17:57:22 +08:00
link
0d6e7ca339 Merge pull request #8 from IceWhaleTech/v0.2.1
update route.go
2021-10-22 04:19:53 -05:00
link
b1d5d9858b update route.go 2021-10-22 17:19:07 +08:00
link
4f06be0e45 Merge pull request #7 from IceWhaleTech/v0.2.1
update webui
2021-10-22 04:10:24 -05:00
link
812ffd56a8 update webui 2021-10-22 17:09:43 +08:00
老竭力
6ba845eec5 Update issue templates 2021-10-22 16:58:29 +08:00
link
4fa72289ed Merge pull request #6 from IceWhaleTech/v0.2.1
remove build file
2021-10-22 03:55:06 -05:00
link
5cdd842a3e remove build file
remove main
remove CasaOS
2021-10-22 16:54:17 +08:00
link
cc5504c0a9 Merge pull request #5 from IceWhaleTech/v0.2.1
Add authentication
2021-10-22 03:52:39 -05:00
link
b3aa22605d Add authentication
Add user authentication module, Login page and initialization page.
Fixed the problem that the application could not start after the system restarted.
2021-10-22 16:49:09 +08:00
John Guan
32e00b17b1 update README.md 2021-10-20 11:23:25 +08:00
John Guan
16108f03ac Merge branch 'main' of https://github.com/IceWhaleTech/CasaOS 2021-10-20 11:10:53 +08:00
John Guan
e7f990b224 Update README.md 2021-10-20 11:10:51 +08:00
link
c5d824c4ba Merge pull request #3 from IceWhaleTech/v0.2.1
Optimize installation process
2021-10-19 06:12:40 -05:00
link
39ccbe251f Optimize installation process
auto create file or dir
2021-10-19 19:07:16 +08:00
link
e69d2e587b Merge pull request #2 from IceWhaleTech/v0.2.1
update create file and dir api
2021-10-18 05:25:26 -05:00
link
8a28d3c589 update create file and dir api 2021-10-18 18:24:18 +08:00
link
8fe0e4aa73 Update casa.yml 2021-10-15 19:48:38 +08:00
link
30a23a93a2 Update casa.yml 2021-10-15 19:38:50 +08:00
link
53157fbb1f Merge pull request #1 from IceWhaleTech/v0.2.1
add widget
2021-10-14 22:45:31 -05:00
link
fb15695dab add widget
Add CPU RAM Status
Add Disk Info
2021-10-15 11:43:41 +08:00
老竭力
5f5091f1e2 🦄 refactor: Change build method
Change build method
add static.go to public folder
2021-09-30 18:52:03 +08:00
a624669980
df92766c74 Catalog Adjustment 2021-09-30 18:45:01 +08:00
a624669980
cc8b3e8f06 Modify gitgnore 2021-09-30 18:42:29 +08:00
John Guan
a116db8dbd Update .gitignore 2021-09-30 18:40:16 +08:00
a624669980
d697547cb7 Modify default config 2021-09-30 17:55:59 +08:00
a624669980
01960c0391 Modify default config 2021-09-30 17:54:29 +08:00
a624669980
953c393e71 Modify default config 2021-09-30 17:53:26 +08:00
a624669980
0873f7dd46 Modify the publishing process 2021-09-30 17:00:55 +08:00
a624669980
8d93a7f320 Modify the publishing process 2021-09-30 16:57:10 +08:00
a624669980
801eca0a14 Modify the publishing process 2021-09-30 16:56:03 +08:00
a624669980
a3ec7b70c9 Modify the publishing process 2021-09-30 16:55:00 +08:00
a624669980
4a77548b23 Modify the publishing process 2021-09-30 16:51:20 +08:00
a624669980
15ccade3d3 Modify the publishing process 2021-09-30 16:42:00 +08:00
a624669980
587fb6fb8a Modify the publishing process 2021-09-30 16:29:32 +08:00
a624669980
5bcb663ac8 Modify the publishing process 2021-09-30 16:26:36 +08:00
a624669980
cbd945536d Modify the publishing process 2021-09-30 16:14:09 +08:00
a624669980
081e9213c2 Modify the publishing process 2021-09-30 16:13:14 +08:00
a624669980
966fae2d4c Modify the publishing process 2021-09-30 16:12:45 +08:00
a624669980
dc4f9ea990 Modify the publishing process 2021-09-30 16:06:56 +08:00
a624669980
05b9c75714 Modify the publishing process 2021-09-30 15:55:02 +08:00
a624669980
4aeeea2325 Modify the publishing process 2021-09-30 15:52:56 +08:00
a624669980
72531cf6c2 Modify the publishing process 2021-09-30 15:45:09 +08:00
a624669980
9ad9be8c61 Modify the publishing process 2021-09-30 15:34:02 +08:00
a624669980
1aa15932a0 Modify the publishing process 2021-09-30 15:24:18 +08:00
a624669980
dbc6a4265a Modify the publishing process 2021-09-30 15:22:05 +08:00
a624669980
edea1f144a Modify the publishing process 2021-09-30 15:10:41 +08:00
a624669980
85c59c03cf Modify the publishing process 2021-09-30 14:52:32 +08:00
a624669980
a1f57bf1d1 Modify the publishing version 2021-09-30 14:45:33 +08:00
a624669980
e6f2c46c28 Modify the publishing process 2021-09-30 14:43:45 +08:00
a624669980
55c6c21aa3 Ignore profile 2021-09-29 19:51:40 +08:00
a624669980
40617185e9 Task modified to remote acquisition
token modified to no expiration time
2021-09-29 19:49:34 +08:00
link
c3dba45e17 Update casa.yml
change path
2021-09-29 18:02:22 +08:00
link
83f58366a6 Fix pack error 2021-09-29 17:43:59 +08:00
link
3fa09dad8e add workflows 2021-09-29 17:33:58 +08:00
jerrykuku
f0f0eb2ef0 🦄 refactor:
Change submodule UI to branch main
2021-09-29 13:50:16 +08:00
jerrykuku
436b87f8a8 🦄 refactor: Change submoudle
Change Frontend submoudle to UI
2021-09-29 13:38:03 +08:00
jerrykuku
f0888ef2ac Remove UI submodule. 2021-09-29 13:33:08 +08:00
Lauren
03e23ec203 Update README.md 2021-09-28 22:48:40 +08:00
a624669980
3e1d24624a Application modification and new creation failure issues 2021-09-28 19:22:20 +08:00
John Guan
1e3585d47c Update README.md 2021-09-27 19:29:56 +08:00
John Guan
db7fe3781e Update README.md 2021-09-27 19:27:16 +08:00
John Guan
c2ad576cd9 Update README.md
Adjusting the wording
2021-09-27 19:08:39 +08:00
John Guan
5c8d4b4b94 Update README.md
Adjusting the wording
2021-09-27 18:42:37 +08:00
John Guan
88f0cdf738 Update README.md
Adjusting the wording
2021-09-27 18:41:15 +08:00
John Guan
b759585d20 Merge branch 'main' of https://github.com/IceWhaleTech/CasaOS into main 2021-09-27 17:31:34 +08:00
John Guan
183bc211cd Update README.md 2021-09-27 17:31:30 +08:00
a624669980
9bce06d171 Merge remote-tracking branch 'origin/main' 2021-09-27 17:22:33 +08:00
a624669980
2491a03d4b update makefile 2021-09-27 17:22:18 +08:00
John Guan
4b02ad914d Update README.md
update banner link
2021-09-27 16:19:45 +08:00
John Guan
a1b876d088 Update README.md 2021-09-27 16:10:41 +08:00
a624669980
2cb16144ca Addressing security issues 2021-09-27 16:07:12 +08:00
John Guan
93b1b618d2 Delete README-ZH.md 2021-09-27 15:54:57 +08:00
John Guan
97e88f595a Update README.md 2021-09-27 15:54:07 +08:00
a624669980
2448173f44 Merge remote-tracking branch 'origin/main' 2021-09-27 15:43:22 +08:00
a624669980
191aaff575 build 0.1.1 2021-09-27 15:40:31 +08:00
440 changed files with 31091 additions and 11941 deletions

32
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,32 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@@ -0,0 +1,15 @@
---
name: Submit application
about: Add an app to this project
title: ''
labels: ''
assignees: LinkLeong
---
Tested platform
e.g. linux/amd64,linux/arm-v7,linux-arm64
Please export and upload the configuration file of this application

148
.github/workflows/casa.yml vendored Normal file
View File

@@ -0,0 +1,148 @@
# This is a basic workflow to help you get started with Actions
name: Build CasaOS
on:
repository_dispatch:
workflow_dispatch:
inputs:
ssh:
description: 'SSH connection to Actions'
required: false
default: 'false'
#on:
# push:
# branches:
# - 'main'
# tags:
# - 'v*'
env:
REPO_URL: https://github.com/IceWhaleTech/CasaOS.git
REPO_BRANCH: main
PACK_SH_URL: https://raw.githubusercontent.com/jerrykuku/actions-casa/main/pack.sh
PACK_SH: pack.sh
TZ: Asia/Shanghai
jobs:
xgo:
strategy:
fail-fast: false
matrix:
go_version:
- 1.17.1
runs-on: ubuntu-latest
steps:
# - name: Get release
# id: get_release
# uses: bruceadams/get-release@v1.2.3
# env:
# GITHUB_TOKEN: ${{ github.token }}
- uses: actions/checkout@v2
with:
fetch-depth: 0
submodules: true
# - name: Initialization environment
# env:
# DEBIAN_FRONTEND: noninteractive
# run: |
# sudo timedatectl set-timezone "$TZ"
# sudo mkdir -p /workdir
# sudo chown $USER:$GROUPS /workdir
# - name: Clone source code
# working-directory: /workdir
# run: |
# df -hT $PWD
# git clone $REPO_URL -b $REPO_BRANCH --recursive casa
# ln -sf /workdir/casa $GITHUB_WORKSPACE/casa
# ls
- name: Set enviroment for github-release
run: |
echo "VERSION=$(cat types/system.go | grep CURRENTVERSION | awk '$2 == "CURRENTVERSION"{print $4}' | sed 's/"//g')" >>$GITHUB_ENV
echo "BODY=$(cat types/system.go | grep BODY | awk -F= '{print $2}' | sed 's/"//g')" >>$GITHUB_ENV
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Build frontend with nodejs and yarn
run: |
cd UI
ls
yarn install
yarn build
- name: list work
run: pwd
- name: Build with xgo
uses: crazy-max/ghaction-xgo@v1
with:
xgo_version: v0.7.5
go_version: ${{ matrix.go_version }}
dest: build
prefix: casa
targets: linux/amd64,linux/arm64,linux/arm-7
v: true
x: false
race: false
ldflags: -s -w
buildmode: default
#
# - name: List Files
# run: |
# ls
# mkdir build
# ls
# echo "::set-output name=status::success"
- name: Pack builds
run: |
wget $PACK_SH_URL
chmod +x $PACK_SH
./$PACK_SH
echo "::set-output name=status::success"
- name: list work
run: ls
- name: Update release
uses: meeDamian/github-release@2.0
with:
token: ${{ secrets.GITHUB_TOKEN }}
files: >
linux-amd64-casaos.tar.gz
linux-arm64-casaos.tar.gz
linux-arm-7-casaos.tar.gz
tag: v${{ env.VERSION }}
body: >
${{ env.BODY }}
name: v${{ env.VERSION }}
gzip: false
allow_override: false
prerelease: true
# - name: Upload linux-amd64-casaos.tar.gz
# id: upload_assets_amd64
# uses: shogo82148/actions-upload-release-asset@v1
# with:
# upload_url: ${{ steps.get_release.outputs.upload_url }}
# asset_path: /workdir/casa/upload/linux-amd64-casaos.tar.gz
#
# - name: Upload linux-arm64-casaos.tar.gz
# id: upload_assets_arm64
# uses: shogo82148/actions-upload-release-asset@v1
# with:
# upload_url: ${{ steps.get_release.outputs.upload_url }}
# asset_path: /workdir/casa/upload/linux-arm64-casaos.tar.gz

79
.github/workflows/demo.yml vendored Normal file
View File

@@ -0,0 +1,79 @@
name: Demo Reset
# Controls when the workflow will run
on:
schedule:
- cron: "0 * * * *"
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# OLD_INSTANCE_SNAPSHOT_NAME=$(aws lightsail get-instance-snapshots | grep '"name": "CasaOS-Demo-Snapshot-[0-9]' | sed 's/ //g' | sed 's/"//g' | sed 's/,//g' | sed 's/name://g')
# OLD_INSTANCE_NAME=$(aws lightsail get-instances | grep '"name": "CasaOS-Demo-[0-9]' | sed 's/ //g' | sed 's/"//g' | sed 's/,//g' | sed 's/name://g')
# NEW_INSTANCE_NAME=CasaOS-Demo-$(date +%s)
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
reset:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: Configure AWS credentials from Test account
uses: aws-actions/configure-aws-credentials@v1
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-west-2
- name: Get old instance and snapshot name, create new instance name
run: |
echo "OLD_INSTANCE_SNAPSHOT_NAME=$(aws lightsail get-instance-snapshots | grep '"name": "CasaOS-Demo-Snapshot-[0-9]' | sed 's/ //g' | sed 's/"//g' | sed 's/,//g' | sed 's/name://g')" >> $GITHUB_ENV
echo "OLD_INSTANCE_NAME=$(aws lightsail get-instances | grep '"name": "CasaOS-Demo-[0-9]' | sed 's/ //g' | sed 's/"//g' | sed 's/,//g' | sed 's/name://g')" >> $GITHUB_ENV
echo "NEW_INSTANCE_NAME=CasaOS-Demo-$(date +%s)" >> $GITHUB_ENV
- name: Create instances from snapshot
run: |
aws lightsail create-instances-from-snapshot \
--instance-snapshot-name ${{ env.OLD_INSTANCE_SNAPSHOT_NAME }} \
--instance-names ${{ env.NEW_INSTANCE_NAME }} \
--availability-zone us-west-2a \
--bundle-id large_2_0
- name: Wait for new instance running
run: |
TIMEOUT=$(($(date +%s)+600))
while [ $TIMEOUT -gt $(date +%s) ]
do
NEW_INSTANCE_STATE=$(aws lightsail get-instance-state --instance-name ${{ env.NEW_INSTANCE_NAME }} | grep '"name":' | sed 's/ //g' | sed 's/"//g' | sed 's/name://g')
if [ $NEW_INSTANCE_STATE == running ]
then
echo "New instance is running now"
sleep 10s
break
fi
done
- name: Put instance public ports
run: |
aws lightsail put-instance-public-ports \
--port-infos fromPort=0,toPort=65535,protocol=all \
--instance-name ${{ env.NEW_INSTANCE_NAME }}
- name: Attach static ip
run: |
aws lightsail attach-static-ip \
--static-ip-name CasaOS-Demo-IP \
--instance-name ${{ env.NEW_INSTANCE_NAME }}
- name: Delete old instance
run: |
aws lightsail delete-instance \
--instance-name ${{ env.OLD_INSTANCE_NAME }}

6
.gitignore vendored
View File

@@ -20,6 +20,7 @@
# IntelliJ project files
.idea
.vscode
*.iml
out
gen
@@ -28,3 +29,8 @@ gen
/out/
/db/
/docs/
/conf/conf.ini
__debug_bin
main
CasaOS
github.com

5
.gitmodules vendored
View File

@@ -1,3 +1,4 @@
[submodule "CasaOS-UI"]
path = CasaOS-UI
[submodule "UI"]
path = UI
url = https://github.com/IceWhaleTech/CasaOS-UI.git
branch = main

363
CHANGELOG.md Normal file
View File

@@ -0,0 +1,363 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
### Changed
### Removed
### Security
### Fixed
## [0.3.1.1] - 2022-05-17
### Fixed
- Fix the data loss problem when importing local applications
## [0.3.1] - 2022-05-16
### Added
- CasaConnect and file add image thumbnail function
- Import of docker applications
- List support custom sorting function
- CasaConnect gives priority to LAN connections
- USB auto-mount switch (Raspberry Pi is off by default)
- Application custom installation supports Docker Compose configuration import in YAML format
- You will see the new version changelog from the next version
- Added live preview for icons in custom installed applications
### Changed
- Application data is no longer saved to the database
- Optimize app store speed issues
- Optimize the way WebUI is filled in
- Image preview has been completely upgraded and now supports switching between all images in the same folder, as well as dragging, zooming, rotating and resetting.
- Added color levels to the CPU and RAM charts
- Optimized the display of the Connect friends list right-click menu
- Change the initial display directory to /DATA
### Removed
- Historical Application Data
### Fixed
- Fixed the problem that some Docker CLI commands failed to import
- Fix the problem that the application is not easily recognized in /DATA/AppData directory and docker command line after installation, it will be shown as application name
- Fix Pi-hole installation failure
- Fixed the issue that the app could not be updated using WatchTower
- Fixed the problem that the task status was lost after closing Files when there was an upload task
## [0.3.0] - 2022-04-08
### Added
- Add CasaConnect function, now you can share private files peer-to-peer with your friends.
- Add a widget for network traffic monitoring.
- 12 new popular apps added to App Center
### Changed
- Updated the sidebar of Files.
- Updated the initial directory of Files to the Root directory.
- Armbian 22.02 armhf/arm64/amd64 platform tests passed [@igorpecovnik ](https://github.com/igorpecovnik)
- Elementary OS 6.1 Jólnir amd64 platform tests passed [@alvarosamudio ](https://github.com/alvarosamudio)
### Fixed
- Fix an issue in Files where the backspace button would trigger a return to the previous level of the directory when creating a folder.
- Fix the display problem of application list in CPU widget.
- Fix the problem that the ipv6 of the application cannot be opened
### Removed
- Interfaces related to "zerotier"
## [0.2.10] - 2022-03-10
### Added
- Added CasaOS own file manager, now you can browse, upload, download files from the system, even edit code online, preview photos and videos through it. It will appear in the first position of Apps.
- Added CPU core count display and memory capacity display.
### Changed
- Optimized the rendering performance of the home page.
- Optimized the internationalization display of the time widget.
- Show the icon of the stopped application as gray.
- Unify the animation of the drop-down menu.
- Optimize the display of the application drop-down menu.
- Replaced the default font to optimize the display.
### Fixed
- Fix the problem of failed to create storage space
## [0.2.9] - 2022-02-18
### Added
- Add a simple notification function
### Changed
- Custom installation of new parameters(Capabilities,Hostname,Privileged)
- Update front-end translation [@SemVer](https://github.com/zarevskaya) [@koboldMaki](https://github.com/koboldMaki) [@sgastol](https://github.com/sgastol) [@delki8](https://github.com/delki8)
- Modify the default location and name of the usb mount
### Fixed
- Fix the problem of being indexed by search engines
- Fix some style display issues
- Solve hard drive can't be formatted, can't finish adding storage
## [0.2.8] - 2022-01-30
### Added
- Add USB disk device display
### Changed
- Update translation [@baptiste313](https://github.com/baptiste313) [@thueske](https://github.com/thueske)
- Compatible with more types of drives
### Fixed
- Fix the language initialization bug
- Fix the problem that the login page could not be displayed
- Fix missing translated content
## [0.2.7] - 2022.01.26
### Changed
- Apply multilingual support
### Security
- Fix an injectable execution bug
## [0.2.6] - 2022.01.26
### Added
- Add a bug report panel.
- App Store apps start supporting multiple languages
### Fixed
- Fix a disk that cannot be formatted under certain circumstances
## [0.2.5] - 2022.01.24
### Added
- Storage Manager
### Changed
- Update Disk widget
- Update language files [@ImOstrovskiy](https://github.com/ImOstrovskiy) [@baptiste313](https://github.com/baptiste313)
### Fixed
- File synchronization issues
- Fix the app store classification problem
## [0.2.4] - 2021.12.30
### Changed
- Brand new App Store
- Optimize request method
### Fixed
- Fix Sync panel width display error.
- Fix App panel width display error.
## [0.2.3] - 2021.12.11
### Added
- Add detailed CPU and memory statistics.
- Add the multi-language function and add Chinese translation.
- Add the function to modify the search engine.
- Add the function of modifying the WebUI port
### Changed
- Update update script
- Preprocessing usb automounting
### Fixed
- Volume path problem when customizing the installation of applications
- Fix Cpu and Ram usage display error
- Fix translation errors
- Fixed an error when importing and exporting appfile.
## [0.2.2] - 2021.12.02
### Changed
- UI adjustment
### Fixed
- Fix the problem of data display error when manually installing apps
- Fix some spelling problems
- Fix the bug of synchronization module
## [0.2.1] - 2021.11.25
### Fixed
- Fix Sync display error
- Fix Sync Downoad url error
- Fix Smart Block display error
- Fix widgets settings dispaly error
- Fix application installation path error
## [0.2.0] - 2021.11.25
### Added
- Add sync function
## [0.1.11] - 2021.11.10
### Changed
- Adaptation of cell phone terminals
- Optimize user experience
- Replaced the default background
- Optimized the display performance and fixed some bugs
### Fixed
- Resolve application installation path errors
## [0.1.10] - 2021.11.04
### Added
- Add application terminal
- Add application logs
- Add system logs
- Add App Store for installation
## [0.1.9] - 2021.11.01 [YANKED]
## [0.1.8] - 2021.10.27
### Added
- Add system terminal
- Add the ability to modify the user name and password
### Changed
- Experience optimization
- Improve single user management function
- Fixed Disk widget display error
- Fixed Username display error after change
- Adaptation for mobile access
## [0.1.7] - 2021.10.22
### Added
- Add user authentication module, Login page and initialization page.
### Fixed
- Fix the problem that the application could not start after the system restarted.
- Home storage space data display exception
- Script override causes application loss after installation
- Fix docker network error
## [0.1.6] - 2021.10.19
### Added
- Add app icon auto-fill via docker image name.
- Add a file selector for app install.
### Changed
- Modify import reminder.
- Optimize the application installation process
### Fixed
- Fixed an issue with the app were it would disappear when the app was modified.
- Fixed device selector default dir to /dev
## [0.1.5] - 2021.10.15
### Added
- Add CPU RAM Status with widget
- Add Disk Info with widget
- Realize automatic loading of widgets
### Changed
- Enhance the Docker cli import experience and automatically fill in the folders that need to be mounted
### Removed
- Remove Weather widget.
### Fixed
- AppFile upload does not pass verification
- The setting menu of the app is displayed abnormally when the browser window is too narrow
- The port is occupied and the program cannot start
- Fix display bugs when windows size less than 1024px
## [0.1.4] - 2021.09.30
### Added
- Import and export of application configuration files
- Automatic parsing of docker commands
### Changed
- Improve the program release process
- Application installation process UX/UI optimization
### Fixed
- Authentication failure during the operation, resulting in the need to re-login
## [0.1.3] - 2021.09.29 [YANKED]
## [0.1.2] - 2021.09.28
### Fixed
- Application modification and new creation failure issues
## [0.1.1] - 2021.09.27
## [0.1.0] - 2021.09.26
### Added
- Application Center

Submodule CasaOS-UI deleted from 6139d87e80

201
LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -4,7 +4,7 @@ build: build-ui build-backend
build-ui:
cd UI && yarn install && yarn build
cd CasaOS-UI && yarn install && yarn build
build-backend:
export CGO_ENABLED=1;export CGO_LDFLAGS=-static;go build -o ./casa main.go;upx --lzma --best casa

View File

@@ -1,7 +0,0 @@
## 目录结构
- conf 配置文件
- route 路由
- service 方法的具体实现
- utils 工具
- main.go 入口

130
README.md
View File

@@ -1,89 +1,89 @@
# CasaOS - A simple, easy to use, beautiful open source home server system.
# CasaOS - A simple, easy-to-use, elegant open-source Home Cloud system.
![CasaOS](https://github.com/IceWhaleTech/logo/raw/main/casaos/casaos_banner_aldeyjarfoss.png)
![CasaOS](https://raw.githubusercontent.com/IceWhaleTech/logo/main/casaos/casaos_banner_aldeyjarfoss.png)
[![Version](https://img.shields.io/static/v1?label=CasaOS&message=v0.1.0&color=162453&style=flat-square)](https://github.com/IceWhaleTech/CasaOS)
[![Version](https://img.shields.io/github/v/release/IceWhaleTech/CasaOS?color=162453&label=CasaOS&style=flat-square)](https://github.com/IceWhaleTech/CasaOS)
[![Pull Requests](https://img.shields.io/github/issues-pr/IceWhaleTech/CasaOS?color=162453&style=flat-square)](https://github.com/IceWhaleTech/CasaOS/pulls)
[![Issues](https://img.shields.io/github/issues/IceWhaleTech/CasaOS?color=162453&style=flat-square)](https://github.com/IceWhaleTech/CasaOS/issues)
[![Ideas](https://img.shields.io/github/stars/IceWhaleTech/CasaOS?color=162453&logo=github&style=flat-square)](https://github.com/IceWhaleTech/CasaOS/stargazers)
[![Discord](https://img.shields.io/discord/884667213326463016?color=162453&label=Chat&logo=discord&logoColor=fff&style=flat-square)](https://discord.gg/Gx4BCEtHjx)
[![GitHub Stars](https://img.shields.io/github/stars/IceWhaleTech/CasaOS?color=162453&logo=github&style=flat-square)](https://github.com/IceWhaleTech/CasaOS/stargazers)
[![Discord](https://img.shields.io/discord/884667213326463016?color=162453&label=Chat&logo=discord&logoColor=fff&style=flat-square)](https://discord.gg/knqAbbBbeX)
CasaOS is an open source home server system based on Docker ecology and designed for home scenarios. It is committed to building the world's most simple, easy-to-use and beautiful home intelligence hub system.
CasaOS is an open-source Home Cloud system based on the Docker ecosystem and designed for home scenarios. It is committed to building the world's most simple, easy-to-use, and elegant Home Cloud system.
The team promotes a community-driven collaborative innovation model to create a home intelligence hub through open communication with global enthusiasts and developers.
## Features
- UI Designed for home scenarios - simple, beautiful and easy to use
- Custom Docker app installation in 3 steps
- Automatic Docker application management
- Private Cloud App Store 🚧
- Home file data/digital asset management 🚧
- Smart Home Device Management 🚧
🚧 is under development...
We are actively moving forward with development and welcome you to discuss ideas with us in [Discord](https://discord.gg/Gx4BCEtHjx)!
## Comunity
Casa is derived from the Spanish word for "home".
The CasaOS project originated as a pre-installed system for IceWhale's hardware product ZimaBoard.
After researching a large number of operating systems and software on the market, the team found that there was no server system designed for home scenarios.
So, we chose to launch this open source project to develop CasaOS with our friends in the community and you.
> Sincerely welcome you to propose and discuss your great ideas in [Discord](https://discord.gg/Gx4BCEtHjx)!
[![Discord Card](https://discordapp.com/api/guilds/884667213326463016/widget.png?style=banner2)](https://discord.gg/Gx4BCEtHjx)
IceWhale team believes that through community-driven collaborative innovation and open communication with global developers, we can reshape the digital home experience like never before.
![CasaOS Snapshot](snapshot.png)
![CasaOS Snapshot Mobile](snapshot-mobile.png)
## Getting Started
> ⚠️ Note:
>
> CasaOS is still in a very early version and may be very different from the final release. Feel free to experience and discuss with us in the [Discord](https://discord.gg/Gx4BCEtHjx)!
### System Compatibility
- Ubuntu Server 20.04 amd64 (✅ Recommend, Tested)
- Debian 11 amd64 (⚠️ Not fully tested yet)
- OpenWrt 21.02 amd64 (⚠️ Not fully tested yet)
- Raspberry Pi OS aarch64/arm64 (🚧 Under Planning)
- OpenWrt 21.02 aarch64/arm64 (🚧 Under Planning)
> CasaOS is still in the early development stage and may vary significantly with the final release. Feel free to test run and share your feedback in the [Discord server](https://discord.gg/knqAbbBbeX)!
### Quick Setup CasaOS
Install a fresh system from the above list and run this command:
Fresh install a system from the list below and run the this command:
```sh
wget -qO- https://get.icewhale.io/casaos.sh | bash
```
or
```sh
curl -fsSL https://get.icewhale.io/casaos.sh | bash
```
## To Do
### Uninstall CasaOS
**v 0.1.x**
```sh
curl -fsSL https://get.icewhale.io/casaos-uninstall.sh | bash
```
- [x] A beautiful UI for home
- [x] Custom installation of Docker Apps
- [x] Docker Apps update, stop, uninstall, restart, etc.
- [x] Docker CLI parser
- [x] System Update
- [ ] Getting Started tutorial
- [ ] Docker Compose parser
- [ ] App config file import and export
- [ ] macvlan network mode
### System Compatibility
## Contributors
- Ubuntu Server 20.04 amd64 (✅ Recommend, Tested)
- Armbian 22.02 armhf/arm64/amd64 (✅ Recommend, Tested)
- Elementary OS 6.1 Jólnir amd64 (✅ Recommend, Tested)
- Deepin 20.4 amd64 (⚠️ Not Fully Tested Yet)
- Raspberry Pi Lite OS aarch64/arm64 (⚠️ Not Fully Tested Yet)
- Debian 11 amd64 (⚠️ Not Fully Tested Yet)
- OpenWrt 21.02 amd64 (⚠️ Not Fully Tested Yet)
- OpenWrt 21.02 aarch64/arm64 (⚠️ Not Fully Tested Yet)
- Icewhale Technology
- Jerry Liu
- Link Liang
- Ober Zhang
- Zyaiire Ann
- John Guan
- CasaOS Community
- Waiting for you
## Key Features
- UI designed for home scenarios - simple, elegant, and easy-to-use
- Quick Docker app installation with only three steps, plus automatic management
- App Store for Home Cloud 🚧
- Home data/digital asset management 🚧
- Smart home manager 🚧
🚧 is under development.
We are actively moving forward with development, and you are more than welcome to share any idea with us!
## Community
The word Casa comes from the Spanish word for "home". Project CasaOS originated as a pre-installed system for crowdfunded product [ZimaBoard](https://www.zimaboard.com) on Kickstarter.
After looking at many systems and software on the market, the team found no server system designed for home scenarios, sadly true.
So, we set out to build this open source project to develop CasaOS with our own hands, everyone in the community, and you.
> A warm welcome for you to share and discuss your great ideas in the [Discord server](https://discord.gg/knqAbbBbeX)!
[![Discord Card](https://discordapp.com/api/guilds/884667213326463016/widget.png?style=banner2)](https://discord.gg/knqAbbBbeX)
## Maintainers
- Jerry Liu
- Link Liang
- Ober Zhang
- Zyaire Ann
- John Guan
- Right here, waiting for YOU!

1
UI Submodule

Submodule UI added at 70d9529d06

View File

@@ -1,51 +0,0 @@
[app]
PAGE_SIZE = 10
RuntimeRootPath = runtime/
;LogSavePath = /casaOS/logs/server/
LogSavePath = /oasis/logs/server/
LogSaveName = log
LogFileExt = log
; 必须的格式
DateStrFormat = 20060102
DateTimeFormat = 2006-01-02 15:04:05
TimeFormat = 15:04:05
DateFormat = 2006-01-02
ProjectPath = /casaOS/server
[server]
HttpPort = 8089
RunMode = debug
;ServerApi = http://113.52.135.30:8090
;ServerApi = https://casaos.zimaboard.com
;ServerApi = http://192.168.2.167:8090
ServerApi = http://192.168.2.142:8090
[user]
UserName = admin
PWD = zimaboard
Email = aaa@222.ddd
Description = ddddddd
Token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImVyZXJlIiwicGFzc3dvcmQiOiJhZHNmZGYiLCJleHAiOjE2MjQwMDU0ODEsImlzcyI6Imdpbi1ibG9nIn0.JNsCccZuFCwlSMLJg62iOIB2xymk_k7xGa11xhZ07bc
[zerotier]
UserName = ddddd
PWD =
Token = yBKYyavr2RdFAIVN7iTpzlsB1o6CqTgm
[redis]
Host = 192.168.2.167:6379
Password =
MaxIdle = 30
MaxActive = 30
IdleTimeout = 200
[system]
AutoUpdate = true
SearchSwitch = true
WidgetsSwitch = false
ShortcutsSwitch = true
SearchEngine = baidu
Background = http://baidu.com1
BackgroundType = d

42
conf/conf.ini.sample Normal file
View File

@@ -0,0 +1,42 @@
[app]
PAGE_SIZE = 10
RuntimeRootPath = runtime/
LogSavePath = /casaOS/logs/server/
LogSaveName = log
LogFileExt = log
DateStrFormat = 20060102
DateTimeFormat = 2006-01-02 15:04:05
TimeFormat = 15:04:05
DateFormat = 2006-01-02
ProjectPath = /casaOS/server
RootPath = /casaOS
[server]
HttpPort = 8089
UDPPort =
RunMode = release
ServerApi = https://api.casaos.io/casaos-api
Handshake = socket.casaos.io
Token =
USBAutoMount =
[user]
UserName =
PWD =
Email = user@gmail.com
Description = description
Initialized = false
Avatar =
NickName =
PublicKey =
[system]
ConfigStr =
WidgetList =
Analyse =
[file]
ShareDir =
DownloadDir =

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

65
go.mod
View File

@@ -3,54 +3,77 @@ module github.com/IceWhaleTech/CasaOS
go 1.16
require (
github.com/PuerkitoBio/goquery v1.7.0
github.com/Curtis-Milo/nat-type-identifier-go v0.0.0-20220215191915-18d42168c63d
github.com/Microsoft/go-winio v0.5.0 // indirect
github.com/Microsoft/hcsshim v0.8.22 // indirect
github.com/StackExchange/wmi v0.0.0-20210224194228-fe8f1750fd46 // indirect
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
github.com/containerd/containerd v1.5.2
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/bits-and-blooms/bitset v1.2.1 // indirect
github.com/containerd/containerd v1.5.7
github.com/containerd/continuity v0.2.0 // indirect
github.com/disintegration/imaging v1.6.2
github.com/docker/distribution v2.8.0+incompatible // indirect
github.com/docker/docker v20.10.7+incompatible
github.com/docker/go-connections v0.4.0
github.com/dsoprea/go-exif/v3 v3.0.0-20210625224831-a6301f85c82b
github.com/dsoprea/go-logging v0.0.0-20200710184922-b02d349568dd // indirect
github.com/forease/gotld v0.0.0-20190808124948-c50ff635576b
github.com/gin-contrib/gzip v0.0.2 // indirect
github.com/gin-contrib/gzip v0.0.2
github.com/gin-gonic/gin v1.7.2
github.com/go-ini/ini v1.62.0
github.com/go-ole/go-ole v1.2.5 // indirect
github.com/go-openapi/jsonreference v0.19.6 // indirect
github.com/go-openapi/spec v0.20.3 // indirect
github.com/go-openapi/swag v0.19.15 // indirect
github.com/go-openapi/spec v0.20.4 // indirect
github.com/go-playground/validator/v10 v10.6.1 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/gogo/googleapis v1.4.1 // indirect
github.com/golang-jwt/jwt v3.2.2+incompatible
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/gomodule/redigo v1.8.5
github.com/google/go-github/v36 v36.0.0
github.com/google/uuid v1.3.0 // indirect
github.com/gorilla/mux v1.8.0 // indirect
github.com/gorilla/websocket v1.4.2
github.com/jinzhu/copier v0.3.2
github.com/json-iterator/go v1.1.11 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/lucas-clemente/quic-go v0.25.0
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-isatty v0.0.13 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mattn/go-sqlite3 v1.14.11 // indirect
github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6 // indirect
github.com/morikuni/aec v1.0.0 // indirect
github.com/opencontainers/image-spec v1.0.2 // indirect
github.com/opencontainers/selinux v1.8.5 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.9.1
github.com/prestonTao/upnp v0.0.0-20150206124352-f4370df5e109
github.com/prometheus/procfs v0.7.3 // indirect
github.com/robfig/cron v1.2.0
github.com/satori/go.uuid v1.2.0
github.com/shirou/gopsutil/v3 v3.21.5
github.com/sirupsen/logrus v1.8.1
github.com/smartystreets/assertions v1.2.0 // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/spf13/afero v1.2.2
github.com/swaggo/gin-swagger v1.3.0
github.com/swaggo/swag v1.7.0
github.com/tidwall/gjson v1.8.0
github.com/swaggo/swag v1.7.3
github.com/tidwall/gjson v1.10.2
github.com/tklauser/go-sysconf v0.3.6 // indirect
github.com/ugorji/go v1.2.6 // indirect
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e
golang.org/x/net v0.0.0-20210614182718-04defd469f4e // indirect
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d
golang.org/x/time v0.0.0-20210611083556-38a9dc6acbc6 // indirect
golang.org/x/tools v0.1.3 // indirect
google.golang.org/grpc v1.39.0 // indirect
go.opencensus.io v0.23.0 // indirect
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5
golang.org/x/mod v0.5.0 // indirect
golang.org/x/net v0.0.0-20211020060615-d418f374d309 // indirect
golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f
golang.org/x/sys v0.0.0-20211020174200-9d6173849985 // indirect
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b // indirect
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac // indirect
golang.org/x/tools v0.1.7 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0 // indirect
google.golang.org/grpc v1.41.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/ini.v1 v1.62.0 // indirect
gorm.io/driver/sqlite v1.1.5
gorm.io/gorm v1.21.15
src.techknowlogick.com/xgo v1.4.1-0.20210909190026-ce016894db20 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
gorm.io/driver/sqlite v1.2.6
gorm.io/gorm v1.22.5
)

412
go.sum

File diff suppressed because it is too large Load Diff

77
main.go
View File

@@ -3,59 +3,105 @@ package main
import (
"flag"
"fmt"
"net/http"
"time"
"github.com/IceWhaleTech/CasaOS/pkg/cache"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/sqlite"
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
"github.com/IceWhaleTech/CasaOS/route"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/robfig/cron"
"gorm.io/gorm"
"net/http"
"time"
)
var sqliteDB *gorm.DB
var swagHandler gin.HandlerFunc
var configFlag = flag.String("c", "", "config address")
var dbFlag = flag.String("db", "", "db path")
var showUserInfo = flag.Bool("show-user-info", false, "show user info")
func init() {
flag.Parse()
config.InitSetup(*configFlag)
config.UpdateSetup()
loger2.LogSetup()
sqliteDB = sqlite.GetDb(config.AppInfo.ProjectPath)
if len(*dbFlag) == 0 {
*dbFlag = config.AppInfo.ProjectPath + "/db"
}
sqliteDB = sqlite.GetDb(*dbFlag)
//gredis.GetRedisConn(config.RedisInfo),
service.MyService = service.NewService(sqliteDB, loger2.NewOLoger())
service.Cache = cache.Init()
go service.UDPService()
fmt.Println("token", service.GetToken())
service.UDPAddressMap = make(map[string]string)
//go service.SocketConnect()
service.CancelList = make(map[string]string)
service.InternalInspection = make(map[string][]string)
service.NewVersionApp = make(map[string]string)
route.InitFunction()
go service.SendIPToServer()
// go service.LoopFriend()
// go service.MyService.App().CheckNewImage()
}
// @title Oasis API
// @title casaOS API
// @version 1.0.0
// @contact.name lauren.pan
// @contact.url https://www.zimaboard.com
// @contact.email lauren.pan@icewhale.org
// @description Oasis v1版本api
// @host 192.168.2.114:8089
// @description casaOS v1版本api
// @host 192.168.2.217:8089
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
// @BasePath /v1
func main() {
if *showUserInfo {
fmt.Println("CasaOS User Info")
fmt.Println("UserName:" + config.UserInfo.UserName)
fmt.Println("Password:" + config.UserInfo.PWD)
return
}
//model.Setup()
//gredis.Setup()
r := route.InitRouter(swagHandler)
service.SyncTask(sqliteDB)
cron2 := cron.New() //创建一个cron实例
//执行定时任务每5秒执行一次
err := cron2.AddFunc("0 0 0 1/1 * *", func() {
r := route.InitRouter()
//service.SyncTask(sqliteDB)
cron2 := cron.New()
//every day execution
err := cron2.AddFunc("0 0/5 * * * *", func() {
//service.PushIpInfo(*&config.ServerInfo.Token)
//service.UpdataDDNSList(mysqldb)
service.SyncTask(sqliteDB)
//service.SyncTask(sqliteDB)
service.SendIPToServer()
service.LoopFriend()
service.MyService.App().CheckNewImage()
})
if err != nil {
fmt.Println(err)
}
err = cron2.AddFunc("0/1 * * * * *", func() {
notify := model2.AppNotify{}
notify.CustomId = ""
notify.Type = types.NOTIFY_TYPE_HEALTH_CHECK
//启动/关闭
go service.MyService.Notify().SendText(notify)
})
if err != nil {
fmt.Println(err)
}
cron2.Start()
defer cron2.Stop()
s := &http.Server{
@@ -65,6 +111,7 @@ func main() {
WriteTimeout: 60 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}

View File

@@ -2,8 +2,9 @@ package middleware
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"github.com/gin-gonic/gin"
)
func Cors() gin.HandlerFunc {
@@ -17,7 +18,7 @@ func Cors() gin.HandlerFunc {
//服务器支持的所有跨域请求的方法
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
//允许跨域设置可以返回其他子段,可以自定义字段
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,Language")
// 允许浏览器(客户端)可以解析的头部 (重要)
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
//设置缓存时间

27
model/app-analyse.go Normal file
View File

@@ -0,0 +1,27 @@
/*
* @Author: LinkLeong link@icewhale.com
* @Date: 2022-03-18 11:40:55
* @LastEditors: LinkLeong
* @LastEditTime: 2022-05-13 14:48:01
* @FilePath: /CasaOS/model/app-analyse.go
* @Description:
* @Website: https://www.casaos.io
* Copyright (c) 2022 by icewhale, All Rights Reserved.
*/
package model
type AppAnalyse struct {
Name string `json:"name"`
Type string `json:"type"`
UUId string `json:"uuid"`
Language string `json:"language"`
Version string `json:"version"`
}
type ConnectionStatus struct {
From string `json:"from"`
To string `json:"to"`
Error string `json:"error"`
UUId string `json:"uuid"`
Event string `json:"event"`
}

View File

@@ -7,32 +7,42 @@ import (
)
type ServerAppList struct {
Id uint `gorm:"column:id;primary_key" json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Tagline string `json:"tagline"`
Tags Strings `gorm:"type:json" json:"tags"`
Icon string `json:"icon"`
ScreenshotLink Strings `gorm:"type:json" json:"screenshot_link"`
Category string `json:"category"`
TcpPort uint `json:"tcp_port"`
PortMap uint `json:"port_map"`
ImageVersion string `json:"image_version"`
Tip string `json:"tip"`
Configures configures `gorm:"type:json" json:"configures"`
NetworkModel string `json:"network_mode"`
Image string `json:"image"`
Index string `json:"index"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
State string `json:"state"`
Author string `json:"author"`
MinMemory int `json:"min_memory"`
MinDisk int `json:"min_disk"`
MaxMemory uint64 `json:"max_memory"`
Thumbnail string `json:"thumbnail"`
Healthy string `json:"healthy"`
Plugins Strings `json:"plugins"`
Id uint `gorm:"column:id;primary_key" json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Tagline string `json:"tagline"`
Tags Strings `gorm:"type:json" json:"tags"`
Icon string `json:"icon"`
ScreenshotLink Strings `gorm:"type:json" json:"screenshot_link"`
Category string `json:"category"`
CategoryFont string `json:"category_font"`
PortMap string `json:"port_map"`
ImageVersion string `json:"image_version"`
Tip string `json:"tip"`
Envs EnvArray `json:"envs"`
Ports PortArray `json:"ports"`
Volumes PathArray `json:"volumes"`
Devices PathArray `json:"devices"`
NetworkModel string `json:"network_model"`
Image string `json:"image"`
Index string `json:"index"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
State string `json:"state"`
Author string `json:"author"`
MinMemory int `json:"min_memory"`
MinDisk int `json:"min_disk"`
MaxMemory uint64 `json:"max_memory"`
Thumbnail string `json:"thumbnail"`
Healthy string `json:"healthy"`
Plugins Strings `json:"plugins"`
Origin string `json:"origin"`
Type int `json:"type"`
Developer string `json:"developer"`
HostName string `json:"host_name"`
Privileged bool `json:"privileged"`
CapAdd Strings `json:"cap_add"`
Cmd Strings `json:"cmd"`
}
type Ports struct {

View File

@@ -5,6 +5,7 @@ type ServerCategoryList struct {
//CreatedAt time.Time `json:"created_at"`
//
//UpdatedAt time.Time `json:"updated_at"`
Font string `json:"font"`
Name string `json:"name"`
Count uint `json:"count"`
}

View File

@@ -20,12 +20,57 @@ type LSBLKModel struct {
Format string `json:"format"`
Health string `json:"health"`
HotPlug bool `json:"hotplug"`
UUID string `json:"uuid"`
FSUsed string `json:"fsused"`
Temperature int `json:"temperature"`
Tran string `json:"tran"`
MinIO uint64 `json:"min-io"`
UsedPercent float64 `json:"used_percent"`
Serial string `json:"serial"`
Children []LSBLKModel `json:"children"`
SubSystems string `json:"subsystems"`
//详情特有
StartSector uint64 `json:"start_sector,omitempty"`
Rota bool `json:"rota"` //true(hhd) false(ssd)
DiskType string `json:"disk_type"`
EndSector uint64 `json:"end_sector,omitempty"`
}
type Drive struct {
Name string `json:"name"`
Size uint64 `json:"size"`
Model string `json:"model"`
Health string `json:"health"`
Temperature int `json:"temperature"`
DiskType string `json:"disk_type"`
NeedFormat bool `json:"need_format"`
Serial string `json:"serial"`
Path string `json:"path"`
}
type DriveUSB struct {
Name string `json:"name"`
Size uint64 `json:"size"`
Used uint64 `json:"use"`
Model string `json:"model"`
Mount bool `json:"mount"` //是否完全挂载
Avail uint64 `json:"avail"` //可用空间
}
type Storage struct {
Name string `json:"name"`
MountPoint string `json:"mountpoint"`
Size string `json:"size"`
Avail string `json:"avail"` //可用空间
Type string `json:"type"`
CreatedAt int64 `json:"create_at"`
Path string `json:"path"`
DriveName string `json:"drive_name"`
}
type Summary struct {
Size uint64 `json:"size"`
Avail uint64 `json:"avail"` //可用空间
Health bool `json:"health"`
Used uint64 `json:"used"`
}

8
model/docker.go Normal file
View File

@@ -0,0 +1,8 @@
package model
type DockerStatsModel struct {
Icon string `json:"icon"`
Title string `json:"title"`
Data interface{} `json:"data"`
Pre interface{} `json:"pre"`
}

6
model/heart.go Normal file
View File

@@ -0,0 +1,6 @@
package model
type CasaOSHeart struct {
UuId string `json:"uuid"`
Type string `json:"type"`
}

View File

@@ -17,20 +17,22 @@ type UdpPorts struct {
/*******************使用gorm支持json************************************/
type PortMap struct {
ContainerPort string `json:"container,omitempty"`
CommendPort string `json:"host,omitempty"`
ContainerPort string `json:"container"`
CommendPort string `json:"host"`
Protocol string `json:"protocol"`
Desc string `json:"desc"`
Type int `json:"type"`
}
type PortArrey []PortMap
type PortArray []PortMap
// Value 实现方法
func (p PortArrey) Value() (driver.Value, error) {
func (p PortArray) Value() (driver.Value, error) {
return json.Marshal(p)
}
// Scan 实现方法
func (p *PortArrey) Scan(input interface{}) error {
func (p *PortArray) Scan(input interface{}) error {
return json.Unmarshal(input.([]byte), p)
}
@@ -41,20 +43,22 @@ func (p *PortArrey) Scan(input interface{}) error {
type Env struct {
Name string `json:"container"`
Value string `json:"host"`
Desc string `json:"desc"`
Type int `json:"type"`
}
type JSON json.RawMessage
type EnvArrey []Env
type EnvArray []Env
// Value 实现方法
func (p EnvArrey) Value() (driver.Value, error) {
func (p EnvArray) Value() (driver.Value, error) {
return json.Marshal(p)
//return .MarshalJSON()
}
// Scan 实现方法
func (p *EnvArrey) Scan(input interface{}) error {
func (p *EnvArray) Scan(input interface{}) error {
return json.Unmarshal(input.([]byte), p)
}
@@ -65,17 +69,19 @@ func (p *EnvArrey) Scan(input interface{}) error {
type PathMap struct {
ContainerPath string `json:"container"`
Path string `json:"host"`
Type int `json:"type"`
Desc string `json:"desc"`
}
type PathArrey []PathMap
type PathArray []PathMap
// Value 实现方法
func (p PathArrey) Value() (driver.Value, error) {
func (p PathArray) Value() (driver.Value, error) {
return json.Marshal(p)
}
// Scan 实现方法
func (p *PathArrey) Scan(input interface{}) error {
func (p *PathArray) Scan(input interface{}) error {
return json.Unmarshal(input.([]byte), p)
}
@@ -98,22 +104,27 @@ func (p *PathArrey) Scan(input interface{}) error {
//}
type CustomizationPostData struct {
CustomId string `json:"custom_id"`
Origin string `json:"origin"`
NetworkModel string `json:"network_model"`
Index string `json:"index"`
Icon string `json:"icon"`
Image string `json:"image"`
Envs EnvArrey `json:"envs"`
Ports PortArrey `json:"ports"`
Volumes PathArrey `json:"volumes"`
Devices PathArrey `json:"devices"`
Envs EnvArray `json:"envs"`
Ports PortArray `json:"ports"`
Volumes PathArray `json:"volumes"`
Devices PathArray `json:"devices"`
//Port string `json:"port,omitempty"`
PortMap string `json:"port_map"`
CpuShares int64 `json:"cpu_shares"`
Memory int64 `json:"memory"`
Restart string `json:"restart"`
EnableUPNP bool `json:"enable_upnp"`
Label string `json:"label"`
Description string `json:"description"`
Position bool `json:"position"`
PortMap string `json:"port_map"`
CpuShares int64 `json:"cpu_shares"`
Memory int64 `json:"memory"`
Restart string `json:"restart"`
EnableUPNP bool `json:"enable_upnp"`
Label string `json:"label"`
Description string `json:"description"`
Position bool `json:"position"`
HostName string `json:"host_name"`
Privileged bool `json:"privileged"`
CapAdd []string `json:"cap_add"`
Cmd []string `json:"cmd"`
}

View File

@@ -1,19 +1,17 @@
package model
import "time"
type IOCountersStat struct {
Name string `json:"name"` // interface name
BytesSent uint64 `json:"bytesSent"` // number of bytes sent
BytesRecv uint64 `json:"bytesRecv"` // number of bytes received
PacketsSent uint64 `json:"packetsSent"` // number of packets sent
PacketsRecv uint64 `json:"packetsRecv"` // number of packets received
Errin uint64 `json:"errin"` // total number of errors while receiving
Errout uint64 `json:"errout"` // total number of errors while sending
Dropin uint64 `json:"dropin"` // total number of incoming packets which were dropped
Dropout uint64 `json:"dropout"` // total number of outgoing packets which were dropped (always 0 on OSX and BSD)
Fifoin uint64 `json:"fifoin"` // total number of FIFO buffers errors while receiving
Fifoout uint64 `json:"fifoout"` // total number of FIFO buffers errors while sending
State string `json:"state"`
DateTime time.Time `json:"date_time"`
Name string `json:"name"` // interface name
BytesSent uint64 `json:"bytesSent"` // number of bytes sent
BytesRecv uint64 `json:"bytesRecv"` // number of bytes received
PacketsSent uint64 `json:"packetsSent"` // number of packets sent
PacketsRecv uint64 `json:"packetsRecv"` // number of packets received
Errin uint64 `json:"errin"` // total number of errors while receiving
Errout uint64 `json:"errout"` // total number of errors while sending
Dropin uint64 `json:"dropin"` // total number of incoming packets which were dropped
Dropout uint64 `json:"dropout"` // total number of outgoing packets which were dropped (always 0 on OSX and BSD)
Fifoin uint64 `json:"fifoin"` // total number of FIFO buffers errors while receiving
Fifoout uint64 `json:"fifoout"` // total number of FIFO buffers errors while sending
State string `json:"state"`
Time int64 `json:"time"`
}

6
model/notify.go Normal file
View File

@@ -0,0 +1,6 @@
package model
type NotifyMssage struct {
Type string `json:"type"`
Data string `json:"data"`
}

54
model/person.go Normal file
View File

@@ -0,0 +1,54 @@
package model
import "time"
type PersionModel struct {
Token string `json:"token"`
Ips []string `json:"ips"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
//记录链接状态
type ConnectState struct {
From string `json:"from"`
To string `json:"to"`
Type string `json:"type"` //current state 1:ready 2:ok
CreatedAt time.Time `json:"created_at"`
UUId string `json:"uuid"` //对接标识
}
type MessageModel struct {
Type string `json:"type"`
Data interface{} `json:"data"`
UUId string `json:"uuid"`
From string `json:"from"`
To string `json:"to"`
}
type TranFileModel struct {
Hash string `json:"hash"` //Verify current fragment integrity
Length int `json:"length"`
Index int `json:"index"`
}
//需要获取文件详情
type FileDetailModel struct {
Path string `json:"path"`
}
//返回文件详情
type FileSummaryModel struct {
Hash string `json:"hash"` //Verify file
Name string `json:"name"`
BlockSize int `json:"block_size"`
Length int `json:"length"`
Size int64 `json:"size"`
Message string `json:"message"`
}
type FriendsModel struct {
Id uint `gorm:"column:id;primary_key" json:"id"`
NickName string `json:"nick_name"`
Desc string `json:"desc"`
ShareId string `json:"share_id"`
}

1
model/receive/app.go Normal file
View File

@@ -0,0 +1 @@
package receive

7
model/search.go Normal file
View File

@@ -0,0 +1,7 @@
package model
type SearchFileInfo struct {
Path string `json:"path"`
Name string `json:"name"`
Type int `json:"type"`
}

69
model/smartctl_model.go Normal file
View File

@@ -0,0 +1,69 @@
package model
//
type SmartctlA struct {
Smartctl struct {
Version []int `json:"version"`
SvnRevision string `json:"svn_revision"`
PlatformInfo string `json:"platform_info"`
BuildInfo string `json:"build_info"`
Argv []string `json:"argv"`
ExitStatus int `json:"exit_status"`
} `json:"smartctl"`
Device struct {
Name string `json:"name"`
InfoName string `json:"info_name"`
Type string `json:"type"`
Protocol string `json:"protocol"`
} `json:"device"`
ModelName string `json:"model_name"`
SerialNumber string `json:"serial_number"`
FirmwareVersion string `json:"firmware_version"`
UserCapacity struct {
Blocks int `json:"blocks"`
Bytes int64 `json:"bytes"`
} `json:"user_capacity"`
SmartStatus struct {
Passed bool `json:"passed"`
} `json:"smart_status"`
AtaSmartData struct {
OfflineDataCollection struct {
Status struct {
Value int `json:"value"`
String string `json:"string"`
} `json:"status"`
CompletionSeconds int `json:"completion_seconds"`
} `json:"offline_data_collection"`
SelfTest struct {
Status struct {
Value int `json:"value"`
String string `json:"string"`
Passed bool `json:"passed"`
} `json:"status"`
PollingMinutes struct {
Short int `json:"short"`
Extended int `json:"extended"`
Conveyance int `json:"conveyance"`
} `json:"polling_minutes"`
} `json:"self_test"`
Capabilities struct {
Values []int `json:"values"`
ExecOfflineImmediateSupported bool `json:"exec_offline_immediate_supported"`
OfflineIsAbortedUponNewCmd bool `json:"offline_is_aborted_upon_new_cmd"`
OfflineSurfaceScanSupported bool `json:"offline_surface_scan_supported"`
SelfTestsSupported bool `json:"self_tests_supported"`
ConveyanceSelfTestSupported bool `json:"conveyance_self_test_supported"`
SelectiveSelfTestSupported bool `json:"selective_self_test_supported"`
AttributeAutosaveEnabled bool `json:"attribute_autosave_enabled"`
ErrorLoggingSupported bool `json:"error_logging_supported"`
GpLoggingSupported bool `json:"gp_logging_supported"`
} `json:"capabilities"`
} `json:"ata_smart_data"`
PowerOnTime struct {
Hours int `json:"hours"`
} `json:"power_on_time"`
PowerCycleCount int `json:"power_cycle_count"`
Temperature struct {
Current int `json:"current"`
} `json:"temperature"`
}

View File

@@ -15,13 +15,22 @@ type UserModel struct {
Head string
Email string
Description string
Initialized bool
Avatar string
NickName string
Public string
}
//服务配置
type ServerModel struct {
HttpPort string
RunMode string
ServerApi string
HttpPort string
RunMode string
ServerApi string
LockAccount bool
Handshake string
Token string
UDPPort string
USBAutoMount string
}
//服务配置
@@ -34,6 +43,7 @@ type APPModel struct {
TimeFormat string
DateFormat string
ProjectPath string
RootPath string
}
//公共返回模型
@@ -43,13 +53,6 @@ type Result struct {
Data interface{} `json:"data" example:"返回结果"`
}
//zeritier相关
type ZeroTierModel struct {
UserName string
PWD string
Token string
}
//redis配置文件
type RedisModel struct {
Host string
@@ -60,11 +63,19 @@ type RedisModel struct {
}
type SystemConfig struct {
SearchSwitch bool `json:"search_switch"` //搜索开关
SearchEngine string `json:"search_engine"` //搜索引擎
ShortcutsSwitch bool `json:"shortcuts_switch"`
WidgetsSwitch bool `json:"widgets_switch"`
BackgroundType string `json:"background_type"`
Background string `json:"background"`
AutoUpdate bool `json:"auto_update"`
ConfigStr string `json:"config_str"`
WidgetList string `json:"widget_list"`
ConfigPath string `json:"config_path"`
SyncPort string `json:"sync_port"`
SyncKey string `json:"sync_key"`
Analyse string `json:"analyse"`
}
type CasaOSGlobalVariables struct {
AppChange bool
}
type FileSetting struct {
ShareDir []string `json:"share_dir" delim:"|"`
DownloadDir string `json:"download_dir"`
}

View File

@@ -1,3 +1 @@
package model

8
model/system_app/sync.go Normal file
View File

@@ -0,0 +1,8 @@
package system_app
import "encoding/xml"
type SyncConfig struct {
XMLName xml.Name `xml:"configuration"`
Key string `xml:"gui>apikey"`
}

9
model/user.go Normal file
View File

@@ -0,0 +1,9 @@
package model
type UserInfo struct {
NickName string `json:"nick_name"`
Desc string `json:"desc"`
ShareId string `json:"share_id"`
Avatar string `json:"avatar"`
Version int `json:"version,omitempty"`
}

View File

@@ -4,7 +4,7 @@ import "time"
type Version struct {
Id uint `gorm:"column:id;primary_key" json:"id"`
ChangLog string `json:"chang_log"`
ChangeLog string `json:"change_log"`
Version string `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`

View File

@@ -1,9 +0,0 @@
package model
type ZeroTierUpData struct {
Config ZeroTierConfig `json:"config"`
}
type ZeroTierConfig struct {
Private bool `json:"private"`
}

View File

@@ -1,6 +1,14 @@
package model
import "time"
type Path struct {
Name string `json:"name"`
Path string `json:"path"`
Name string `json:"name"` //File name or document name
Path string `json:"path"` //Full path to file or folder
IsDir bool `json:"is_dir"` //Is it a folder
Date time.Time `json:"date"`
Size int64 `json:"size"` //File Size
Type string `json:"type,omitempty"`
Label string `json:"label,omitempty"`
Write bool `json:"write"`
}

11
pkg/cache/cache.go vendored Normal file
View File

@@ -0,0 +1,11 @@
package cache
import (
"time"
"github.com/patrickmn/go-cache"
)
func Init() *cache.Cache {
return cache.New(5*time.Minute, 60*time.Second)
}

View File

@@ -2,14 +2,15 @@ package config
import (
"fmt"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/go-ini/ini"
"log"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/go-ini/ini"
)
//系统配置
@@ -21,17 +22,17 @@ var UserInfo = &model.UserModel{}
//用户相关
var AppInfo = &model.APPModel{}
//redis相关配置
var RedisInfo = &model.RedisModel{}
//zerotier相关
var ZeroTierInfo = &model.ZeroTierModel{}
//var RedisInfo = &model.RedisModel{}
//server相关
var ServerInfo = &model.ServerModel{}
var SystemConfigInfo = &model.SystemConfig{}
var CasaOSGlobalVariables = &model.CasaOSGlobalVariables{}
var FileSettingInfo = &model.FileSetting{}
var Cfg *ini.File
//初始化设置,获取系统的部分信息。
@@ -51,10 +52,11 @@ func InitSetup(config string) {
mapTo("user", UserInfo)
mapTo("app", AppInfo)
mapTo("zerotier", ZeroTierInfo)
mapTo("redis", RedisInfo)
//mapTo("redis", RedisInfo)
mapTo("server", ServerInfo)
mapTo("system", SystemConfigInfo)
mapTo("file", FileSettingInfo)
SystemConfigInfo.ConfigPath = configDir
// AppInfo.ProjectPath = getCurrentDirectory() //os.Getwd()
}

32
pkg/config/update.go Normal file
View File

@@ -0,0 +1,32 @@
package config
import (
"runtime"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
)
//检查目录是否存在
func mkdirDATAAll() {
sysType := runtime.GOOS
var dirArray []string
if sysType == "linux" {
dirArray = []string{"/DATA/AppData", "/DATA/Documents", "/DATA/Downloads", "/DATA/Gallery", "/DATA/Media/Movies", "/DATA/Media/TV Shows", "/DATA/Media/Music"}
}
if sysType == "windows" {
dirArray = []string{"C:\\CasaOS\\DATA\\AppData", "C:\\CasaOS\\DATA\\Documents", "C:\\CasaOS\\DATA\\Downloads", "C:\\CasaOS\\DATA\\Gallery", "C:\\CasaOS\\DATA\\Media/Movies", "C:\\CasaOS\\DATA\\Media\\TV Shows", "C:\\CasaOS\\DATA\\Media\\Music"}
}
if sysType == "darwin" {
dirArray = []string{"./CasaOS/DATA/AppData", "./CasaOS/DATA/Documents", "./CasaOS/DATA/Downloads", "./CasaOS/DATA/Gallery", "./CasaOS/DATA/Media/Movies", "./CasaOS/DATA/Media/TV Shows", "./CasaOS/DATA/Media/Music"}
}
for _, v := range dirArray {
file.IsNotExistMkDir(v)
}
}
func UpdateSetup() {
mkdirDATAAll()
}

View File

@@ -4,30 +4,35 @@ import (
"bytes"
json2 "encoding/json"
"fmt"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"io"
"regexp"
"strconv"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
func NewSshClient() (*ssh.Client, error) {
func NewSshClient(user, password string) (*ssh.Client, error) {
// connet to ssh
// addr = fmt.Sprintf("%s:%d", host, port)
config := &ssh.ClientConfig{
Timeout: time.Second * 5,
User: "root",
User: user,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
//HostKeyCallback: ,
//HostKeyCallback: hostKeyCallBackFunc(h.Host),
}
//if h.Type == "password" {
config.Auth = []ssh.AuthMethod{ssh.Password("123456")}
config.Auth = []ssh.AuthMethod{ssh.Password(password)}
//} else {
// config.Auth = []ssh.AuthMethod{publicKeyAuthFunc(h.Key)}
//}
addr := fmt.Sprintf("%s:%d", "192.168.2.142", 22)
addr := fmt.Sprintf("%s:%d", "127.0.0.1", 22)
c, err := ssh.Dial("tcp", addr, config)
if err != nil {
return nil, err
@@ -98,6 +103,98 @@ const (
wsMsgResize = "resize"
)
//ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
func ReceiveWsMsgUser(wsConn *websocket.Conn, logBuff *bytes.Buffer) string {
//tells other go routine quit
username := ""
for {
//read websocket msg
_, wsData, err := wsConn.ReadMessage()
if err != nil {
return ""
}
msgObj := wsMsg{}
if err := json2.Unmarshal(wsData, &msgObj); err != nil {
msgObj.Type = "cmd"
msgObj.Cmd = string(wsData)
}
//if err := json.Unmarshal(wsData, &msgObj); err != nil {
// logrus.WithError(err).WithField("wsData", string(wsData)).Error("unmarshal websocket message failed")
//}
switch msgObj.Type {
case wsMsgCmd:
//handle xterm.js stdin
//decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
decodeBytes := []byte(msgObj.Cmd)
if msgObj.Cmd == "\u007f" {
if len(username) == 0 {
continue
}
wsConn.WriteMessage(websocket.TextMessage, []byte("\b\x1b[K"))
username = username[:len(username)-1]
continue
}
if msgObj.Cmd == "\r" {
return username
}
username += msgObj.Cmd
if err := wsConn.WriteMessage(websocket.TextMessage, decodeBytes); err != nil {
logrus.WithError(err).Error("ws cmd bytes write to ssh.stdin pipe failed")
}
//write input cmd to log buffer
if _, err := logBuff.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("write received cmd into log buffer failed")
}
}
}
}
func ReceiveWsMsgPassword(wsConn *websocket.Conn, logBuff *bytes.Buffer) string {
//tells other go routine quit
password := ""
for {
//read websocket msg
_, wsData, err := wsConn.ReadMessage()
if err != nil {
logrus.WithError(err).Error("reading webSocket message failed")
return ""
}
msgObj := wsMsg{}
if err := json2.Unmarshal(wsData, &msgObj); err != nil {
msgObj.Type = "cmd"
msgObj.Cmd = string(wsData)
}
//if err := json.Unmarshal(wsData, &msgObj); err != nil {
// logrus.WithError(err).WithField("wsData", string(wsData)).Error("unmarshal websocket message failed")
//}
switch msgObj.Type {
case wsMsgCmd:
//handle xterm.js stdin
//decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
if msgObj.Cmd == "\r" {
return password
}
if msgObj.Cmd == "\u007f" {
if len(password) == 0 {
continue
}
password = password[:len(password)-1]
continue
}
password += msgObj.Cmd
}
}
}
//ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
func (ssConn *SshConn) ReceiveWsMsg(wsConn *websocket.Conn, logBuff *bytes.Buffer, exitCh chan bool) {
//tells other go routine quit
@@ -187,6 +284,64 @@ func flushComboOutput(w *wsBufferWriter, wsConn *websocket.Conn) error {
}
return nil
}
//ReceiveWsMsg receive websocket msg do some handling then write into ssh.session.stdin
func (ssConn *SshConn) Login(wsConn *websocket.Conn, logBuff *bytes.Buffer, exitCh chan bool) {
//tells other go routine quit
defer setQuit(exitCh)
for {
select {
case <-exitCh:
return
default:
//read websocket msg
_, wsData, err := wsConn.ReadMessage()
if err != nil {
logrus.WithError(err).Error("reading webSocket message failed")
return
}
//unmashal bytes into struct
//msgObj := wsMsg{
// Type: "cmd",
// Cmd: "",
// Rows: 50,
// Cols: 180,
//}
msgObj := wsMsg{}
if err := json2.Unmarshal(wsData, &msgObj); err != nil {
msgObj.Type = "cmd"
msgObj.Cmd = string(wsData)
}
//if err := json.Unmarshal(wsData, &msgObj); err != nil {
// logrus.WithError(err).WithField("wsData", string(wsData)).Error("unmarshal websocket message failed")
//}
switch msgObj.Type {
case wsMsgResize:
//handle xterm.js size change
if msgObj.Cols > 0 && msgObj.Rows > 0 {
if err := ssConn.Session.WindowChange(msgObj.Rows, msgObj.Cols); err != nil {
logrus.WithError(err).Error("ssh pty change windows size failed")
}
}
case wsMsgCmd:
//handle xterm.js stdin
//decodeBytes, err := base64.StdEncoding.DecodeString(msgObj.Cmd)
decodeBytes := []byte(msgObj.Cmd)
if err != nil {
logrus.WithError(err).Error("websock cmd string base64 decoding failed")
}
if _, err := ssConn.StdinPipe.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("ws cmd bytes write to ssh.stdin pipe failed")
}
//write input cmd to log buffer
if _, err := logBuff.Write(decodeBytes); err != nil {
logrus.WithError(err).Error("write received cmd into log buffer failed")
}
}
}
}
}
func (ssConn *SshConn) SessionWait(quitChan chan bool) {
if err := ssConn.Session.Wait(); err != nil {
logrus.WithError(err).Error("ssh session wait failed")
@@ -241,7 +396,7 @@ func WsReaderCopy(reader *websocket.Conn, writer io.Writer) {
if err = json2.Unmarshal(p, &msgObj); err != nil {
writer.Write(p)
} else if msgObj.Type == wsMsgResize {
writer.Write([]byte("stty rows " + strconv.Itoa(msgObj.Rows) + " && stty cols " + strconv.Itoa(msgObj.Cols) + " \r" ))
writer.Write([]byte("stty rows " + strconv.Itoa(msgObj.Rows) + " && stty cols " + strconv.Itoa(msgObj.Cols) + " \r"))
}
}
}

View File

@@ -1,12 +1,11 @@
package docker
import "strings"
func GetDir(id, envName string) string {
var path string
switch envName {
case "/config":
path = "/oasis/app_data/" + id + "/"
default:
//path = "/media"
if strings.Contains(envName, "$AppID") && len(id) > 0 {
return strings.ReplaceAll(envName, "$AppID", id)
}
return path
return envName
}

View File

@@ -0,0 +1,10 @@
package docker
import (
"fmt"
"testing"
)
func TestGetDir(t *testing.T) {
fmt.Println(GetDir("", "config"))
}

View File

@@ -6,11 +6,10 @@ import (
"golang.org/x/oauth2"
)
func GetGithubClient() *github.Client {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: "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"},
&oauth2.Token{AccessToken: ""},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)

View File

@@ -1,7 +0,0 @@
package github
import "testing"
func TestGetRepos(t *testing.T) {
GetRepos()
}

View File

@@ -1,9 +1,10 @@
package gredis
import (
"github.com/gomodule/redigo/redis"
"oasis/model"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/gomodule/redigo/redis"
)
func GetRedisConn(m *model.RedisModel) *redis.Pool {

51
pkg/quic_helper/config.go Normal file
View File

@@ -0,0 +1,51 @@
package quic_helper
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"math/big"
"github.com/lucas-clemente/quic-go"
)
// Setup a bare-bones TLS config for the server
func GetGenerateTLSConfig(token string) *tls.Config {
key, err := rsa.GenerateKey(rand.Reader, 1024)
if err != nil {
panic(err)
}
template := x509.Certificate{SerialNumber: big.NewInt(1)}
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
if err != nil {
panic(err)
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
panic(err)
}
return &tls.Config{
Certificates: []tls.Certificate{tlsCert},
NextProtos: []string{token},
SessionTicketsDisabled: true,
}
}
func GetClientTlsConfig(otherToken string) *tls.Config {
return &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{otherToken},
SessionTicketsDisabled: true,
}
}
func GetQUICConfig() *quic.Config {
return &quic.Config{
ConnectionIDLength: 4,
KeepAlive: true,
}
}

View File

@@ -2,24 +2,25 @@ package sqlite
import (
"fmt"
"time"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"time"
)
var gdb *gorm.DB
func GetDb(projectPath string) *gorm.DB {
func GetDb(dbPath string) *gorm.DB {
if gdb != nil {
return gdb
}
// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
//dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", m.User, m.PWD, m.IP, m.Port, m.DBName)
//db, err := gorm.Open(mysql2.Open(dsn), &gorm.Config{})
file.IsNotExistMkDir(projectPath + "/db/")
db, err := gorm.Open(sqlite.Open(projectPath+"/db/casaOS.db"), &gorm.Config{})
file.IsNotExistMkDir(dbPath)
db, err := gorm.Open(sqlite.Open(dbPath+"/casaOS.db"), &gorm.Config{})
c, _ := db.DB()
c.SetMaxIdleConns(10)
c.SetMaxOpenConns(100)
@@ -30,7 +31,7 @@ func GetDb(projectPath string) *gorm.DB {
return nil
}
gdb = db
err = db.AutoMigrate(&model2.TaskDBModel{}, &model2.AppNotify{}, &model2.AppListDBModel{})
err = db.AutoMigrate(&model2.TaskDBModel{}, &model2.AppNotify{}, &model2.AppListDBModel{}, &model2.SerialDisk{}, model2.PersonDownloadDBModel{}, model2.FriendModel{}, model2.PersonDownRecordDBModel{}, model2.ApplicationModel{})
if err != nil {
fmt.Println("检查和创建数据库出错", err)
}

View File

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

View File

@@ -1,8 +1,9 @@
package upnp
import (
ip_helper2 "oasis/pkg/utils/ip_helper"
"testing"
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
)
func TestGetCtrlUrl(t *testing.T) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,9 +2,11 @@ package command
import (
"bufio"
"context"
"fmt"
"io/ioutil"
"os/exec"
"time"
)
func OnlyExec(cmdStr string) {
@@ -75,6 +77,7 @@ func ExecResultStr(cmdStr string) string {
func ExecLSBLK() []byte {
output, err := exec.Command("lsblk", "-O", "-J", "-b").Output()
if err != nil {
fmt.Println("lsblk", err)
return nil
}
return output
@@ -84,7 +87,26 @@ func ExecLSBLK() []byte {
func ExecLSBLKByPath(path string) []byte {
output, err := exec.Command("lsblk", path, "-O", "-J", "-b").Output()
if err != nil {
fmt.Println("lsblk", err)
return nil
}
return output
}
//exec smart
func ExecSmartCTLByPath(path string) []byte {
timeout := 3
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
output, err := exec.CommandContext(ctx, "smartctl", "-a", path, "-j").Output()
if err != nil {
fmt.Println("smartctl", err)
return nil
}
return output
}
func ExecEnabledSMART(path string) {
exec.Command("smartctl", "-s on", path).Output()
}

View File

@@ -0,0 +1,26 @@
package env_helper
import "strings"
func ReplaceDefaultENV(key, tz string) string {
temp := ""
switch key {
case "$DefaultPassword":
temp = "casaos"
case "$DefaultUserName":
temp = "admin"
case "$PUID":
temp = "1000"
case "$PGID":
temp = "1000"
case "$TZ":
temp = tz
}
return temp
}
//replace env default setting
func ReplaceStringDefaultENV(str string) string {
return strings.ReplaceAll(strings.ReplaceAll(str, "$DefaultPassword", ReplaceDefaultENV("$DefaultPassword", "")), "$DefaultUserName", ReplaceDefaultENV("$DefaultUserName", ""))
}

81
pkg/utils/file/block.go Normal file
View File

@@ -0,0 +1,81 @@
package file
import (
"crypto/md5"
"encoding/hex"
"io"
"math"
"os"
"strconv"
)
// Get info of block
func GetBlockInfo(fileSize int64) (blockSize int, length int) {
switch {
case fileSize <= 1<<28: //256M
blockSize = 1 << 17 //128kb
case fileSize <= 1<<29: //512M
blockSize = 1 << 18 //256kb
case fileSize <= 1<<30: //1G
blockSize = 1 << 19 //512kb
case fileSize <= 1<<31: //2G
blockSize = 1 << 20 //(mb)
case fileSize <= 1<<32: //4G
blockSize = 1 << 21 //2mb
case fileSize <= 1<<33: //8G
blockSize = 1 << 22 //4mb
case fileSize <= 1<<34: //16g
blockSize = 1 << 23 //8mb
default:
blockSize = 1 << 24 //16mb
}
temp := float64(fileSize) / float64(blockSize)
length = int(math.Ceil(temp))
return
}
//get the hash of the data
func GetHashByContent(data []byte) string {
sum := md5.Sum(data)
return hex.EncodeToString(sum[:])
}
//get the hash of the data
func GetHashByPath(path string) string {
pFile, err := os.Open(path)
if err != nil {
return ""
}
defer pFile.Close()
md5h := md5.New()
io.Copy(md5h, pFile)
return hex.EncodeToString(md5h.Sum(nil))
}
//Comparison data hash
func ComparisonHash(data []byte, hash string) bool {
sum := md5.Sum(data)
return hex.EncodeToString(sum[:]) == hash
}
//get prefix byte length
func PrefixLength(byteLength int) []byte {
lengthByte := []byte{'0', '0', '0', '0', '0', '0'}
bSize := strconv.Itoa(byteLength)
cha := 6 - len(bSize)
for i := len(bSize); i > 0; i-- {
lengthByte[cha+i-1] = bSize[i-1]
}
return lengthByte
}
//get data byte length
func DataLength(length int) []byte {
lengthByte := []byte{'0', '0', '0', '0', '0', '0', '0', '0'}
bSize := strconv.Itoa(length)
cha := 8 - len(bSize)
for i := len(bSize); i > 0; i-- {
lengthByte[cha+i-1] = bSize[i-1]
}
return lengthByte
}

View File

@@ -1,11 +1,17 @@
package file
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"os"
"path"
path2 "path"
"path/filepath"
"strconv"
"strings"
)
// GetSize get the file size
@@ -35,7 +41,7 @@ func CheckPermission(src string) bool {
// IsNotExistMkDir create a directory if it does not exist
func IsNotExistMkDir(src string) error {
if notExist := CheckNotExist(src); notExist == true {
if notExist := CheckNotExist(src); notExist {
if err := MkDir(src); err != nil {
return err
}
@@ -50,6 +56,7 @@ func MkDir(src string) error {
if err != nil {
return err
}
os.Chmod(src, 0777)
return nil
}
@@ -100,10 +107,9 @@ func MustOpen(fileName, filePath string) (*os.File, error) {
return f, nil
}
// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
@@ -126,3 +132,203 @@ func IsDir(path string) bool {
func IsFile(path string) bool {
return !IsDir(path)
}
func CreateFile(path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
return nil
}
func CreateFileAndWriteContent(path string, content string) error {
file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return err
}
defer file.Close()
write := bufio.NewWriter(file)
write.WriteString(content)
write.Flush()
return nil
}
// IsNotExistMkDir create a directory if it does not exist
func IsNotExistCreateFile(src string) error {
if notExist := CheckNotExist(src); notExist == true {
if err := CreateFile(src); err != nil {
return err
}
}
return nil
}
func ReadFullFile(path string) []byte {
file, err := os.Open(path)
if err != nil {
return []byte("")
}
defer file.Close()
content, err := ioutil.ReadAll(file)
if err != nil {
return []byte("")
}
return content
}
// File copies a single file from src to dst
func CopyFile(src, dst string) error {
var err error
var srcfd *os.File
var dstfd *os.File
var srcinfo os.FileInfo
lastPath := src[strings.LastIndex(src, "/")+1:]
if !strings.HasSuffix(dst, "/") {
dst += "/"
}
dstPath := dst
dst += lastPath
for i := 0; Exists(dst); i++ {
name := strings.Split(lastPath, ".")
nameIndex := 0
if len(name) > 2 {
nameIndex = len(name) - 2
}
name[nameIndex] = name[nameIndex] + "(Copy)"
dst = dstPath
for _, v := range name {
dst += v + "."
}
dst = strings.TrimSuffix(dst, ".")
}
if srcfd, err = os.Open(src); err != nil {
return err
}
defer srcfd.Close()
if dstfd, err = os.Create(dst); err != nil {
return err
}
defer dstfd.Close()
if _, err = io.Copy(dstfd, srcfd); err != nil {
return err
}
if srcinfo, err = os.Stat(src); err != nil {
return err
}
return os.Chmod(dst, srcinfo.Mode())
}
//Check for duplicate file names
func GetNoDuplicateFileName(fullPath string) string {
path, fileName := filepath.Split(fullPath)
fileSuffix := path2.Ext(fileName)
filenameOnly := strings.TrimSuffix(fileName, fileSuffix)
for i := 0; Exists(fullPath); i++ {
fullPath = path2.Join(path, filenameOnly+"("+strconv.Itoa(i+1)+")"+fileSuffix)
}
return fullPath
}
// Dir copies a whole directory recursively
func CopyDir(src string, dst string) error {
var err error
var fds []os.FileInfo
var srcinfo os.FileInfo
if srcinfo, err = os.Stat(src); err != nil {
return err
}
if !srcinfo.IsDir() {
if err = CopyFile(src, dst); err != nil {
fmt.Println(err)
}
return nil
}
dstPath := dst
lastPath := src[strings.LastIndex(src, "/")+1:]
dst += "/" + lastPath
for i := 0; Exists(dst); i++ {
dst = dstPath + "/" + lastPath + strconv.Itoa(i+1)
}
if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
return err
}
if fds, err = ioutil.ReadDir(src); err != nil {
return err
}
for _, fd := range fds {
srcfp := path.Join(src, fd.Name())
dstfp := dst //path.Join(dst, fd.Name())
if fd.IsDir() {
if err = CopyDir(srcfp, dstfp); err != nil {
fmt.Println(err)
}
} else {
if err = CopyFile(srcfp, dstfp); err != nil {
fmt.Println(err)
}
}
}
return nil
}
func WriteToPath(data []byte, path, name string) error {
fullPath := path
if strings.HasSuffix(path, "/") {
fullPath += name
} else {
fullPath += "/" + name
}
IsNotExistCreateFile(fullPath)
file, err := os.OpenFile(fullPath,
os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
0666,
)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(data)
return err
}
//最终拼接
func SpliceFiles(dir, path string, length int, startPoint int) error {
fullPath := path
IsNotExistCreateFile(fullPath)
file, _ := os.OpenFile(fullPath,
os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
0666,
)
defer file.Close()
bufferedWriter := bufio.NewWriter(file)
for i := 0; i < length+startPoint; i++ {
data, err := ioutil.ReadFile(dir + "/" + strconv.Itoa(i+startPoint))
if err != nil {
return err
}
_, err = bufferedWriter.Write(data)
if err != nil {
return err
}
}
bufferedWriter.Flush()
return nil
}

84
pkg/utils/file/image.go Normal file
View File

@@ -0,0 +1,84 @@
package file
import (
"bytes"
"fmt"
"io"
"os"
"github.com/disintegration/imaging"
"github.com/dsoprea/go-exif/v3"
exifcommon "github.com/dsoprea/go-exif/v3/common"
)
func GetImage(path string, width, height int) ([]byte, error) {
if thumbnail, err := GetThumbnailByOwnerPhotos(path); err == nil {
return thumbnail, nil
} else {
return GetThumbnailByWebPhoto(path, width, height)
}
}
func GetThumbnailByOwnerPhotos(path string) ([]byte, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
buff := &bytes.Buffer{}
defer file.Close()
offset := 0
offsets := []int{12, 30}
head := make([]byte, 0xffff)
r := io.TeeReader(file, buff)
_, err = r.Read(head)
if err != nil {
return nil, err
}
for _, offset = range offsets {
if _, err = exif.ParseExifHeader(head[offset:]); err == nil {
break
}
}
if err != nil {
return nil, err
}
im, err := exifcommon.NewIfdMappingWithStandard()
if err != nil {
return nil, err
}
_, index, err := exif.Collect(im, exif.NewTagIndex(), head[offset:])
if err != nil {
return nil, err
}
ifd := index.RootIfd.NextIfd()
if ifd == nil {
return nil, exif.ErrNoThumbnail
}
thumbnail, err := ifd.Thumbnail()
if err != nil {
return nil, err
}
return thumbnail, nil
}
func GetThumbnailByWebPhoto(path string, width, height int) ([]byte, error) {
src, err := imaging.Open(path)
if err != nil {
fmt.Println(err)
return nil, err
}
img := imaging.Resize(src, width, 0, imaging.Lanczos)
f, err := imaging.FormatFromFilename(path)
if err != nil {
return nil, err
}
buf := bytes.Buffer{}
imaging.Encode(&buf, img, f)
return buf.Bytes(), nil
}

176
pkg/utils/file/reader.go Normal file
View File

@@ -0,0 +1,176 @@
package file
import (
"bytes"
"fmt"
"io"
"os"
)
var (
buffSize = 1 << 20
)
// ReadLineFromEnd --
type ReadLineFromEnd struct {
f *os.File
fileSize int
bwr *bytes.Buffer
lineBuff []byte
swapBuff []byte
isFirst bool
}
// NewReadLineFromEnd --
func NewReadLineFromEnd(name string) (rd *ReadLineFromEnd, err error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
info, err := f.Stat()
if info.IsDir() {
return nil, fmt.Errorf("not file")
}
fileSize := int(info.Size())
rd = &ReadLineFromEnd{
f: f,
fileSize: fileSize,
bwr: bytes.NewBuffer([]byte{}),
lineBuff: make([]byte, 0),
swapBuff: make([]byte, buffSize),
isFirst: true,
}
return rd, nil
}
// ReadLine 结尾包含'\n'
func (c *ReadLineFromEnd) ReadLine() (line []byte, err error) {
var ok bool
for {
ok, err = c.buff()
if err != nil {
return nil, err
}
if ok {
break
}
}
line, err = c.bwr.ReadBytes('\n')
if err == io.EOF && c.fileSize > 0 {
err = nil
}
return line, err
}
// Close --
func (c *ReadLineFromEnd) Close() (err error) {
return c.f.Close()
}
func (c *ReadLineFromEnd) buff() (ok bool, err error) {
if c.fileSize == 0 {
return true, nil
}
if c.bwr.Len() >= buffSize {
return true, nil
}
offset := 0
if c.fileSize > buffSize {
offset = c.fileSize - buffSize
}
_, err = c.f.Seek(int64(offset), 0)
if err != nil {
return false, err
}
n, err := c.f.Read(c.swapBuff)
if err != nil && err != io.EOF {
return false, err
}
if c.fileSize < n {
n = c.fileSize
}
if n == 0 {
return true, nil
}
for {
m := bytes.LastIndex(c.swapBuff[:n], []byte{'\n'})
if m == -1 {
break
}
if m < n-1 {
err = c.writeLine(c.swapBuff[m+1 : n])
if err != nil {
return false, err
}
ok = true
} else if m == n-1 && !c.isFirst {
err = c.writeLine(nil)
if err != nil {
return false, err
}
ok = true
}
n = m
if n == 0 {
break
}
}
if n > 0 {
reverseBytes(c.swapBuff[:n])
c.lineBuff = append(c.lineBuff, c.swapBuff[:n]...)
}
if offset == 0 {
err = c.writeLine(nil)
if err != nil {
return false, err
}
ok = true
}
c.fileSize = offset
if c.isFirst {
c.isFirst = false
}
return ok, nil
}
func (c *ReadLineFromEnd) writeLine(b []byte) (err error) {
if len(b) > 0 {
_, err = c.bwr.Write(b)
if err != nil {
return err
}
}
if len(c.lineBuff) > 0 {
reverseBytes(c.lineBuff)
_, err = c.bwr.Write(c.lineBuff)
if err != nil {
return err
}
c.lineBuff = c.lineBuff[:0]
}
_, err = c.bwr.Write([]byte{'\n'})
if err != nil {
return err
}
return nil
}
func reverseBytes(b []byte) {
n := len(b)
if n <= 1 {
return
}
for i := 0; i < n; i++ {
k := n - 1
if k != i {
b[i], b[k] = b[k], b[i]
}
n--
}
}

View File

@@ -2,25 +2,62 @@ package httper
import (
"bytes"
"encoding/json"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/tidwall/gjson"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/tidwall/gjson"
)
//发送GET请求
//url:请求地址
//response:请求返回的内容
func Get(url string, head map[string]string) (response string) {
client := http.Client{Timeout: 30 * time.Second}
client := &http.Client{Timeout: 30 * time.Second}
req, err := http.NewRequest("GET", url, nil)
req.BasicAuth()
for k, v := range head {
req.Header.Add(k, v)
}
if err != nil {
return ""
}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
//需要错误日志的处理
//loger.Error(error)
return ""
//panic(error)
}
defer resp.Body.Close()
var buffer [512]byte
result := bytes.NewBuffer(nil)
for {
n, err := resp.Body.Read(buffer[0:])
result.Write(buffer[0:n])
if err != nil && err == io.EOF {
break
} else if err != nil {
//loger.Error(err)
return ""
// panic(err)
}
}
response = result.String()
return
}
//发送GET请求
//url:请求地址
//response:请求返回的内容
func PersonGet(url string) (response string) {
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return ""
}
@@ -52,10 +89,13 @@ func Get(url string, head map[string]string) (response string) {
//发送POST请求
//url:请求地址data:POST请求提交的数据,contentType:请求体格式application/json
//content:请求放回的内容
func Post(url string, data interface{}, contentType string) (content string) {
jsonStr, _ := json.Marshal(data)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
func Post(url string, data []byte, contentType string, head map[string]string) (content string) {
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
req.Header.Add("content-type", contentType)
for k, v := range head {
req.Header.Add(k, v)
}
if err != nil {
panic(err)
}
@@ -63,7 +103,8 @@ func Post(url string, data interface{}, contentType string) (content string) {
client := &http.Client{Timeout: 5 * time.Second}
resp, error := client.Do(req)
if error != nil {
panic(error)
fmt.Println(error)
return
}
defer resp.Body.Close()
@@ -72,88 +113,6 @@ func Post(url string, data interface{}, contentType string) (content string) {
return
}
//发送POST请求
//url:请求地址data:POST请求提交的数据,contentType:请求体格式application/json
//content:请求放回的内容
func ZeroTierPost(url string, data map[string]string, head map[string]string, cookies []*http.Cookie) (content string, code int) {
b, _ := json.Marshal(data)
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
for _, cookie := range cookies {
req.AddCookie(cookie)
}
for k, v := range head {
req.Header.Add(k, v)
}
if err != nil {
panic(err)
}
client := &http.Client{Timeout: 20 * time.Second}
resp, error := client.Do(req)
if error != nil {
panic(error)
}
defer resp.Body.Close()
code = resp.StatusCode
result, _ := ioutil.ReadAll(resp.Body)
content = string(result)
return
}
//发送POST请求
//url:请求地址data:POST请求提交的数据,contentType:请求体格式application/json
//content:请求放回的内容
func ZeroTierPostJson(url string, data string, head map[string]string) (content string, code int) {
var postData *bytes.Buffer
jsonStr := []byte(data)
postData = bytes.NewBuffer(jsonStr)
req, err := http.NewRequest("POST", url, postData)
for k, v := range head {
req.Header.Add(k, v)
}
if err != nil {
panic(err)
}
client := &http.Client{Timeout: 20 * time.Second}
resp, error := client.Do(req)
if error != nil {
panic(error)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
content = string(result)
code = resp.StatusCode
return
}
func ZeroTierDelete(url string, head map[string]string) (content string, code int) {
req, err := http.NewRequest("DELETE", url, nil)
for k, v := range head {
req.Header.Add(k, v)
}
if err != nil {
panic(err)
}
client := &http.Client{Timeout: 20 * time.Second}
resp, error := client.Do(req)
if error != nil {
panic(error)
}
defer resp.Body.Close()
result, _ := ioutil.ReadAll(resp.Body)
content = string(result)
code = resp.StatusCode
return
}
//发送POST请求
//url:请求地址data:POST请求提交的数据,contentType:请求体格式application/json
//content:请求放回的内容

View File

@@ -1 +0,0 @@
package utils

View File

@@ -1,9 +1,10 @@
package ip_helper
import (
httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
"net"
"strings"
httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
)
func IsIPv4(address string) bool {
@@ -39,3 +40,35 @@ func GetLoclIp() string {
}
return "127.0.0.1"
}
func GetDeviceAllIP(port string) []string {
var address []string
addrs, err := net.InterfaceAddrs()
if err != nil {
return address
}
for _, a := range addrs {
if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To16() != nil {
address = append(address, ipNet.IP.String()+":"+port)
}
}
}
return address
}
func HasLocalIP(ip net.IP) bool {
if ip.IsLoopback() {
return true
}
ip.String()
ip4 := ip.To4()
if ip4 == nil {
return false
}
return ip4[0] == 10 || // 10.0.0.0/8
(ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31) || // 172.16.0.0/12
(ip4[0] == 169 && ip4[1] == 254) || // 169.254.0.0/16
(ip4[0] == 192 && ip4[1] == 168) // 192.168.0.0/16
}

View File

@@ -2,6 +2,7 @@ package ip_helper
import (
"fmt"
"net"
"testing"
)
@@ -20,3 +21,7 @@ func TestGetExternalIPV6(t *testing.T) {
func TestGetLoclIp(t *testing.T) {
fmt.Println(GetLoclIp())
}
func TestHasLocalIP(t *testing.T) {
fmt.Println("dddd")
fmt.Println(HasLocalIP(net.ParseIP("192.168.2.10")))
}

View File

@@ -1,8 +1,9 @@
package jwt
import (
jwt "github.com/dgrijalva/jwt-go"
"time"
jwt "github.com/golang-jwt/jwt"
)
type Claims struct {
@@ -15,8 +16,7 @@ var jwtSecret []byte
//创建token
func GenerateToken(username, password string) (string, error) {
nowTime := time.Now()
expireTime := nowTime.Add(3 * time.Hour)
expireTime := time.Now().AddDate(999, 0, 0)
clims := Claims{
username,
password,

View File

@@ -2,12 +2,12 @@ package jwt
import (
"fmt"
"net/http"
"github.com/IceWhaleTech/CasaOS/model"
loger2 "github.com/IceWhaleTech/CasaOS/pkg/utils/loger"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func JWT(swagHandler gin.HandlerFunc) gin.HandlerFunc {
@@ -22,13 +22,15 @@ func JWT(swagHandler gin.HandlerFunc) gin.HandlerFunc {
code = oasis_err2.INVALID_PARAMS
}
if swagHandler == nil {
claims, err := ParseToken(token)
//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
}
//else if time.Now().Unix() > claims.ExpiresAt {
// code = oasis_err2.ERROR_AUTH_TOKEN
//}
}
if code != oasis_err2.SUCCESS {

View File

@@ -2,13 +2,13 @@ package loger
import (
"fmt"
"github.com/IceWhaleTech/CasaOS/pkg/config"
file2 "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"log"
"os"
"path/filepath"
"runtime"
"time"
"github.com/IceWhaleTech/CasaOS/pkg/config"
file2 "github.com/IceWhaleTech/CasaOS/pkg/utils/file"
)
//定义一个int的别名
@@ -20,6 +20,7 @@ type OLog interface {
Warn(v ...interface{})
Error(v ...interface{})
Fatal(v ...interface{})
Path() string
}
type oLog struct {
@@ -47,9 +48,8 @@ const (
func LogSetup() {
var err error
filePath := fmt.Sprintf("%s", config.AppInfo.LogSavePath)
fileName := fmt.Sprintf("%s%s.%s",
fileName := fmt.Sprintf("%s.%s",
config.AppInfo.LogSaveName,
time.Now().Format(config.AppInfo.DateStrFormat),
config.AppInfo.LogFileExt,
)
F, err = file2.MustOpen(fileName, filePath)
@@ -60,7 +60,14 @@ func LogSetup() {
logger = log.New(F, DefaultPrefix, log.LstdFlags)
}
func (o *oLog) Path() string {
filePath := fmt.Sprintf("%s", config.AppInfo.LogSavePath)
fileName := fmt.Sprintf("%s.%s",
config.AppInfo.LogSaveName,
config.AppInfo.LogFileExt,
)
return filePath + fileName
}
func (o *oLog) Debug(v ...interface{}) {
setPrefix(DEBUG)
logger.Println(v)

View File

@@ -0,0 +1,30 @@
/*
* @Author: LinkLeong a624669980@163.com
* @Date: 2022-05-08 14:58:46
* @LastEditors: LinkLeong a624669980@163.com
* @LastEditTime: 2022-05-09 13:42:26
* @FilePath: /CasaOS/pkg/utils/network_detection.go
* @Description:
*
* Copyright (c) 2022 by LinkLeong a624669980@163.com, All Rights Reserved.
*/
package utils
import natType "github.com/Curtis-Milo/nat-type-identifier-go"
/**
* @description:
* @param {chanstring} data
* @param {string} url
* @return {*}
*/
func GetNetWorkTypeDetection(data chan string, url string) {
// fmt.Println("url:", url)
// httper.Get(url, nil)
// aaa <- url
result, err := natType.GetDeterminedNatType(true, 5, url)
if err == nil {
data <- result
}
}

View File

@@ -0,0 +1,29 @@
/*
* @Author: LinkLeong a624669980@163.com
* @Date: 2022-05-08 15:07:31
* @LastEditors: LinkLeong a624669980@163.com
* @LastEditTime: 2022-05-09 11:43:30
* @FilePath: /CasaOS/pkg/utils/network_detection_test.go
* @Description:
*
* Copyright (c) 2022 by LinkLeong a624669980@163.com, All Rights Reserved.
*/
package utils
import (
"fmt"
"testing"
)
func TestGetResultTest(t *testing.T) {
list := []string{"https://www.google.com", "https://www.bing.com", "https://www.baidu.com"}
data := make(chan string)
//data <- "init"
for _, v := range list {
go GetNetWorkTypeDetection(data, v)
}
result := <-data
close(data)
fmt.Println(result)
}

View File

@@ -7,53 +7,102 @@ const (
ERROR_AUTH_TOKEN = 401
//user
PWD_INVALID = 10001
PWD_INVALID = 10001
PWD_IS_EMPTY = 10002
PWD_INVALID_OLD = 10003
ACCOUNT_LOCK = 10004
//system
DIR_ALREADY_EXISTS = 20001
DIR_ALREADY_EXISTS = 20001
FILE_ALREADY_EXISTS = 20002
FILE_OR_DIR_EXISTS = 20003
PORT_IS_OCCUPIED = 20004
COMMAND_ERROR_INVALID_OPERATION = 20005
//zerotier
GET_TOKEN_ERROR = 30001
//disk
NAME_NOT_AVAILABLE = 40001
DISK_NEEDS_FORMAT = 40002
DISK_BUSYING = 40003
REMOVE_MOUNT_POINT_ERROR = 40004
FORMAT_ERROR = 40005
//app
UNINSTALL_APP_ERROR = 50001
PULL_IMAGE_ERROR = 50002
DEVICE_NOT_EXIST = 50003
UNINSTALL_APP_ERROR = 50001
PULL_IMAGE_ERROR = 50002
DEVICE_NOT_EXIST = 50003
ERROR_APP_NAME_EXIST = 50004
//file
FILE_DOES_NOT_EXIST = 60001
FILE_READ_ERROR = 60002
FILE_DELETE_ERROR = 60003
DIR_NOT_EXISTS = 60004
//shortcuts
SHORTCUTS_URL_ERROR = 70001
//person
PERSON_REMOTE_ERROR = 80001
PERSON_DOWN_NOT_EXIST = 80002
PERSON_EXIST_DOWNLOAD = 80003
PERSON_NOT_EXIST_USER = 80004
PERSON_EXIST_FRIEND = 80005
PERSON_MYSELF = 80006
)
var MsgFlags = map[int]string{
SUCCESS: "ok",
ERROR: "fail",
INVALID_PARAMS: "Invalid params",
ERROR_AUTH_TOKEN: "error auth token",
INVALID_PARAMS: "Parameters Error",
ERROR_AUTH_TOKEN: "Error auth token",
//user
PWD_INVALID: "Password invalid",
PWD_INVALID: "Invalid password",
PWD_IS_EMPTY: "Password is empty",
PWD_INVALID_OLD: "Invalid old password",
ACCOUNT_LOCK: "Account is locked",
//system
DIR_ALREADY_EXISTS: "Directory already exists",
DIR_ALREADY_EXISTS: "Folder already exists",
FILE_ALREADY_EXISTS: "File already exists",
FILE_OR_DIR_EXISTS: "File or folder already exists",
PORT_IS_OCCUPIED: "Port is occupied",
//zerotier
GET_TOKEN_ERROR: "Get token error,Please log in to zerotier's official website to confirm whether the account is available",
//app
UNINSTALL_APP_ERROR: "uninstall app error",
PULL_IMAGE_ERROR: "pull image error",
DEVICE_NOT_EXIST: "device not exist",
UNINSTALL_APP_ERROR: "Error uninstalling app",
PULL_IMAGE_ERROR: "Error pulling image",
DEVICE_NOT_EXIST: "Device does not exist",
ERROR_APP_NAME_EXIST: "App name already exists",
//disk
NAME_NOT_AVAILABLE: "Name not available",
DISK_NEEDS_FORMAT: "Drive needs to be formatted",
REMOVE_MOUNT_POINT_ERROR: "Failed to remove mount point",
DISK_BUSYING: "Drive is busy",
FORMAT_ERROR: "Formatting failed, please check if the directory is occupied",
//
FILE_DOES_NOT_EXIST: "file does not exist",
FILE_DOES_NOT_EXIST: "File does not exist",
FILE_READ_ERROR: "file read error",
SHORTCUTS_URL_ERROR: "url error",
DIR_NOT_EXISTS: "Directory does not exist",
FILE_READ_ERROR: "File read error",
FILE_DELETE_ERROR: "Delete error",
SHORTCUTS_URL_ERROR: "URL error",
PERSON_REMOTE_ERROR: "Remote connection error",
PERSON_DOWN_NOT_EXIST: "Download record does not exist",
PERSON_EXIST_DOWNLOAD: "The same download task exists",
PERSON_EXIST_FRIEND: "Friend already exist",
PERSON_NOT_EXIST_USER: "User does not exist",
PERSON_MYSELF: "You can not add yourself",
COMMAND_ERROR_INVALID_OPERATION: "invalid operation",
}
//获取错误信息

View File

@@ -47,6 +47,7 @@ func IsPortAvailable(port int, t string) bool {
uc, err := net.ListenUDP("udp", sadd)
if err != nil {
fmt.Println(err.Error())
return false
} else {
defer uc.Close()

View File

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

View File

@@ -1,73 +0,0 @@
package sort
import (
"github.com/IceWhaleTech/CasaOS/model"
"sort"
)
// 数据集类型, 与上一篇排序文章(多字段单独排序)比较, less字段的数据类型不再是 func(p1, p2 *Change) bool
// 而是 []func(p1, p2 *Change) bool 因为在第一个比较的值相等的情况下, 还要比较第二个值, 所以这里需要多个比较函数
type devSorter struct {
dev []model.Devices
less []lessFuncDev
}
// sort接口方法之一(Less)
type lessFuncDev func(p1, p2 *model.Devices) bool
// Sort 函数有两个作用
// 第一, 将参数(实际的数据集)赋值给ms对象
// 第二, 调用内置sort函数进行排序操作
func (ms *devSorter) Sort(dev []model.Devices) {
ms.dev = dev
sort.Sort(ms)
}
// OrderedBy 函数的作用是返回一个multiSorter实例, 并将所有的实际排序函数赋值给实例的less字段,
// 上面已经为multiSorter结构体定义了Sort方法, 所以该函数的返回值可以直接调用Sort方法进行排序
// 该函数中, 为multiSorter结构体中的less字段赋值, Sort方法中又将实际数据集传入, 赋值给multiSorter的ports字段
// 一个函数, 一个方法调用过后, multiSorter实例中两个字段就已经全部被正确赋值, 可以调用系统sort函数进行排序
// 该函数也可看作是一个工厂方法, 用来生成less字段已经被赋值的multiSorter实例
func DevSort(less ...lessFuncDev) *devSorter {
return &devSorter{
less: less,
}
}
// Len 为sort接口方法之一
func (ms *devSorter) Len() int {
return len(ms.dev)
}
// Swap 为sort接口方法之一
func (ms *devSorter) Swap(i, j int) {
ms.dev[i], ms.dev[j] = ms.dev[j], ms.dev[i]
}
// Less 为sort接口方法之一
func (ms *devSorter) Less(i, j int) bool {
temp := ms.dev
p, q := &temp[i], &temp[j]
// Try all but the last comparison.
var k int
// 由于可能有多个需要排序的字段, 也就对应了多个less函数, 当第一个字段的值相等时,
// 需要依次尝试比对后续其他字段的值得大小, 所以这里需要获取比较函数的长度, 以便遍历比较
for k = 0; k < len(ms.less)-1; k++ {
// 提取比较函数, 将函数赋值到新的变量中以便调用
less := ms.less[k]
switch {
case less(p, q):
// 如果 p < q, 返回值为true, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
// 如果 p > q, 返回值为false, 则调到下一个case中处理
return true
case less(q, p):
// 如果 p > q, 返回值为false, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
return false
}
// 如果代码走到这里, 说明ms.less[k]函数比较后 p == q; 重新开始下一次循环, 更换到下一个比较函数处理
continue
}
// 如果代码走到这里, 说明所有的比较函数执行过后, 所有比较的值都相等
// 直接返回最后一次的比较结果数据即可
return ms.less[k](p, q)
}

View File

@@ -1,73 +0,0 @@
package sort
import (
"github.com/IceWhaleTech/CasaOS/model"
"sort"
)
// 数据集类型, 与上一篇排序文章(多字段单独排序)比较, less字段的数据类型不再是 func(p1, p2 *Change) bool
// 而是 []func(p1, p2 *Change) bool 因为在第一个比较的值相等的情况下, 还要比较第二个值, 所以这里需要多个比较函数
type evnSorter struct {
evn []model.Envs
less []lessFuncEnv
}
// sort接口方法之一(Less)
type lessFuncEnv func(p1, p2 *model.Envs) bool
// Sort 函数有两个作用
// 第一, 将参数(实际的数据集)赋值给ms对象
// 第二, 调用内置sort函数进行排序操作
func (ms *evnSorter) Sort(env []model.Envs) {
ms.evn = env
sort.Sort(ms)
}
// OrderedBy 函数的作用是返回一个multiSorter实例, 并将所有的实际排序函数赋值给实例的less字段,
// 上面已经为multiSorter结构体定义了Sort方法, 所以该函数的返回值可以直接调用Sort方法进行排序
// 该函数中, 为multiSorter结构体中的less字段赋值, Sort方法中又将实际数据集传入, 赋值给multiSorter的ports字段
// 一个函数, 一个方法调用过后, multiSorter实例中两个字段就已经全部被正确赋值, 可以调用系统sort函数进行排序
// 该函数也可看作是一个工厂方法, 用来生成less字段已经被赋值的multiSorter实例
func EnvSort(less ...lessFuncEnv) *evnSorter {
return &evnSorter{
less: less,
}
}
// Len 为sort接口方法之一
func (ms *evnSorter) Len() int {
return len(ms.evn)
}
// Swap 为sort接口方法之一
func (ms *evnSorter) Swap(i, j int) {
ms.evn[i], ms.evn[j] = ms.evn[j], ms.evn[i]
}
// Less 为sort接口方法之一
func (ms *evnSorter) Less(i, j int) bool {
temp := ms.evn
p, q := &temp[i], &temp[j]
// Try all but the last comparison.
var k int
// 由于可能有多个需要排序的字段, 也就对应了多个less函数, 当第一个字段的值相等时,
// 需要依次尝试比对后续其他字段的值得大小, 所以这里需要获取比较函数的长度, 以便遍历比较
for k = 0; k < len(ms.less)-1; k++ {
// 提取比较函数, 将函数赋值到新的变量中以便调用
less := ms.less[k]
switch {
case less(p, q):
// 如果 p < q, 返回值为true, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
// 如果 p > q, 返回值为false, 则调到下一个case中处理
return true
case less(q, p):
// 如果 p > q, 返回值为false, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
return false
}
// 如果代码走到这里, 说明ms.less[k]函数比较后 p == q; 重新开始下一次循环, 更换到下一个比较函数处理
continue
}
// 如果代码走到这里, 说明所有的比较函数执行过后, 所有比较的值都相等
// 直接返回最后一次的比较结果数据即可
return ms.less[k](p, q)
}

View File

@@ -1,73 +0,0 @@
package sort
import (
"github.com/IceWhaleTech/CasaOS/model"
"sort"
)
// 数据集类型, 与上一篇排序文章(多字段单独排序)比较, less字段的数据类型不再是 func(p1, p2 *Change) bool
// 而是 []func(p1, p2 *Change) bool 因为在第一个比较的值相等的情况下, 还要比较第二个值, 所以这里需要多个比较函数
type multiSorter struct {
ports []model.Ports
less []lessFunc
}
// sort接口方法之一(Less)
type lessFunc func(p1, p2 *model.Ports) bool
// Sort 函数有两个作用
// 第一, 将参数(实际的数据集)赋值给ms对象
// 第二, 调用内置sort函数进行排序操作
func (ms *multiSorter) Sort(ports []model.Ports) {
ms.ports = ports
sort.Sort(ms)
}
// OrderedBy 函数的作用是返回一个multiSorter实例, 并将所有的实际排序函数赋值给实例的less字段,
// 上面已经为multiSorter结构体定义了Sort方法, 所以该函数的返回值可以直接调用Sort方法进行排序
// 该函数中, 为multiSorter结构体中的less字段赋值, Sort方法中又将实际数据集传入, 赋值给multiSorter的ports字段
// 一个函数, 一个方法调用过后, multiSorter实例中两个字段就已经全部被正确赋值, 可以调用系统sort函数进行排序
// 该函数也可看作是一个工厂方法, 用来生成less字段已经被赋值的multiSorter实例
func PortsSort(less ...lessFunc) *multiSorter {
return &multiSorter{
less: less,
}
}
// Len 为sort接口方法之一
func (ms *multiSorter) Len() int {
return len(ms.ports)
}
// Swap 为sort接口方法之一
func (ms *multiSorter) Swap(i, j int) {
ms.ports[i], ms.ports[j] = ms.ports[j], ms.ports[i]
}
// Less 为sort接口方法之一
func (ms *multiSorter) Less(i, j int) bool {
port := ms.ports
p, q := &port[i], &port[j]
// Try all but the last comparison.
var k int
// 由于可能有多个需要排序的字段, 也就对应了多个less函数, 当第一个字段的值相等时,
// 需要依次尝试比对后续其他字段的值得大小, 所以这里需要获取比较函数的长度, 以便遍历比较
for k = 0; k < len(ms.less)-1; k++ {
// 提取比较函数, 将函数赋值到新的变量中以便调用
less := ms.less[k]
switch {
case less(p, q):
// 如果 p < q, 返回值为true, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
// 如果 p > q, 返回值为false, 则调到下一个case中处理
return true
case less(q, p):
// 如果 p > q, 返回值为false, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
return false
}
// 如果代码走到这里, 说明ms.less[k]函数比较后 p == q; 重新开始下一次循环, 更换到下一个比较函数处理
continue
}
// 如果代码走到这里, 说明所有的比较函数执行过后, 所有比较的值都相等
// 直接返回最后一次的比较结果数据即可
return ms.less[k](p, q)
}

View File

@@ -1,73 +0,0 @@
package sort
import (
"github.com/IceWhaleTech/CasaOS/model"
"sort"
)
// 数据集类型, 与上一篇排序文章(多字段单独排序)比较, less字段的数据类型不再是 func(p1, p2 *Change) bool
// 而是 []func(p1, p2 *Change) bool 因为在第一个比较的值相等的情况下, 还要比较第二个值, 所以这里需要多个比较函数
type volSorter struct {
vol []model.Volume
less []lessFuncVol
}
// sort接口方法之一(Less)
type lessFuncVol func(p1, p2 *model.Volume) bool
// Sort 函数有两个作用
// 第一, 将参数(实际的数据集)赋值给ms对象
// 第二, 调用内置sort函数进行排序操作
func (ms *volSorter) Sort(vol []model.Volume) {
ms.vol = vol
sort.Sort(ms)
}
// OrderedBy 函数的作用是返回一个multiSorter实例, 并将所有的实际排序函数赋值给实例的less字段,
// 上面已经为multiSorter结构体定义了Sort方法, 所以该函数的返回值可以直接调用Sort方法进行排序
// 该函数中, 为multiSorter结构体中的less字段赋值, Sort方法中又将实际数据集传入, 赋值给multiSorter的ports字段
// 一个函数, 一个方法调用过后, multiSorter实例中两个字段就已经全部被正确赋值, 可以调用系统sort函数进行排序
// 该函数也可看作是一个工厂方法, 用来生成less字段已经被赋值的multiSorter实例
func VolSort(less ...lessFuncVol) *volSorter {
return &volSorter{
less: less,
}
}
// Len 为sort接口方法之一
func (ms *volSorter) Len() int {
return len(ms.vol)
}
// Swap 为sort接口方法之一
func (ms *volSorter) Swap(i, j int) {
ms.vol[i], ms.vol[j] = ms.vol[j], ms.vol[i]
}
// Less 为sort接口方法之一
func (ms *volSorter) Less(i, j int) bool {
temp := ms.vol
p, q := &temp[i], &temp[j]
// Try all but the last comparison.
var k int
// 由于可能有多个需要排序的字段, 也就对应了多个less函数, 当第一个字段的值相等时,
// 需要依次尝试比对后续其他字段的值得大小, 所以这里需要获取比较函数的长度, 以便遍历比较
for k = 0; k < len(ms.less)-1; k++ {
// 提取比较函数, 将函数赋值到新的变量中以便调用
less := ms.less[k]
switch {
case less(p, q):
// 如果 p < q, 返回值为true, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
// 如果 p > q, 返回值为false, 则调到下一个case中处理
return true
case less(q, p):
// 如果 p > q, 返回值为false, 不存在两个值相等需要比较后续字段的情况, 所以这里直接返回
return false
}
// 如果代码走到这里, 说明ms.less[k]函数比较后 p == q; 重新开始下一次循环, 更换到下一个比较函数处理
continue
}
// 如果代码走到这里, 说明所有的比较函数执行过后, 所有比较的值都相等
// 直接返回最后一次的比较结果数据即可
return ms.less[k](p, q)
}

View File

@@ -2,13 +2,14 @@ package version
import (
json2 "encoding/json"
"strconv"
"strings"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/tidwall/gjson"
"strconv"
"strings"
)
func IsNeedUpdate() (bool, model.Version) {
@@ -35,3 +36,48 @@ func IsNeedUpdate() (bool, model.Version) {
}
return false, version
}
func IsClientNeedUpdate() (bool, model.Version) {
var version model.Version
v := httper.OasisGet(config.ServerInfo.ServerApi + "/v1/sys/client/version")
data := gjson.Get(v, "data")
json2.Unmarshal([]byte(data.String()), &version)
v1 := strings.Split(version.Version, ".")
v2 := strings.Split(types.CURRENTVERSION, ".")
for len(v1) < len(v2) {
v1 = append(v1, "0")
}
for len(v2) < len(v1) {
v2 = append(v2, "0")
}
for i := 0; i < len(v1); i++ {
a, _ := strconv.Atoi(v1[i])
b, _ := strconv.Atoi(v2[i])
if a > b {
return true, version
}
}
return false, version
}
//a版本大于b版本
func VersionCompared(a string, b string) bool {
v1 := strings.Split(a, ".")
v2 := strings.Split(b, ".")
for len(v1) < len(v2) {
v1 = append(v1, "0")
}
for len(v2) < len(v1) {
v2 = append(v2, "0")
}
for i := 0; i < len(v1); i++ {
a, _ := strconv.Atoi(v1[i])
b, _ := strconv.Atoi(v2[i])
if a > b {
return true
}
}
return false
}

View File

@@ -1,47 +0,0 @@
package zerotier
import (
httper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/httper"
"github.com/tidwall/gjson"
"net/http"
)
func PostData(url, token string, data string) interface{} {
body, code := httper2.ZeroTierPostJson(url, data, GetHead(token))
if code != http.StatusOK {
return ""
}
result := gjson.Parse(body)
return result.Value()
}
func GetData(url, token string) interface{} {
body, code := httper2.ZeroTierGet(url, GetHead(token))
if code != http.StatusOK {
return ""
}
result := gjson.Parse(body)
return result.Value()
}
func DeleteMember(url, token string) interface{} {
body, code := httper2.ZeroTierDelete(url, GetHead(token))
if code != http.StatusOK {
return ""
}
result := gjson.Parse(body)
return result.Value()
}
func GetHead(token string) map[string]string {
var head = make(map[string]string)
head["Authorization"] = "Bearer " + token
head["Content-Type"] = "application/json"
return head
}

View File

@@ -1,3 +1,4 @@
//go:build doc
// +build doc
package route
@@ -5,9 +6,10 @@ package route
import (
_ "github.com/IceWhaleTech/CasaOS/docs"
ginSwagger "github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
swaggerFiles "github.com/swaggo/gin-swagger/swaggerFiles"
)
func init() {
// swagHandler = ginSwagger.WrapHandler(swaggerFiles.Handler)
swagHandler = ginSwagger.WrapHandler(swaggerFiles.Handler)
}

298
route/init.go Normal file
View File

@@ -0,0 +1,298 @@
package route
import (
"encoding/xml"
"fmt"
"runtime"
"strconv"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/model/system_app"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/command"
"github.com/IceWhaleTech/CasaOS/pkg/utils/env_helper"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/port"
"github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
uuid "github.com/satori/go.uuid"
)
func InitFunction() {
go checkSystemApp()
Update2_3()
CheckSerialDiskMount()
CheckToken2_11()
ImportApplications()
ChangeAPIUrl()
InitSystemApplication()
}
var syncIsExistence = false
func installSyncthing(appId string) {
var appInfo model.ServerAppList
m := model.CustomizationPostData{}
var dockerImage string
var dockerImageVersion string
appInfo = service.MyService.Casa().GetServerAppInfo(appId, "system", "us_en")
dockerImage = appInfo.Image
dockerImageVersion = appInfo.ImageVersion
if len(appInfo.ImageVersion) == 0 {
dockerImageVersion = "latest"
}
if appInfo.NetworkModel != "host" {
for i := 0; i < len(appInfo.Ports); i++ {
if p, _ := strconv.Atoi(appInfo.Ports[i].ContainerPort); port.IsPortAvailable(p, appInfo.Ports[i].Protocol) {
appInfo.Ports[i].CommendPort = strconv.Itoa(p)
} else {
if appInfo.Ports[i].Protocol == "tcp" {
if p, err := port.GetAvailablePort("tcp"); err == nil {
appInfo.Ports[i].CommendPort = strconv.Itoa(p)
}
} else if appInfo.Ports[i].Protocol == "upd" {
if p, err := port.GetAvailablePort("udp"); err == nil {
appInfo.Ports[i].CommendPort = strconv.Itoa(p)
}
}
}
if appInfo.Ports[i].Type == 0 {
appInfo.PortMap = appInfo.Ports[i].CommendPort
}
}
}
for i := 0; i < len(appInfo.Devices); i++ {
if !file.CheckNotExist(appInfo.Devices[i].ContainerPath) {
appInfo.Devices[i].Path = appInfo.Devices[i].ContainerPath
}
}
if len(appInfo.Tip) > 0 {
appInfo.Tip = env_helper.ReplaceStringDefaultENV(appInfo.Tip)
}
appInfo.MaxMemory = service.MyService.ZiMa().GetMemInfo().Total >> 20
id := uuid.NewV4().String()
installLog := model2.AppNotify{}
// step下载镜像
err := service.MyService.Docker().DockerPullImage(dockerImage+":"+dockerImageVersion, installLog)
if err != nil {
//pull image error
fmt.Println("pull image error", err, dockerImage, dockerImageVersion)
return
}
for !service.MyService.Docker().IsExistImage(dockerImage + ":" + dockerImageVersion) {
time.Sleep(time.Second)
}
m.CpuShares = 50
m.Envs = appInfo.Envs
m.Memory = int64(appInfo.MaxMemory)
m.Origin = "system"
m.PortMap = appInfo.PortMap
m.Ports = appInfo.Ports
m.Restart = "always"
m.Volumes = appInfo.Volumes
m.Label = id
m.CustomId = id
containerId, err := service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m, appInfo.NetworkModel)
if err != nil {
fmt.Println("container create error", err)
// create container error
return
}
//stepstart container
err = service.MyService.Docker().DockerContainerStart(containerId)
if err != nil {
//start container error
return
}
checkSystemApp()
}
// check if the system application is installed
func checkSystemApp() {
list := service.MyService.App().GetSystemAppList()
for _, v := range list {
info, err := service.MyService.Docker().DockerContainerInfo(v.ID)
if err != nil {
continue
}
if strings.Contains(info.Config.Image, "linuxserver/syncthing") {
if v.State != "running" {
//stepstart container
service.MyService.Docker().DockerContainerStart(v.ID)
}
syncIsExistence = true
if config.SystemConfigInfo.SyncPort != v.Labels["web"] {
config.SystemConfigInfo.SyncPort = v.Labels["web"]
}
path := ""
for _, i := range info.HostConfig.Mounts {
if i.Target == "/config" {
path = i.Source
break
}
}
content := file.ReadFullFile(path + "config.xml")
syncConfig := &system_app.SyncConfig{}
xml.Unmarshal(content, &syncConfig)
config.SystemConfigInfo.SyncKey = syncConfig.Key
break
}
}
if !syncIsExistence {
installSyncthing("74")
}
}
func CheckSerialDiskMount() {
// check mount point
dbList := service.MyService.Disk().GetSerialAll()
list := service.MyService.Disk().LSBLK(true)
mountPoint := make(map[string]string, len(dbList))
//remount
for _, v := range dbList {
mountPoint[v.UUID] = v.MountPoint
}
for _, v := range list {
command.ExecEnabledSMART(v.Path)
if v.Children != nil {
for _, h := range v.Children {
if len(h.MountPoint) == 0 && len(v.Children) == 1 && h.FsType == "ext4" {
if m, ok := mountPoint[h.UUID]; ok {
//mount point check
volume := m
if !file.CheckNotExist(m) {
for i := 0; file.CheckNotExist(volume); i++ {
volume = m + strconv.Itoa(i+1)
}
}
service.MyService.Disk().MountDisk(h.Path, volume)
if volume != m {
ms := model2.SerialDisk{}
ms.UUID = v.UUID
ms.MountPoint = volume
service.MyService.Disk().UpdateMountPoint(ms)
}
}
}
}
}
}
service.MyService.Disk().RemoveLSBLKCache()
command.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/helper.sh ;AutoRemoveUnuseDir")
}
func Update2_3() {
command.OnlyExec("source " + config.AppInfo.ProjectPath + "/shell/assist.sh")
}
func CheckToken2_11() {
if len(config.ServerInfo.Token) == 0 {
token := uuid.NewV4().String
config.ServerInfo.Token = token()
config.Cfg.Section("server").Key("Token").SetValue(token())
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
if len(config.AppInfo.RootPath) == 0 {
config.Cfg.Section("app").Key("RootPath").SetValue("/casaOS")
config.AppInfo.RootPath = "/casaOS"
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
// if len(config.ServerInfo.Handshake) == 0 {
// config.Cfg.Section("app").Key("RootPath").SetValue("/casaOS")
// config.AppInfo.RootPath = "/casaOS"
// config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
// }
sysType := runtime.GOOS
if len(config.FileSettingInfo.DownloadDir) == 0 {
downloadPath := "/DATA/Downloads"
if sysType == "windows" {
downloadPath = "C:\\CasaOS\\DATA\\Downloads"
}
if sysType == "darwin" {
downloadPath = "./CasaOS/DATA/Downloads"
}
config.Cfg.Section("file").Key("DownloadDir").SetValue(downloadPath)
config.FileSettingInfo.DownloadDir = downloadPath
file.IsNotExistMkDir(config.FileSettingInfo.DownloadDir)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
if len(config.UserInfo.Description) == 0 {
config.Cfg.Section("user").Key("Description").SetValue("nothing")
config.UserInfo.Description = "nothing"
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
if len(config.ServerInfo.Handshake) == 0 {
config.Cfg.Section("server").Key("Handshake").SetValue("socket.casaos.io")
config.ServerInfo.Handshake = "socket.casaos.io"
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
if service.MyService.ZiMa().GetSysInfo().KernelArch == "aarch64" && config.ServerInfo.USBAutoMount != "True" && strings.Contains(service.MyService.ZiMa().GetDeviceTree(), "Raspberry Pi") {
service.MyService.System().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False")
}
// str := []string{}
// str = append(str, "ddd")
// str = append(str, "aaa")
// ddd := strings.Join(str, "|")
// config.Cfg.Section("file").Key("ShareDir").SetValue(ddd)
// config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
func ImportApplications() {
service.MyService.App().ImportApplications(true)
}
// 0.3.1
func ChangeAPIUrl() {
newAPIUrl := "https://api.casaos.io/casaos-api"
if config.ServerInfo.ServerApi == "https://api.casaos.zimaboard.com" {
config.ServerInfo.ServerApi = newAPIUrl
config.Cfg.Section("server").Key("ServerApi").SetValue(newAPIUrl)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
}
}
// 0.3.1
func InitSystemApplication() {
list := service.MyService.App().GetApplicationList()
if len(list) != 2 {
application := model2.ApplicationModel{}
application.Name = "Files"
application.Icon = "/ui/img/Files.svg"
application.Type = "system"
application.Order = 0
service.MyService.App().CreateApplication(application)
application.Name = "CasaConnect"
application.Icon = "/ui/img/CasaConnect.svg"
application.Type = "system"
application.Order = 0
service.MyService.App().CreateApplication(application)
}
}

View File

@@ -1,21 +1,26 @@
package route
import (
"net/http"
"github.com/IceWhaleTech/CasaOS/middleware"
"github.com/IceWhaleTech/CasaOS/pkg/config"
jwt2 "github.com/IceWhaleTech/CasaOS/pkg/utils/jwt"
v1 "github.com/IceWhaleTech/CasaOS/route/v1"
"github.com/IceWhaleTech/CasaOS/web"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"net/http"
)
var swagHandler gin.HandlerFunc
var OnlineDemo bool = false
func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
func InitRouter() *gin.Engine {
r := gin.Default()
r.Use(middleware.Cors())
r.Use(gzip.Gzip(gzip.DefaultCompression))
gin.SetMode(config.ServerInfo.RunMode)
r.StaticFS("/ui", http.FS(web.Static))
@@ -26,11 +31,18 @@ func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
if swagHandler != nil {
r.GET("/swagger/*any", swagHandler)
}
//登录
r.POST("/v1/user/login", v1.Login)
r.GET("/debug", v1.GetSystemConfigDebug)
r.GET("/v1/guide/check", v1.GetGuideCheck)
r.GET("/v1/debug", v1.GetSystemConfigDebug)
//set user
r.POST("/v1/user/setusernamepwd", v1.Set_Name_Pwd)
//get user info
r.GET("/v1/user/info", v1.GetUserInfo)
//get user info
r.GET("/v1/person/shareid", v1.GetPersonShareId)
v1Group := r.Group("/v1")
v1Group.Use(jwt2.JWT(swagHandler))
@@ -38,18 +50,21 @@ func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
v1UserGroup := v1Group.Group("/user")
v1UserGroup.Use()
{
//设置用户
v1UserGroup.POST("/setusernamepwd", v1.Set_Name_Pwd)
//chang head
v1UserGroup.POST("/changhead", v1.Up_Load_Head)
v1UserGroup.POST("/head", v1.PostUserHead)
//chang user name
v1UserGroup.PUT("/changusername", v1.Chang_User_Name)
v1UserGroup.PUT("/username", v1.PutUserName)
//chang pwd
v1UserGroup.PUT("/changuserpwd", v1.Chang_User_Pwd)
v1UserGroup.PUT("/password", v1.PutUserPwd)
//edit user info
v1UserGroup.POST("/changuserinfo", v1.Chang_User_Info)
//get user info
v1UserGroup.GET("/info", v1.UserInfo)
v1UserGroup.POST("/info", v1.PostUserChangeInfo)
v1UserGroup.PUT("/nick", v1.PutUserChangeNick)
v1UserGroup.PUT("/desc", v1.PutUserChangeDesc)
v1UserGroup.POST("/person/info", v1.PostUserPersonInfo)
v1UserGroup.GET("/shareid", v1.GetUserShareID)
}
v1ZiMaGroup := v1Group.Group("/zima")
@@ -64,56 +79,10 @@ func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
//获取网络信息
v1ZiMaGroup.GET("/getnetinfo", v1.NetInfo)
//获取网络信息
v1ZiMaGroup.GET("/getinfo", v1.Info)
//获取系统信息
v1ZiMaGroup.GET("/sysinfo", v1.SysInfo)
}
v1ZeroTierGroup := v1Group.Group("/zerotier")
v1ZeroTierGroup.Use()
{
//获取zerotier token
v1ZeroTierGroup.POST("/login", v1.ZeroTierGetToken)
//注册zerotier
v1ZeroTierGroup.POST("/register", v1.ZeroTierRegister)
//是否需要登录
v1ZeroTierGroup.GET("/islogin", v1.ZeroTierIsNeedLogin)
//获取网络列表
v1ZeroTierGroup.GET("/list", v1.ZeroTierGetNetworkList)
//加入网络
v1ZeroTierGroup.POST("/join/:id", v1.ZeroTierJoinNetwork)
//离开网络
v1ZeroTierGroup.POST("/leave/:id", v1.ZeroTierLeaveNetwork)
//详情
v1ZeroTierGroup.GET("/info/:id", v1.ZeroTierGetNetworkGetInfo)
////网络状态
//v1ZeroTierGroup.GET("/status", v1.ZeroTierGetNetworkGetStatus)
//修改网络类型
//v1ZeroTierGroup.PUT("/type/:id", v1.ZeroTierEditType)
//修改网络类型
//v1ZeroTierGroup.PUT("/name/:id", v1.ZeroTierEditName)
//修改v6 assign
//v1ZeroTierGroup.PUT("/v6assign/:id", v1.ZeroTierEditV6Assign)
//修改 broadcast
//v1ZeroTierGroup.PUT("/broadcast/:id", v1.ZeroTierEditBroadcast)
//create new network
v1ZeroTierGroup.POST("/create", v1.ZeroTierCreateNetwork)
//获取用户列表
v1ZeroTierGroup.GET("/member/:id", v1.ZeroTierMemberList)
//修改用户信息
//v1ZeroTierGroup.PUT("/members/:id/auth/:mId", v1.ZeroTierMemberAuth)
//修改网络用户name
//v1ZeroTierGroup.PUT("/members/:id/name/:mId", v1.ZeroTierMemberName)
v1ZeroTierGroup.DELETE("/members/:id/del/:mId", v1.ZeroTierMemberDelete)
v1ZeroTierGroup.DELETE("/network/:id/del", v1.ZeroTierDeleteNetwork)
//修改网络用户bridge功能
//v1ZeroTierGroup.PUT("/members/:id/bridge/:mId", v1.ZeroTierMemberBridge)
v1ZeroTierGroup.PUT("/edit/:id", v1.ZeroTierEdit)
v1ZeroTierGroup.GET("/joined/list", v1.ZeroTierJoinedList)
v1ZeroTierGroup.PUT("/member/:id/edit/:mId", v1.ZeroTierMemberEdit)
}
v1DDNSGroup := v1Group.Group("/ddns")
v1DDNSGroup.Use()
{
@@ -134,7 +103,9 @@ func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
v1AppGroup.Use()
{
//获取我的已安装的列表
v1AppGroup.GET("/mylist", v1.MyAppList)
v1AppGroup.GET("/my/list", v1.MyAppList)
//
v1AppGroup.GET("/usage", v1.AppUsageList)
//app详情
v1AppGroup.GET("/appinfo/:id", v1.AppInfo)
//获取未安装的列表
@@ -147,8 +118,8 @@ func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
v1AppGroup.GET("/category", v1.CategoryList)
//容器相关
v1AppGroup.GET("/terminal/:id", v1.DockerTerminal)
//准备安装
//v1AppGroup.GET("/ready/:id", v1.ReadyInstall)
v1AppGroup.GET("/order", v1.GetAppOrder)
v1AppGroup.POST("/order", v1.PostAppOrder)
//app容器详情
v1AppGroup.GET("/info/:id", v1.ContainerInfo)
//app容器日志
@@ -169,55 +140,80 @@ func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
v1AppGroup.GET("/update/:id/info", v1.ContainerUpdateInfo)
v1AppGroup.GET("/rely/:id/info", v1.ContainerRelyInfo)
v1AppGroup.GET("/install/config", v1.GetDockerInstallConfig)
//v1AppGroup.POST("/custom/install", v1.CustomInstallApp)
v1AppGroup.PUT("/update/:id", v1.PutAppUpdate)
v1AppGroup.POST("/share", v1.ShareAppFile)
}
v1SysGroup := v1Group.Group("/sys")
v1SysGroup.Use()
{
//获取检查版本是否需要升级
v1SysGroup.GET("/check", v1.CheckVersion)
v1SysGroup.GET("/hardware/info", v1.GetSystemHardwareInfo)
v1SysGroup.GET("/client/version", v1.GetClientVersion)
v1SysGroup.POST("/update", v1.SystemUpdate)
v1SysGroup.GET("/sys", v1.Sys)
v1SysGroup.GET("/wsssh", v1.WsSsh)
v1SysGroup.GET("/config", v1.GetSystemConfig)
v1SysGroup.GET("/error/logs", v1.GetCasaOSErrorLogs)
v1SysGroup.POST("/config", v1.PostSetSystemConfig)
v1SysGroup.GET("/widget/config", v1.GetWidgetConfig)
v1SysGroup.POST("/widget/config", v1.PostSetWidgetConfig)
v1SysGroup.GET("/port", v1.GetCasaOSPort)
v1SysGroup.PUT("/port", v1.PutCasaOSPort)
v1SysGroup.POST("/kill", v1.PostKillCasaOS)
v1SysGroup.GET("/info", v1.Info)
v1SysGroup.PUT("/usb/off", v1.PutSystemOffUSBAutoMount)
v1SysGroup.PUT("/usb/on", v1.PutSystemOnUSBAutoMount)
v1SysGroup.GET("/usb", v1.GetSystemUSBAutoMount)
}
v1FileGroup := v1Group.Group("/file")
v1FileGroup.Use()
{
//修改文件名称/目录名称
v1FileGroup.PUT("/rename", v1.RenamePath)
v1FileGroup.GET("/read", v1.GetFilerContent)
v1FileGroup.POST("/upload", v1.PostFileUpload)
v1FileGroup.GET("/upload", v1.GetFileUpload)
v1FileGroup.GET("/dirpath", v1.DirPath)
//创建目录
//create folder
v1FileGroup.POST("/mkdir", v1.MkdirAll)
v1FileGroup.POST("/create", v1.PostCreateFile)
v1FileGroup.GET("/download", v1.GetDownloadFile)
v1FileGroup.GET("/new/download", v1.GetFileDownloadNew)
v1FileGroup.POST("/operate", v1.PostOperateFileOrDir)
v1FileGroup.DELETE("/delete", v1.DeleteFile)
v1FileGroup.PUT("/update", v1.PutFileContent)
v1FileGroup.GET("/image", v1.GetFileImage)
//v1FileGroup.GET("/download", v1.UserFileDownloadCommonService)
}
v1DiskGroup := v1Group.Group("/disk")
v1DiskGroup.Use()
{
//获取磁盘列表
v1DiskGroup.GET("/list", v1.GetPlugInDisk)
v1DiskGroup.GET("/check", v1.GetDiskCheck)
v1DiskGroup.GET("/list", v1.GetDiskList)
//获取磁盘详情
v1DiskGroup.GET("/info", v1.GetDiskInfo)
//格式化磁盘
//format storage
v1DiskGroup.POST("/format", v1.FormatDisk)
//添加分区
v1DiskGroup.POST("/addpart", v1.AddPartition)
// add storage
v1DiskGroup.POST("/storage", v1.AddPartition)
//mount SATA disk
v1DiskGroup.POST("/mount", v1.PostMountDisk)
//umount sata disk
v1DiskGroup.POST("/umount", v1.PostDiskUmount)
//获取可以格式化的内容
v1DiskGroup.GET("/type", v1.FormatDiskType)
//删除分区
v1DiskGroup.DELETE("/delpart", v1.RemovePartition)
v1DiskGroup.GET("/usb", v1.GetUSBList)
}
v1ShareGroup := v1Group.Group("/share")
@@ -238,20 +234,48 @@ func InitRouter(swagHandler gin.HandlerFunc) *gin.Engine {
v1TaskGroup.PUT("/completion/:id", v1.PutTaskMarkerCompletion)
}
v1ShortcutsGroup := v1Group.Group("/shortcuts")
v1ShortcutsGroup.Use()
{
v1ShortcutsGroup.GET("/list", v1.GetShortcutsList)
v1ShortcutsGroup.POST("/add", v1.PostShortcutsAdd)
v1ShortcutsGroup.PUT("/edit", v1.PutShortcutsEdit)
v1ShortcutsGroup.DELETE("/del/:id", v1.DeleteShortcutsDelete)
}
v1NotifyGroup := v1Group.Group("/notify")
v1NotifyGroup.Use()
{
v1NotifyGroup.GET("/ws", v1.NotifyWS)
v1NotifyGroup.PUT("/read/:id", v1.PutNotifyRead)
}
v1PersonGroup := v1Group.Group("/person")
v1PersonGroup.Use()
{
v1PersonGroup.GET("/detection", v1.GetPersonDetection)
v1PersonGroup.GET("/users", v1.GetPersonFriend)
v1PersonGroup.POST("/user/:shareids", v1.PostAddPersonFriend)
v1PersonGroup.DELETE("/user/:shareid", v1.DeletePersonFriend)
v1PersonGroup.GET("/directory", v1.GetPersonDirectory)
v1PersonGroup.GET("/file", v1.GetPersonFile)
v1PersonGroup.GET("/refile/:uuid", v1.GetPersonReFile)
v1PersonGroup.PUT("/remarks/:shareid", v1.PutPersonRemarks)
v1PersonGroup.GET("/list", v1.GetPersonDownloadList)
v1PersonGroup.DELETE("/file/:uuid", v1.DeletePersonDownloadFile)
v1PersonGroup.POST("/share", v1.PostPersonShare)
v1PersonGroup.POST("/file/:shareid", v1.PostPersonFile)
v1PersonGroup.GET("/share", v1.GetPersonShare)
v1PersonGroup.POST("/down/dir", v1.PostPersonDownDir)
v1PersonGroup.GET("/down/dir", v1.GetPersonDownDir)
v1PersonGroup.PUT("/block/:shareid", v1.PutPersonBlock)
v1PersonGroup.GET("/public", v1.GetPersonPublic)
v1PersonGroup.PUT("/friend/:shareid", v1.PutPersonAgreeFriend)
v1PersonGroup.PUT("/write/:shareid", v1.PutPersonWrite)
v1PersonGroup.GET("/image/thumbnail/:shareid", v1.GetPersonImageThumbnail)
}
v1AnalyseGroup := v1Group.Group("/analyse")
v1AnalyseGroup.Use()
{
v1AnalyseGroup.POST("/app", v1.PostAppAnalyse)
}
v1Group.GET("/sync/config", v1.GetSyncConfig)
v1Group.Any("/syncthing/*url", v1.SyncToSyncthing)
}
return r
}

38
route/v1/analyse.go Normal file
View File

@@ -0,0 +1,38 @@
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

@@ -1,15 +1,17 @@
package v1
import (
"encoding/json"
"io/ioutil"
"net/http"
"strconv"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
"github.com/IceWhaleTech/CasaOS/pkg/utils/sort"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
// @Summary 获取远程列表
@@ -29,20 +31,34 @@ func AppList(c *gin.Context) {
//service.MyService.Docker().DockerContainerCommit("test2")
index := c.DefaultQuery("index", "1")
size := c.DefaultQuery("size", "10")
size := c.DefaultQuery("size", "10000")
t := c.DefaultQuery("type", "rank")
categoryId := c.DefaultQuery("category_id", "0")
key := c.DefaultQuery("key", "")
list, count := service.MyService.OAPI().GetServerList(index, size, t, categoryId, key)
for i := 0; i < len(list); i++ {
ct, _ := service.MyService.Docker().DockerListByImage(list[i].Image, list[i].ImageVersion)
if ct != nil {
list[i].State = ct.State
}
}
data := make(map[string]interface{}, 2)
data["count"] = count
data["items"] = list
language := c.GetHeader("Language")
recommend, list, community := service.MyService.Casa().GetServerList(index, size, t, categoryId, key, language)
// for i := 0; i < len(recommend); i++ {
// ct, _ := service.MyService.Docker().DockerListByImage(recommend[i].Image, recommend[i].ImageVersion)
// if ct != nil {
// recommend[i].State = ct.State
// }
// }
// for i := 0; i < len(list); i++ {
// ct, _ := service.MyService.Docker().DockerListByImage(list[i].Image, list[i].ImageVersion)
// if ct != nil {
// list[i].State = ct.State
// }
// }
// for i := 0; i < len(community); i++ {
// ct, _ := service.MyService.Docker().DockerListByImage(community[i].Image, community[i].ImageVersion)
// if ct != nil {
// community[i].State = ct.State
// }
// }
data := make(map[string]interface{}, 3)
data["recommend"] = recommend
data["list"] = list
data["community"] = community
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
}
@@ -90,12 +106,29 @@ func PortCheck(c *gin.Context) {
// @Param size query int false "size"
// @Param position query bool false "是否是首页应用"
// @Success 200 {string} string "ok"
// @Router /app/mylist [get]
// @Router /app/my/list [get]
func MyAppList(c *gin.Context) {
index, _ := strconv.Atoi(c.DefaultQuery("index", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("size", "0"))
position, _ := strconv.ParseBool(c.DefaultQuery("position", "true"))
list := service.MyService.App().GetMyList(index, size, position)
list, unTranslation := service.MyService.App().GetMyList(index, size, position)
data := make(map[string]interface{}, 2)
data["list"] = list
data["local"] = unTranslation
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
}
// @Summary my app hardware usage list
// @Produce application/json
// @Accept application/json
// @Tags app
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/usage [get]
func AppUsageList(c *gin.Context) {
list := service.MyService.App().GetHardwareUsage()
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
}
@@ -110,51 +143,71 @@ func MyAppList(c *gin.Context) {
func AppInfo(c *gin.Context) {
id := c.Param("id")
info := service.MyService.App().GetServerAppInfo(id)
language := c.GetHeader("Language")
info := service.MyService.Casa().GetServerAppInfo(id, "", language)
if info.NetworkModel != "host" {
port, _ := port2.GetAvailablePort("tcp")
info.PortMap = uint(port)
for i := 0; i < len(info.Configures.TcpPorts); i++ {
info.Configures.TcpPorts[i].CommendPort, _ = port2.GetAvailablePort("tcp")
}
for i := 0; i < len(info.Configures.UdpPorts); i++ {
info.Configures.UdpPorts[i].CommendPort, _ = port2.GetAvailablePort("udp")
for i := 0; i < len(info.Ports); i++ {
if p, _ := strconv.Atoi(info.Ports[i].ContainerPort); port2.IsPortAvailable(p, info.Ports[i].Protocol) {
info.Ports[i].CommendPort = strconv.Itoa(p)
} else {
if info.Ports[i].Protocol == "tcp" {
if p, err := port2.GetAvailablePort("tcp"); err == nil {
info.Ports[i].CommendPort = strconv.Itoa(p)
}
} else if info.Ports[i].Protocol == "upd" {
if p, err := port2.GetAvailablePort("udp"); err == nil {
info.Ports[i].CommendPort = strconv.Itoa(p)
}
}
}
if info.Ports[i].Type == 0 {
info.PortMap = info.Ports[i].CommendPort
}
}
} else {
info.PortMap = info.TcpPort
}
for i := 0; i < len(info.Configures.Devices); i++ {
if !file.CheckNotExist(info.Configures.Devices[i].ContainerPath) {
info.Configures.Devices[i].Path = info.Configures.Devices[i].ContainerPath
for i := 0; i < len(info.Ports); i++ {
if info.Ports[i].Type == 0 {
info.PortMap = info.Ports[i].ContainerPort
break
}
}
}
portOrder := func(c1, c2 *model.Ports) bool {
return c1.Type < c2.Type
for i := 0; i < len(info.Devices); i++ {
if !file.CheckNotExist(info.Devices[i].ContainerPath) {
info.Devices[i].Path = info.Devices[i].ContainerPath
}
}
// if len(info.Tip) > 0 {
// info.Tip = env_helper.ReplaceStringDefaultENV(info.Tip)
// }
envOrder := func(c1, c2 *model.Envs) bool {
return c1.Type < c2.Type
}
// portOrder := func(c1, c2 *model.Ports) bool {
// return c1.Type < c2.Type
// }
volOrder := func(c1, c2 *model.Volume) bool {
return c1.Type < c2.Type
}
// envOrder := func(c1, c2 *model.Envs) bool {
// return c1.Type < c2.Type
// }
devOrder := func(c1, c2 *model.Devices) bool {
return c1.Type < c2.Type
}
// volOrder := func(c1, c2 *model.Volume) bool {
// return c1.Type < c2.Type
// }
// devOrder := func(c1, c2 *model.Devices) bool {
// return c1.Type < c2.Type
// }
//sort
if info.NetworkModel != "host" {
sort.PortsSort(portOrder).Sort(info.Configures.TcpPorts)
sort.PortsSort(portOrder).Sort(info.Configures.UdpPorts)
}
// if info.NetworkModel != "host" {
// sort.PortsSort(portOrder).Sort(info.Configures.TcpPorts)
// sort.PortsSort(portOrder).Sort(info.Configures.UdpPorts)
// }
sort.EnvSort(envOrder).Sort(info.Configures.Envs)
sort.VolSort(volOrder).Sort(info.Configures.Volumes)
sort.DevSort(devOrder).Sort(info.Configures.Devices)
// sort.EnvSort(envOrder).Sort(info.Envs)
// sort.VolSort(volOrder).Sort(info.Volumes.([]model.PathMap))
// sort.DevSort(devOrder).Sort(info.Devices)
info.MaxMemory = service.MyService.ZiMa().GetMemInfo().Total >> 20
@@ -169,14 +222,27 @@ func AppInfo(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /app/category [get]
func CategoryList(c *gin.Context) {
list := service.MyService.OAPI().GetServerCategoryList()
list := service.MyService.Casa().GetServerCategoryList()
var count uint = 0
for _, category := range list {
count += category.Count
}
rear := append([]model.ServerCategoryList{}, list[0:]...)
list = append(list[:0], model.ServerCategoryList{Count: count, Name: "All"})
list = append(list[:0], model.ServerCategoryList{Count: count, Name: "All", Font: "apps"})
list = append(list, rear...)
c.JSON(http.StatusOK, &model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
}
// @Summary 分享该应用配置
// @Produce application/json
// @Accept application/json
// @Tags app
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/share [post]
func ShareAppFile(c *gin.Context) {
str, _ := ioutil.ReadAll(c.Request.Body)
content := service.MyService.Casa().ShareAppFile(str)
c.JSON(http.StatusOK, json.RawMessage(content))
}

View File

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

View File

@@ -1,65 +1,163 @@
package v1
import (
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/v3/disk"
"net/http"
"strconv"
)
// @Summary 获取磁盘列表
var diskMap = make(map[string]string)
// @Summary disk list
// @Produce application/json
// @Accept application/json
// @Tags disk
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /disk/list [get]
func GetPlugInDisk(c *gin.Context) {
func GetDiskList(c *gin.Context) {
list := service.MyService.Disk().LSBLK(false)
dbList := service.MyService.Disk().GetSerialAll()
part := make(map[string]int64, len(dbList))
for _, v := range dbList {
part[v.MountPoint] = v.CreatedAt
}
findSystem := 0
//ls := service.MyService.Disk().GetPlugInDisk()
//fmt.Println(ls)
//dd, _ := disk.Partitions(true)
//fmt.Println(dd)
//
//dir, err := ioutil.ReadDir("/sys/block")
//if err != nil {
// panic(err)
//}
//
//files := make([]string, 0)
//
////fmt.Println(regexp.MatchString("sd[a-z]*[0-9]", "sda"))
//
//for _, f := range dir {
// if match, _ := regexp.MatchString("sd[a-z]", f.Name()); match {
// files = append(files, f.Name())
// }
//}
//fmt.Println(files)
//filess := make([]string, 0)
//for _, file := range files {
// dirs, _ := ioutil.ReadDir("/sys/block/" + file)
//
// for _, f := range dirs {
// if match, _ := regexp.MatchString("sd[a-z]*[0-9]", f.Name()); match {
// filess = append(filess, f.Name())
// }
// }
//}
//fmt.Println(filess)
//
//for _, s := range filess {
// fmt.Println(disk.Usage("/dev/" + s))
//}
disks := []model.Drive{}
storage := []model.Storage{}
avail := []model.Drive{}
for i := 0; i < len(list); i++ {
disk := model.Drive{}
if list[i].Rota {
disk.DiskType = "HDD"
} else {
disk.DiskType = "SSD"
}
disk.Serial = list[i].Serial
disk.Name = list[i].Name
disk.Size = list[i].Size
disk.Path = list[i].Path
disk.Model = list[i].Model
lst := service.MyService.Disk().LSBLK()
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: lst})
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 == "/" {
stor := model.Storage{}
stor.Name = "System"
stor.MountPoint = v.MountPoint
stor.Size = v.FSSize
stor.Avail = v.FSAvail
stor.Path = v.Path
stor.Type = v.FsType
stor.DriveName = "System"
disk.Model = "System"
if strings.Contains(v.SubSystems, "mmc") {
disk.DiskType = "MMC"
} else if strings.Contains(v.SubSystems, "usb") {
disk.DiskType = "USB"
}
disk.Health = "true"
disks = append(disks, disk)
storage = append(storage, stor)
findSystem = 1
break
}
}
} else {
if list[i].Children[j].MountPoint == "/" {
stor := model.Storage{}
stor.Name = "System"
stor.MountPoint = list[i].Children[j].MountPoint
stor.Size = list[i].Children[j].FSSize
stor.Avail = list[i].Children[j].FSAvail
stor.Path = list[i].Children[j].Path
stor.Type = list[i].Children[j].FsType
stor.DriveName = "System"
disk.Model = "System"
if strings.Contains(list[i].Children[j].SubSystems, "mmc") {
disk.DiskType = "MMC"
} else if strings.Contains(list[i].Children[j].SubSystems, "usb") {
disk.DiskType = "USB"
}
disk.Health = "true"
disks = append(disks, disk)
storage = append(storage, stor)
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" {
temp := service.MyService.Disk().SmartCTL(list[i].Path)
if reflect.DeepEqual(temp, model.SmartctlA{}) {
temp.SmartStatus.Passed = true
}
if len(list[i].Children) == 1 && len(list[i].Children[0].MountPoint) > 0 {
stor := model.Storage{}
stor.MountPoint = list[i].Children[0].MountPoint
stor.Size = list[i].Children[0].FSSize
stor.Avail = list[i].Children[0].FSAvail
stor.Path = list[i].Children[0].Path
stor.Type = list[i].Children[0].FsType
stor.DriveName = list[i].Name
pathArr := strings.Split(list[i].Children[0].MountPoint, "/")
if len(pathArr) == 3 {
stor.Name = pathArr[2]
}
if t, ok := part[list[i].Children[0].MountPoint]; ok {
stor.CreatedAt = t
}
storage = append(storage, stor)
} else {
//todo 长度有问题
if len(list[i].Children) == 1 && list[i].Children[0].FsType == "ext4" {
disk.NeedFormat = false
avail = append(avail, disk)
} else {
disk.NeedFormat = true
avail = append(avail, disk)
}
}
disk.Temperature = temp.Temperature.Current
disk.Health = strconv.FormatBool(temp.SmartStatus.Passed)
disks = append(disks, disk)
}
}
data := make(map[string]interface{}, 3)
data["drive"] = disks
data["storage"] = storage
data["avail"] = avail
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
}
// @Summary 获取磁盘列表
// @Summary get disk list
// @Produce application/json
// @Accept application/json
// @Tags disk
@@ -68,7 +166,7 @@ func GetPlugInDisk(c *gin.Context) {
// @Router /disk/lists [get]
func GetPlugInDisks(c *gin.Context) {
list := service.MyService.Disk().LSBLK()
list := service.MyService.Disk().LSBLK(true)
var result []*disk.UsageStat
for _, item := range list {
result = append(result, service.MyService.Disk().GetDiskInfoByPath(item.Path))
@@ -76,12 +174,12 @@ func GetPlugInDisks(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: result})
}
// @Summary 磁盘详情
// @Summary disk detail
// @Produce application/json
// @Accept application/json
// @Tags disk
// @Security ApiKeyAuth
// @Param path query string true "要获取的磁盘详情 例如/dev/sda"
// @Param path query string true "for example /dev/sda"
// @Success 200 {string} string "ok"
// @Router /disk/info [get]
func GetDiskInfo(c *gin.Context) {
@@ -93,31 +191,46 @@ func GetDiskInfo(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: m})
}
// @Summary 磁盘详情
// @Summary format storage
// @Produce application/json
// @Accept multipart/form-data
// @Tags disk
// @Security ApiKeyAuth
// @Param path formData string true "磁盘路径 例如/dev/sda1"
// @Param path formData string true "e.g. /dev/sda1"
// @Param pwd formData string true "user password"
// @Param volume formData string true "mount point"
// @Success 200 {string} string "ok"
// @Router /disk/format [post]
func FormatDisk(c *gin.Context) {
path := c.PostForm("path")
t := "ext4"
pwd := c.PostForm("pwd")
volume := c.PostForm("volume")
t := c.PostForm("type")
if pwd != config.UserInfo.PWD {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.PWD_INVALID, Message: oasis_err.GetMsg(oasis_err.PWD_INVALID)})
return
}
if len(path) == 0 || len(t) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
return
}
//删除挂载点
if _, ok := diskMap[path]; ok {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.DISK_BUSYING, Message: oasis_err.GetMsg(oasis_err.DISK_BUSYING)})
return
}
diskMap[path] = "busying"
service.MyService.Disk().UmountPointAndRemoveDir(path)
//格式化磁盘
service.MyService.Disk().FormatDisk(path, t)
//重新挂载
format := service.MyService.Disk().FormatDisk(path, t)
if len(format) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.FORMAT_ERROR, Message: oasis_err.GetMsg(oasis_err.FORMAT_ERROR)})
delete(diskMap, path)
return
}
service.MyService.Disk().MountDisk(path, volume)
service.MyService.Disk().RemoveLSBLKCache()
delete(diskMap, path)
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
}
@@ -154,25 +267,231 @@ func RemovePartition(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
}
// @Summary 添加分区
// @Summary add storage
// @Produce application/json
// @Accept multipart/form-data
// @Tags disk
// @Security ApiKeyAuth
// @Param path formData string true "磁盘路径 例如/dev/sda"
// @Param size formData string true "需要分区容量大小(MB)"
// @Param num formData string true "磁盘符号"
// @Param path formData string true "disk path e.g. /dev/sda"
// @Param serial formData string true "serial"
// @Param name formData string true "name"
// @Param format formData bool true "need format(true)"
// @Success 200 {string} string "ok"
// @Router /disk/addpart [post]
// @Router /disk/storage [post]
func AddPartition(c *gin.Context) {
name := c.PostForm("name")
path := c.PostForm("path")
size, _ := strconv.Atoi(c.DefaultPostForm("size", "0"))
num := c.DefaultPostForm("num", "9")
if len(path) == 0 {
format, _ := strconv.ParseBool(c.PostForm("format"))
if len(name) == 0 || len(path) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
return
}
if _, ok := diskMap[path]; ok {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.DISK_BUSYING, Message: oasis_err.GetMsg(oasis_err.DISK_BUSYING)})
return
}
if !file.CheckNotExist("/DATA/" + name) {
// /mnt/name exist
c.JSON(http.StatusOK, model.Result{Success: oasis_err.NAME_NOT_AVAILABLE, Message: oasis_err.GetMsg(oasis_err.NAME_NOT_AVAILABLE)})
return
}
diskMap[path] = "busying"
currentDisk := service.MyService.Disk().GetDiskInfo(path)
if !format {
if len(currentDisk.Children) != 1 || !(len(currentDisk.Children) > 0 && currentDisk.Children[0].FsType == "ext4") {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.DISK_NEEDS_FORMAT, Message: oasis_err.GetMsg(oasis_err.DISK_NEEDS_FORMAT)})
delete(diskMap, path)
return
}
} else {
service.MyService.Disk().AddPartition(path)
}
//size*1024*1024/512
service.MyService.Disk().AddPartition(path, num, uint64(size*1024*2))
formatBool := true
for formatBool {
currentDisk = service.MyService.Disk().GetDiskInfo(path)
fmt.Println(currentDisk.Children)
if len(currentDisk.Children) > 0 {
formatBool = false
break
}
time.Sleep(time.Second)
}
currentDisk = service.MyService.Disk().GetDiskInfo(path)
if len(currentDisk.Children) != 1 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.DISK_NEEDS_FORMAT, Message: oasis_err.GetMsg(oasis_err.DISK_NEEDS_FORMAT)})
return
}
mountPath := "/DATA/" + name
m := model2.SerialDisk{}
m.MountPoint = mountPath
m.Path = currentDisk.Children[0].Path
m.UUID = currentDisk.Children[0].UUID
m.State = 0
m.CreatedAt = time.Now().Unix()
service.MyService.Disk().SaveMountPoint(m)
//mount dir
service.MyService.Disk().MountDisk(currentDisk.Children[0].Path, mountPath)
service.MyService.Disk().RemoveLSBLKCache()
delete(diskMap, path)
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
}
// @Summary add mount point
// @Produce application/json
// @Accept multipart/form-data
// @Tags disk
// @Security ApiKeyAuth
// @Param path formData string true "for example: /dev/sda1"
// @Param serial formData string true "disk id"
// @Success 200 {string} string "ok"
// @Router /disk/mount [post]
func PostMountDisk(c *gin.Context) {
// for example: path=/dev/sda1
path := c.PostForm("path")
serial := c.PostForm("serial")
mountPath := "/DATA/volume"
var list = service.MyService.Disk().GetSerialAll()
var pathMapList = make(map[string]string, len(list))
for _, v := range list {
pathMapList[v.MountPoint] = "1"
}
for i := 0; i < len(list)+1; i++ {
if _, ok := pathMapList[mountPath+strconv.Itoa(i)]; !ok {
mountPath = mountPath + strconv.Itoa(i)
break
}
}
//mount dir
service.MyService.Disk().MountDisk(path, mountPath)
m := model2.SerialDisk{}
m.MountPoint = mountPath
m.Path = path
m.UUID = serial
m.State = 0
//service.MyService.Disk().SaveMountPoint(m)
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
}
// @Summary remove mount point
// @Produce application/json
// @Accept multipart/form-data
// @Tags disk
// @Security ApiKeyAuth
// @Param path formData string true "e.g. /dev/sda1"
// @Param mount_point formData string true "e.g. /mnt/volume1"
// @Param pwd formData string true "user password"
// @Success 200 {string} string "ok"
// @Router /disk/umount [post]
func PostDiskUmount(c *gin.Context) {
path := c.PostForm("path")
mountPoint := c.PostForm("volume")
pwd := c.PostForm("pwd")
if len(path) == 0 || len(mountPoint) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
return
}
if pwd != config.UserInfo.PWD {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.PWD_INVALID, Message: oasis_err.GetMsg(oasis_err.PWD_INVALID)})
return
}
if _, ok := diskMap[path]; ok {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.DISK_BUSYING, Message: oasis_err.GetMsg(oasis_err.DISK_BUSYING)})
return
}
service.MyService.Disk().UmountPointAndRemoveDir(path)
//delete data
service.MyService.Disk().DeleteMountPoint(path, mountPoint)
service.MyService.Disk().RemoveLSBLKCache()
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
}
// @Summary confirm delete disk
// @Produce application/json
// @Accept application/json
// @Tags disk
// @Security ApiKeyAuth
// @Param id path string true "id"
// @Success 200 {string} string "ok"
// @Router /disk/remove/{id} [delete]
func DeleteDisk(c *gin.Context) {
id := c.Param("id")
service.MyService.Disk().DeleteMount(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
}
// @Summary check mount point
// @Produce application/json
// @Accept application/json
// @Tags disk
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /disk/init [get]
func GetDiskCheck(c *gin.Context) {
dbList := service.MyService.Disk().GetSerialAll()
list := service.MyService.Disk().LSBLK(true)
mapList := make(map[string]string)
for _, v := range list {
mapList[v.Serial] = "1"
}
for _, v := range dbList {
if _, ok := mapList[v.UUID]; !ok {
//disk undefind
c.JSON(http.StatusOK, model.Result{Success: oasis_err.ERROR, Message: oasis_err.GetMsg(oasis_err.ERROR), Data: "disk undefind"})
return
}
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
}
// @Summary check mount point
// @Produce application/json
// @Accept application/json
// @Tags disk
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /disk/usb [get]
func GetUSBList(c *gin.Context) {
list := service.MyService.Disk().LSBLK(false)
data := []model.DriveUSB{}
for _, v := range list {
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
} else {
mountTemp = false
}
}
temp.Mount = mountTemp
data = append(data, temp)
}
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
}

View File

@@ -2,12 +2,21 @@ package v1
import (
"bytes"
"encoding/json"
json2 "encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/docker"
upnp2 "github.com/IceWhaleTech/CasaOS/pkg/upnp"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
ip_helper2 "github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
"github.com/IceWhaleTech/CasaOS/pkg/utils/random"
@@ -19,11 +28,7 @@ import (
"github.com/gorilla/websocket"
"github.com/jinzhu/copier"
uuid "github.com/satori/go.uuid"
"net/http"
"reflect"
"strconv"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
var upgrader = websocket.Upgrader{
@@ -64,19 +69,46 @@ func DockerTerminal(c *gin.Context) {
//打开本机的ssh接口
func WsSsh(c *gin.Context) {
wsConn, _ := upgrader.Upgrade(c.Writer, c.Request, nil)
defer wsConn.Close()
cols, _ := strconv.Atoi(c.DefaultQuery("cols", "200"))
rows, _ := strconv.Atoi(c.DefaultQuery("rows", "32"))
client, _ := docker.NewSshClient()
defer client.Close()
ssConn, _ := docker.NewSshConn(cols, rows, client)
defer ssConn.Close()
quitChan := make(chan bool, 3)
var logBuff = new(bytes.Buffer)
quitChan := make(chan bool, 3)
user := ""
password := ""
var login int = 1
cols, _ := strconv.Atoi(c.DefaultQuery("cols", "200"))
rows, _ := strconv.Atoi(c.DefaultQuery("rows", "32"))
var client *ssh.Client
for login != 0 {
var err error
wsConn.WriteMessage(websocket.TextMessage, []byte("login:"))
user = docker.ReceiveWsMsgUser(wsConn, logBuff)
wsConn.WriteMessage(websocket.TextMessage, []byte("\r\n\x1b[0m"))
wsConn.WriteMessage(websocket.TextMessage, []byte("password:"))
password = docker.ReceiveWsMsgPassword(wsConn, logBuff)
wsConn.WriteMessage(websocket.TextMessage, []byte("\r\n\x1b[0m"))
client, err = docker.NewSshClient(user, password)
if err != nil && client == nil {
wsConn.WriteMessage(websocket.TextMessage, []byte(err.Error()))
wsConn.WriteMessage(websocket.TextMessage, []byte("\r\n\x1b[0m"))
} else {
login = 0
}
}
if client != nil {
defer client.Close()
}
ssConn, _ := docker.NewSshConn(cols, rows, client)
defer ssConn.Close()
go ssConn.ReceiveWsMsg(wsConn, logBuff, quitChan)
go ssConn.SendComboOutput(wsConn, quitChan)
go ssConn.SessionWait(quitChan)
<-quitChan
}
@@ -114,6 +146,7 @@ func SpeedPush(c *gin.Context) {
// @Router /app/install/{id} [post]
func InstallApp(c *gin.Context) {
appId := c.Param("id")
language := c.GetHeader("Language")
var appInfo model.ServerAppList
m := model.CustomizationPostData{}
c.BindJSON(&m)
@@ -121,6 +154,27 @@ func InstallApp(c *gin.Context) {
const CUSTOM = "custom"
var dockerImage string
var dockerImageVersion string
//check app name is exist
if m.Origin != "custom" {
oldName := m.Label
for i := 0; true; i++ {
if i != 0 {
m.Label = oldName + "-" + strconv.Itoa(i)
}
if _, err := service.MyService.Docker().DockerListByName(m.Label); err != nil {
break
}
}
} else {
if _, err := service.MyService.Docker().DockerListByName(m.Label); err == nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR_APP_NAME_EXIST, Message: oasis_err2.GetMsg(oasis_err2.ERROR_APP_NAME_EXIST)})
return
}
}
//检查端口
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)})
@@ -143,7 +197,7 @@ func InstallApp(c *gin.Context) {
dockerImageVersion = "latest"
}
if m.Origin != "custom" {
appInfo = service.MyService.App().GetServerAppInfo(appId)
appInfo = service.MyService.Casa().GetServerAppInfo(appId, "", language)
} else {
@@ -187,14 +241,24 @@ func InstallApp(c *gin.Context) {
}
}
if m.Origin == "custom" {
for _, device := range m.Devices {
if file.CheckNotExist(device.Path) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.DEVICE_NOT_EXIST, Message: device.Path + "," + oasis_err2.GetMsg(oasis_err2.DEVICE_NOT_EXIST)})
return
}
for _, device := range m.Devices {
if file.CheckNotExist(device.Path) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.DEVICE_NOT_EXIST, Message: device.Path + "," + oasis_err2.GetMsg(oasis_err2.DEVICE_NOT_EXIST)})
return
}
} else {
dev := []model.PathMap{}
for _, device := range dev {
if !file.CheckNotExist(device.Path) {
dev = append(dev, device)
}
}
m.Devices = dev
}
//restart := c.PostForm("restart") //always 总是重启, unless-stopped 除非用户手动停止容器,否则总是重新启动, on-failure:仅当容器退出代码非零时重新启动
//if len(restart) > 0 {
//
@@ -205,17 +269,18 @@ func InstallApp(c *gin.Context) {
//
//}
id := uuid.NewV4().String()
m.CustomId = id
var relyMap = make(map[string]string)
go func() {
installLog := model2.AppNotify{}
installLog.CustomId = id
installLog.State = 0
installLog.CustomId = m.Label
installLog.Message = "installing rely"
installLog.Speed = 10
installLog.Class = types.NOTIFY_APP
installLog.Type = types.NOTIFY_TYPE_UNIMPORTANT
installLog.CreatedAt = strconv.FormatInt(time.Now().Unix(), 10)
installLog.UpdatedAt = strconv.FormatInt(time.Now().Unix(), 10)
installLog.Id = uuid.NewV4().String()
service.MyService.Notify().AddLog(installLog)
if m.Origin != "custom" {
for _, plugin := range appInfo.Plugins {
@@ -237,12 +302,12 @@ func InstallApp(c *gin.Context) {
rely.Type = types.RELY_TYPE_MYSQL
rely.ContainerId = mysqlContainerId
rely.CustomId = mid
rely.ContainerCustomId = id
var msqlConfig model2.MysqlConfigs
rely.ContainerCustomId = m.Label
var mysqlConfig model2.MysqlConfigs
//结构体转换
copier.Copy(&msqlConfig, &mc)
rely.Config = msqlConfig
copier.Copy(&mysqlConfig, &mc)
rely.Config = mysqlConfig
service.MyService.Rely().Create(rely)
relyMap["mysql"] = mid
@@ -250,16 +315,13 @@ func InstallApp(c *gin.Context) {
} else {
docker_base.MysqlDelete(mysqlContainerId)
installLog.State = 0
installLog.Speed = 30
installLog.Message = err.Error()
service.MyService.Notify().UpdateLog(installLog)
}
}
}
}
installLog.Speed = 50
installLog.Message = "pulling"
service.MyService.Notify().UpdateLog(installLog)
@@ -267,7 +329,6 @@ func InstallApp(c *gin.Context) {
err := service.MyService.Docker().DockerPullImage(dockerImage+":"+dockerImageVersion, installLog)
if err != nil {
installLog.State = 0
installLog.Speed = 70
installLog.Message = err.Error()
installLog.Type = types.NOTIFY_TYPE_ERROR
service.MyService.Notify().UpdateLog(installLog)
@@ -283,36 +344,45 @@ func InstallApp(c *gin.Context) {
//}
//step创建容器
containerId, err := service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, id, m, appInfo.NetworkModel)
installLog.ContainerId = containerId
// networkName, err := service.MyService.Docker().GetNetWorkNameByNetWorkID(appInfo.NetworkModel)
// if err != nil {
// //service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":80}", 100)
// installLog.State = 0
// installLog.Speed = 75
// installLog.Type = types.NOTIFY_TYPE_ERROR
// installLog.Message = err.Error()
// service.MyService.Notify().UpdateLog(installLog)
// return
// }
containerId, err := service.MyService.Docker().DockerContainerCreate(dockerImage+":"+dockerImageVersion, m, appInfo.NetworkModel)
installLog.Name = appInfo.Title
installLog.Icon = appInfo.Icon
if err != nil {
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":80}", 100)
installLog.State = 0
installLog.Speed = 80
installLog.Type = types.NOTIFY_TYPE_ERROR
installLog.Message = err.Error()
service.MyService.Notify().UpdateLog(installLog)
return
} else {
//service.MyService.Redis().Set(id, "{\"id\":\""+id+"\",\"state\":true,\"message\":\"starting\",\"speed\":80}", 100)
installLog.Speed = 80
installLog.Message = "starting"
service.MyService.Notify().UpdateLog(installLog)
}
// echo -e "hellow\nworld" >>
//step启动容器
err = service.MyService.Docker().DockerContainerStart(id)
err = service.MyService.Docker().DockerContainerStart(m.Label)
if err != nil {
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":90}", 100)
installLog.State = 0
installLog.Type = types.NOTIFY_TYPE_ERROR
installLog.Speed = 90
installLog.Message = err.Error()
service.MyService.Notify().UpdateLog(installLog)
return
} else {
//service.MyService.Redis().Set(id, "{\"id\":\""+id+"\",\"state\":true,\"message\":\"setting upnp\",\"speed\":90}", 100)
installLog.Speed = 90
if m.Origin != CUSTOM {
installLog.Message = "setting upnp"
} else {
@@ -357,13 +427,11 @@ func InstallApp(c *gin.Context) {
if err != nil {
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":95}", 100)
installLog.State = 0
installLog.Speed = 95
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.Speed = 95
installLog.Message = "checking"
service.MyService.Notify().UpdateLog(installLog)
}
@@ -371,18 +439,16 @@ func InstallApp(c *gin.Context) {
}
//step: 启动成功 检查容器状态确认启动成功
container, err := service.MyService.Docker().DockerContainerInfo(id)
container, err := service.MyService.Docker().DockerContainerInfo(m.Label)
if err != nil && container.ContainerJSONBase.State.Running {
//service.MyService.Redis().Set(id, "{\"id\"\""+id+"\",\"state\":false,\"message\":\""+err.Error()+"\",\"speed\":100}", 100)
installLog.State = 0
installLog.Speed = 100
installLog.Type = types.NOTIFY_TYPE_ERROR
installLog.Message = err.Error()
service.MyService.Notify().UpdateLog(installLog)
return
} else {
//service.MyService.Redis().Set(id, "{\"id\":\""+id+"\",\"state\":true,\"message\":\"installed\",\"speed\":100}", 100)
installLog.Speed = 100
installLog.Message = "installed"
service.MyService.Notify().UpdateLog(installLog)
}
@@ -390,13 +456,21 @@ func InstallApp(c *gin.Context) {
rely := model.MapStrings{}
copier.Copy(&rely, &relyMap)
// if m.Origin != "custom" {
// for i := 0; i < len(m.Volumes); i++ {
// m.Volumes[i].Path = docker.GetDir(id, m.Volumes[i].Path)
// }
// }
portsStr, _ := json2.Marshal(m.Ports)
envsStr, _ := json2.Marshal(m.Envs)
volumesStr, _ := json2.Marshal(m.Volumes)
devicesStr, _ := json2.Marshal(m.Devices)
cmd, _ := json2.Marshal(m.Cmd)
capAdd, _ := json.Marshal(m.CapAdd)
//step: 保存数据到数据库
md := model2.AppListDBModel{
CustomId: id,
CustomId: "",
Title: appInfo.Title,
//ScreenshotLink: appInfo.ScreenshotLink,
Slogan: appInfo.Tagline,
@@ -421,18 +495,24 @@ func InstallApp(c *gin.Context) {
Memory: m.Memory,
Devices: string(devicesStr),
//Rely: rely,
Origin: m.Origin,
CreatedAt: strconv.FormatInt(time.Now().Unix(), 10),
UpdatedAt: strconv.FormatInt(time.Now().Unix(), 10),
Origin: m.Origin,
CreatedAt: strconv.FormatInt(time.Now().Unix(), 10),
UpdatedAt: strconv.FormatInt(time.Now().Unix(), 10),
Cmd: string(cmd),
CapAdd: string(capAdd),
HostName: m.HostName,
Privileged: m.Privileged,
}
//if appInfo.NetworkModel == "host" {
// m.PortMap = m.Port
//}
service.MyService.App().SaveContainer(md)
fmt.Println(md)
//service.MyService.App().SaveContainer(md)
config.CasaOSGlobalVariables.AppChange = true
}()
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: id})
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: m.Label})
}
@@ -633,17 +713,23 @@ func UnInstallApp(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
info := service.MyService.App().GetUninstallInfo(appId)
//info := service.MyService.App().GetUninstallInfo(appId)
info, err := service.MyService.Docker().DockerContainerInfo(appId)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
//step停止容器
err := service.MyService.Docker().DockerContainerStop(appId)
err = service.MyService.Docker().DockerContainerStop(appId)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.UNINSTALL_APP_ERROR, Message: oasis_err2.GetMsg(oasis_err2.UNINSTALL_APP_ERROR), Data: err.Error()})
return
}
//step删除容器
err = service.MyService.Docker().DockerContainerRemove(appId)
err = service.MyService.Docker().DockerContainerRemove(appId, false)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.UNINSTALL_APP_ERROR, Message: oasis_err2.GetMsg(oasis_err2.UNINSTALL_APP_ERROR), Data: err.Error()})
return
@@ -651,17 +737,21 @@ func UnInstallApp(c *gin.Context) {
//存在镜像正在使用的情况
// step删除镜像
service.MyService.Docker().DockerImageRemove(info.Image + ":" + info.Version)
service.MyService.Docker().DockerImageRemove(info.Image)
//step: 删除本地数据
service.MyService.App().RemoveContainerById(appId)
if info.Origin != "custom" {
//service.MyService.App().RemoveContainerById(appId)
if info.Config.Labels["origin"] != "custom" {
fmt.Println(info.HostConfig.Mounts)
//step: 删除文件夹
service.MyService.App().DelAppConfigDir(appId)
for _, v := range info.HostConfig.Mounts {
if strings.Contains(v.Source, info.Name) {
service.MyService.App().DelAppConfigDir(v.Source)
}
}
//step: 删除install log
service.MyService.Notify().DelLog(appId)
//service.MyService.Notify().DelLog(appId)
// for k, v := range info.Rely {
//
@@ -700,6 +790,13 @@ func UnInstallApp(c *gin.Context) {
// }
//}
}
config.CasaOSGlobalVariables.AppChange = true
unInstallLog := model2.AppNotify{}
unInstallLog.State = 0
unInstallLog.CustomId = appId
unInstallLog.Message = "uninstalled"
unInstallLog.Id = uuid.NewV4().String()
service.MyService.Notify().UpdateLog(unInstallLog)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
@@ -723,7 +820,7 @@ func ChangAppState(c *gin.Context) {
} else if state == "start" {
err = service.MyService.Docker().DockerContainerStart(appId)
} else if state == "restart" {
err = service.MyService.Docker().DockerContainerStop(appId)
service.MyService.Docker().DockerContainerStop(appId)
err = service.MyService.Docker().DockerContainerStart(appId)
}
if err != nil {
@@ -763,7 +860,6 @@ func ContainerLog(c *gin.Context) {
func GetInstallSpeed(c *gin.Context) {
id := c.Param("id")
b := service.MyService.Notify().GetLog(id)
b.Id = b.CustomId
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: b})
}
@@ -820,19 +916,23 @@ func UpdateSetting(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
var cpd model.CustomizationPostData
//var cpd model.CustomizationPostData
copier.Copy(&cpd, &m)
//copier.Copy(&cpd, &m)
appInfo := service.MyService.App().GetAppDBInfo(id)
//appInfo := service.MyService.App().GetAppDBInfo(id)
//info, err := service.MyService.Docker().DockerContainerInfo(id)
var containerId string
containerId = appInfo.ContainerId
// //check app name is exist
// if _, err := service.MyService.Docker().DockerListByName(m.Label); err == nil {
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR_APP_NAME_EXIST, Message: oasis_err2.GetMsg(oasis_err2.ERROR_APP_NAME_EXIST)})
// return
// }
service.MyService.Docker().DockerContainerStop(id)
portMap, _ := strconv.Atoi(m.PortMap)
if !port2.IsPortAvailable(portMap, "tcp") {
service.MyService.Docker().DockerContainerStart(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + m.PortMap})
return
}
@@ -842,53 +942,54 @@ func UpdateSetting(c *gin.Context) {
if u.Protocol == "udp" {
t, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(t, "udp") {
service.MyService.Docker().DockerContainerStart(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
return
}
} else if u.Protocol == "tcp" {
te, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(te, "tcp") {
service.MyService.Docker().DockerContainerStart(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
return
}
} else if u.Protocol == "both" {
t, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(t, "udp") {
service.MyService.Docker().DockerContainerStart(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
return
}
te, _ := strconv.Atoi(u.CommendPort)
if !port2.IsPortAvailable(te, "tcp") {
service.MyService.Docker().DockerContainerStart(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: "Duplicate port:" + u.CommendPort})
return
}
}
}
service.MyService.Docker().DockerContainerUpdateName(id, id)
//service.MyService.Docker().DockerContainerRemove(id, true)
if !reflect.DeepEqual(m.Ports, appInfo.Ports) || !reflect.DeepEqual(m.Envs, appInfo.Envs) || !reflect.DeepEqual(m.Volumes, appInfo.Volumes) || m.PortMap != appInfo.PortMap {
service.MyService.Docker().DockerContainerRemove(id)
var err error
containerId, err = service.MyService.Docker().DockerContainerCreate(appInfo.Image+":"+appInfo.Version, id, cpd, appInfo.NetModel)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
return
}
} else if !reflect.DeepEqual(m.Devices, appInfo.Devices) || m.CpuShares != appInfo.CpuShares || m.Memory != appInfo.Memory || m.Restart != appInfo.Restart {
service.MyService.Docker().DockerContainerUpdate(cpd, id)
containerId, err := service.MyService.Docker().DockerContainerCreate(m.Image, m, m.NetworkModel)
if err != nil {
service.MyService.Docker().DockerContainerUpdateName(m.Label, id)
service.MyService.Docker().DockerContainerStart(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
return
}
// echo -e "hellow\nworld" >>
//step启动容器
err = service.MyService.Docker().DockerContainerStart(containerId)
err := service.MyService.Docker().DockerContainerStart(id)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
return
}
service.MyService.Docker().DockerContainerRemove(id, true)
//更新upnp
if m.Origin != CUSTOM {
//if appInfo.EnableUPNP != appInfo.EnableUPNP {
@@ -954,30 +1055,96 @@ func UpdateSetting(c *gin.Context) {
//}
}
//如果容器端口均未修改,这不进行处理
portsStr, _ := json2.Marshal(m.Ports)
envsStr, _ := json2.Marshal(m.Envs)
volumesStr, _ := json2.Marshal(m.Volumes)
devicesStr, _ := json2.Marshal(m.Devices)
appInfo.ContainerId = containerId
appInfo.PortMap = m.PortMap
appInfo.Label = m.Label
appInfo.Ports = string(portsStr)
appInfo.Envs = string(envsStr)
appInfo.Icon = m.Icon
appInfo.Volumes = string(volumesStr)
appInfo.Devices = string(devicesStr)
appInfo.Position = m.Position
appInfo.EnableUPNP = m.EnableUPNP
appInfo.Restart = m.Restart
appInfo.Memory = m.Memory
appInfo.CpuShares = m.CpuShares
appInfo.UpdatedAt = strconv.FormatInt(time.Now().Unix(), 10)
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)})
}
// @Summary update app version
// @Produce application/json
// @Accept multipart/form-data
// @Tags app
// @Param id path string true "容器id"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/update/{id} [put]
func PutAppUpdate(c *gin.Context) {
id := c.Param("id")
if len(id) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
inspect, err := service.MyService.Docker().DockerContainerInfo(id)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
imageLatest := strings.Split(inspect.Config.Image, ":")[0] + ":latest"
err = service.MyService.Docker().DockerPullImage(imageLatest, model2.AppNotify{})
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
service.MyService.Docker().DockerContainerStop(id)
service.MyService.Docker().DockerContainerUpdateName(id, id)
//service.MyService.Docker().DockerContainerRemove(id, true)
inspect.Image = imageLatest
inspect.Config.Image = imageLatest
containerId, err := service.MyService.Docker().DockerContainerCopyCreate(inspect)
if err != nil {
service.MyService.Docker().DockerContainerUpdateName(inspect.Name, id)
service.MyService.Docker().DockerContainerStart(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
return
}
//step启动容器
err = service.MyService.Docker().DockerContainerStart(containerId)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR)})
return
}
service.MyService.Docker().DockerContainerRemove(id, true)
delete(service.NewVersionApp, id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary get app index
// @Produce application/json
// @Accept application/json
// @Tags app
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/order [get]
func GetAppOrder(c *gin.Context) {
data := service.MyService.System().GetAppOrderFile()
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: json.RawMessage(data)})
}
// @Summary update app index
// @Produce application/json
// @Accept application/json
// @Tags app
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/order [post]
func PostAppOrder(c *gin.Context) {
data := c.PostForm("data")
service.MyService.System().UpAppOrderFile(data)
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
Data: json.RawMessage(data),
})
}
// @Summary 获取容器详情
// @Produce application/json
// @Accept application/json
@@ -1066,46 +1233,89 @@ func ContainerRelyInfo(c *gin.Context) {
// @Router /app/update/{id}/info [get]
func ContainerUpdateInfo(c *gin.Context) {
appId := c.Param("id")
appInfo := service.MyService.App().GetAppDBInfo(appId)
//appInfo := service.MyService.App().GetAppDBInfo(appId)
info, err := service.MyService.Docker().DockerContainerInfo(appId)
if err != nil {
//todo 需要自定义错误
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: err.Error()})
return
}
var port model.PortArrey
json2.Unmarshal([]byte(appInfo.Ports), &port)
var port model.PortArray
// json2.Unmarshal([]byte(appInfo.Ports), &port)
var envs model.EnvArrey
json2.Unmarshal([]byte(appInfo.Envs), &envs)
for k, v := range info.HostConfig.PortBindings {
temp := model.PortMap{
CommendPort: v[0].HostPort,
ContainerPort: k.Port(),
var vol model.PathArrey
json2.Unmarshal([]byte(appInfo.Volumes), &vol)
Protocol: k.Proto(),
}
port = append(port, temp)
}
var dir model.PathArrey
json2.Unmarshal([]byte(appInfo.Devices), &dir)
var envs model.EnvArray
// json2.Unmarshal([]byte(appInfo.Envs), &envs)
for _, v := range info.Config.Env {
temp := model.Env{
Name: strings.Split(v, "=")[0],
Value: strings.Split(v, "=")[1],
}
envs = append(envs, temp)
}
var vol model.PathArray
// json2.Unmarshal([]byte(appInfo.Volumes), &vol)
for i := 0; i < len(info.Mounts); i++ {
temp := model.PathMap{
Path: strings.ReplaceAll(info.Mounts[i].Source, "$AppID", info.Name),
ContainerPath: info.Mounts[i].Destination,
}
vol = append(vol, temp)
}
var driver model.PathArray
//volumesStr, _ := json2.Marshal(m.Volumes)
//devicesStr, _ := json2.Marshal(m.Devices)
for _, v := range info.HostConfig.Resources.Devices {
temp := model.PathMap{
Path: v.PathOnHost,
ContainerPath: v.PathInContainer,
}
driver = append(driver, temp)
}
m := model.CustomizationPostData{}
m.Index = appInfo.Index
m.Icon = appInfo.Icon
m.Icon = info.Config.Labels["icon"]
m.Ports = port
m.Image = appInfo.Image + ":" + appInfo.Version
m.Origin = appInfo.Origin
m.NetworkModel = appInfo.NetModel
m.Description = appInfo.Description
m.Label = appInfo.Label
m.PortMap = appInfo.PortMap
m.Devices = dir //appInfo.Devices
m.Image = info.Config.Image
m.Origin = info.Config.Labels["origin"]
if len(m.Origin) == 0 {
m.Origin = "local"
}
m.NetworkModel = string(info.HostConfig.NetworkMode)
m.Description = info.Config.Labels["desc"]
m.Label = strings.ReplaceAll(info.Name, "/", "")
m.PortMap = info.Config.Labels["web"]
m.Devices = driver
m.Envs = envs
m.Memory = info.HostConfig.Memory >> 20
m.CpuShares = info.HostConfig.CPUShares
m.Volumes = vol //appInfo.Volumes
m.Restart = info.HostConfig.RestartPolicy.Name
m.EnableUPNP = appInfo.EnableUPNP
m.Position = appInfo.Position
m.EnableUPNP = false
m.Index = info.Config.Labels["index"]
m.Position = false
m.CustomId = info.Config.Labels["custom_id"]
if len(m.CustomId) == 0 {
m.CustomId = uuid.NewV4().String()
}
m.CapAdd = info.HostConfig.CapAdd
m.Cmd = info.Config.Cmd
m.HostName = info.Config.Hostname
m.Privileged = info.HostConfig.Privileged
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: m})
}

View File

@@ -4,16 +4,22 @@ import (
"bufio"
"encoding/csv"
"fmt"
"io"
"io/ioutil"
"net/http"
url2 "net/url"
"os"
"path"
"strconv"
"strings"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/gin-gonic/gin"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"github.com/spf13/afero"
)
func downloadReadFile(c *gin.Context) {
@@ -124,12 +130,12 @@ func GetLocalFile(c *gin.Context) {
return
}
// @Summary 下载文件
// @Summary download
// @Produce application/json
// @Accept application/json
// @Tags file
// @Security ApiKeyAuth
// @Param path query string true "路径"
// @Param path query string true "path of file"
// @Success 200 {string} string "ok"
// @Router /file/download [get]
func GetDownloadFile(c *gin.Context) {
@@ -154,15 +160,57 @@ func GetDownloadFile(c *gin.Context) {
//获取文件的名称
fileName := path.Base(filePath)
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", "attachment; filename="+fileName)
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
c.Header("Content-Transfer-Encoding", "binary")
c.Header("Cache-Control", "no-cache")
c.Header("Content-Type", "application/octet-stream")
c.Header("Content-Disposition", "attachment; filename="+fileName)
c.Header("Content-Transfer-Encoding", "binary")
c.File(filePath)
return
}
// @Summary download
// @Produce application/json
// @Accept application/json
// @Tags file
// @Security ApiKeyAuth
// @Param path query string true "path of file"
// @Success 200 {string} string "ok"
// @Router /file/new/download [get]
func GetFileDownloadNew(c *gin.Context) {
filePath := c.Query("path")
if len(filePath) == 0 {
c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.INVALID_PARAMS,
Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS),
})
return
}
if !file.Exists(filePath) {
c.JSON(http.StatusOK, model.Result{
Success: oasis_err2.FILE_DOES_NOT_EXIST,
Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST),
})
return
}
//打开文件
fileStat, _ := os.Stat(filePath)
var AppFs = afero.NewOsFs()
fileT, _ := AppFs.Open(filePath)
//fileTmp, _ := os.Open(filePath)
//defer fileTmp.Close()
//获取文件的名称
//fileName := path.Base(filePath)
//c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(fileName))
//在线
//c.Header("Content-Disposition", "inline")
// extraHeaders := map[string]string{
// "Content-Disposition": `attachment; filename="` + url2.PathEscape(fileName) + `"`,
// }
//c.Header("Cache-Control", "private")
//c.Header("Content-Type", "application/octet-stream")
http.ServeContent(c.Writer, c.Request, fileStat.Name(), fileStat.ModTime(), fileT)
}
// @Summary 获取目录列表
@@ -174,18 +222,58 @@ func GetDownloadFile(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /file/dirpath [get]
func DirPath(c *gin.Context) {
path := c.DefaultQuery("path", "/")
path := c.DefaultQuery("path", "")
info := service.MyService.ZiMa().GetDirPath(path)
if path == "/DATA/AppData" {
list := service.MyService.Docker().DockerContainerList()
apps := make(map[string]string, len(list))
for _, v := range list {
apps[strings.ReplaceAll(v.Names[0], "/", "")] = strings.ReplaceAll(v.Names[0], "/", "")
}
for i := 0; i < len(info); i++ {
if v, ok := apps[info[i].Name]; ok {
info[i].Label = v
info[i].Type = "application"
}
}
} else if path == "/DATA" {
disk := make(map[string]string)
lsblk := service.MyService.Disk().LSBLK(true)
for _, v := range lsblk {
if len(v.Children) > 0 {
t := v.Tran
for _, c := range v.Children {
if len(c.Children) > 0 {
for _, gc := range c.Children {
if len(gc.MountPoint) > 0 {
disk[gc.MountPoint] = t
}
}
}
if len(c.MountPoint) > 0 {
disk[c.MountPoint] = t
}
}
}
}
for i := 0; i < len(info); i++ {
if v, ok := disk[info[i].Path]; ok {
info[i].Type = v
}
}
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: info})
}
// @Summary 重命名目录或文件
// @Summary rename file or dir
// @Produce application/json
// @Accept application/json
// @Tags file
// @Security ApiKeyAuth
// @Param oldpath formData string true "旧的路径"
// @Param newpath formData string true "新路径"
// @Param oldpath formData string true "path of old"
// @Param newpath formData string true "path of new"
// @Success 200 {string} string "ok"
// @Router /file/rename [put]
func RenamePath(c *gin.Context) {
@@ -195,16 +283,16 @@ func RenamePath(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
service.MyService.ZiMa().RenameFile(op, np)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
success, err := service.MyService.ZiMa().RenameFile(op, np)
c.JSON(http.StatusOK, model.Result{Success: success, Message: oasis_err2.GetMsg(success), Data: err})
}
// @Summary 创建文件夹
// @Summary create folder
// @Produce application/json
// @Accept multipart/form-data
// @Tags file
// @Security ApiKeyAuth
// @Param path formData string false "路径"
// @Param path formData string true "path of folder"
// @Success 200 {string} string "ok"
// @Router /file/mkdir [post]
func MkdirAll(c *gin.Context) {
@@ -218,21 +306,259 @@ func MkdirAll(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)})
}
// @Summary 上传文件
// @Summary create file
// @Produce application/json
// @Accept multipart/form-data
// @Tags file
// @Security ApiKeyAuth
// @Param path formData string false "路径"
// @Success 200 {string} string "ok"
// @Router /file/mkdir [post]
func PostFileUpload(c *gin.Context) {
file, _, _ := c.Request.FormFile("file")
//file.Read()
// @Router /file/create [post]
func PostCreateFile(c *gin.Context) {
path := c.PostForm("path")
var code int
if len(path) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
code, _ = service.MyService.ZiMa().CreateFile(path)
c.JSON(http.StatusOK, model.Result{Success: code, Message: oasis_err2.GetMsg(code)})
}
// @Summary upload file
// @Produce application/json
// @Accept multipart/form-data
// @Tags file
// @Security ApiKeyAuth
// @Param path formData string false "file path"
// @Param file formData file true "file"
// @Success 200 {string} string "ok"
// @Router /file/upload [get]
func GetFileUpload(c *gin.Context) {
relative := c.Query("relativePath")
fileName := c.Query("filename")
chunkNumber := c.Query("chunkNumber")
totalChunks, _ := strconv.Atoi(c.DefaultQuery("totalChunks", "0"))
path := c.Query("path")
//上传文件
out, _ := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
defer out.Close()
io.Copy(out, file)
dirPath := ""
hash := file.GetHashByContent([]byte(fileName))
tempDir := config.AppInfo.RootPath + "/temp/" + hash + strconv.Itoa(totalChunks) + "/"
if fileName != relative {
dirPath = strings.TrimSuffix(relative, fileName)
tempDir += dirPath
file.MkDir(path + "/" + dirPath)
}
tempDir += chunkNumber
if !file.CheckNotExist(tempDir) {
c.JSON(200, model.Result{Success: 200, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
return
}
c.JSON(204, model.Result{Success: 204, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary upload file
// @Produce application/json
// @Accept multipart/form-data
// @Tags file
// @Security ApiKeyAuth
// @Param path formData string false "file path"
// @Param file formData file true "file"
// @Success 200 {string} string "ok"
// @Router /file/upload [post]
func PostFileUpload(c *gin.Context) {
f, _, _ := c.Request.FormFile("file")
relative := c.PostForm("relativePath")
fileName := c.PostForm("filename")
totalChunks, _ := strconv.Atoi(c.DefaultPostForm("totalChunks", "0"))
chunkNumber := c.PostForm("chunkNumber")
dirPath := ""
path := c.PostForm("path")
hash := file.GetHashByContent([]byte(fileName))
if len(path) == 0 {
c.JSON(oasis_err2.INVALID_PARAMS, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
tempDir := config.AppInfo.RootPath + "/temp/" + hash + strconv.Itoa(totalChunks) + "/"
if fileName != relative {
dirPath = strings.TrimSuffix(relative, fileName)
tempDir += dirPath
file.MkDir(path + "/" + dirPath)
}
path += "/" + relative
if !file.CheckNotExist(tempDir + chunkNumber) {
file.RMDir(tempDir + chunkNumber)
}
if totalChunks > 1 {
file.IsNotExistMkDir(tempDir)
out, _ := os.OpenFile(tempDir+chunkNumber, os.O_WRONLY|os.O_CREATE, 0644)
defer out.Close()
_, err := io.Copy(out, f)
if err != nil {
c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
} else {
out, _ := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
defer out.Close()
_, err := io.Copy(out, f)
if err != nil {
c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
return
}
fileNum, err := ioutil.ReadDir(tempDir)
if err != nil {
c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
if totalChunks == len(fileNum) {
file.SpliceFiles(tempDir, path, totalChunks, 1)
file.RMDir(tempDir)
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary copy or move file
// @Produce application/json
// @Accept multipart/form-data
// @Tags file
// @Security ApiKeyAuth
// @Param from formData string true "from path"
// @Param to formData string true "to path"
// @Param type formData string true "action" Enums(move,copy)
// @Success 200 {string} string "ok"
// @Router /file/operate [post]
func PostOperateFileOrDir(c *gin.Context) {
from := c.PostForm("from")
to := c.PostForm("to")
t := c.PostForm("type")
if len(from) == 0 || len(t) == 0 || len(to) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
if t == "move" {
lastPath := from[strings.LastIndex(from, "/")+1:]
if !file.CheckNotExist(to + "/" + lastPath) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_OR_DIR_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
return
}
err := os.Rename(from, to+"/"+lastPath)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
} else if t == "copy" {
err := file.CopyDir(from, to)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
} else {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary delete file
// @Produce application/json
// @Accept multipart/form-data
// @Tags file
// @Security ApiKeyAuth
// @Param path query string true "path"
// @Success 200 {string} string "ok"
// @Router /file/delete [delete]
func DeleteFile(c *gin.Context) {
path := c.Query("path")
//err := os.Remove(path)
err := os.RemoveAll(path)
if err != nil {
fmt.Println(err)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_DELETE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.FILE_DELETE_ERROR), Data: err})
return
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary update file
// @Produce application/json
// @Accept multipart/form-data
// @Tags file
// @Security ApiKeyAuth
// @Param path formData string true "path"
// @Param content formData string true "content"
// @Success 200 {string} string "ok"
// @Router /file/update [put]
func PutFileContent(c *gin.Context) {
path := c.PostForm("path")
content := c.PostForm("content")
if !file.Exists(path) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_ALREADY_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
return
}
//err := os.Remove(path)
err := os.RemoveAll(path)
if err != nil {
fmt.Println(err)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_DELETE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.FILE_DELETE_ERROR), Data: err})
return
}
err = file.CreateFileAndWriteContent(path, content)
if err != nil {
fmt.Println(err)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err})
return
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary image thumbnail/original image
// @Produce application/json
// @Accept application/json
// @Tags file
// @Security ApiKeyAuth
// @Param path query string true "path"
// @Param type query string false "original,thumbnail" Enums(original,thumbnail)
// @Success 200 {string} string "ok"
// @Router /file/image [get]
func GetFileImage(c *gin.Context) {
t := c.Query("type")
path := c.Query("path")
if !file.Exists(path) {
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.FILE_ALREADY_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
return
}
if t == "thumbnail" {
f, err := file.GetImage(path, 100, 0)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
c.Writer.WriteString(string(f))
return
}
f, err := os.Open(path)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
c.Writer.WriteString(string(data))
}

View File

@@ -1,15 +1,13 @@
package v1
import (
json2 "encoding/json"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"fmt"
"net/http"
"github.com/IceWhaleTech/CasaOS/service"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
"time"
)
var upGrader = websocket.Upgrader{
@@ -33,24 +31,17 @@ func NotifyWS(c *gin.Context) {
return
}
defer ws.Close()
service.WebSocketConns = append(service.WebSocketConns, ws)
if !service.SocketRun {
service.SocketRun = true
service.SendMeg()
}
for {
mt, message, err := ws.ReadMessage()
if err != nil {
break
}
if string(message) != "notify" {
return
}
for {
list := service.MyService.Notify().GetList()
json, _ := json2.Marshal(list)
err = ws.WriteMessage(mt, json)
if err != nil {
break
}
time.Sleep(time.Second * 2)
}
fmt.Println(mt, message, err)
}
}
// @Summary 标记notify已读
@@ -62,9 +53,10 @@ func NotifyWS(c *gin.Context) {
// @Router /notify/read/{id} [put]
func PutNotifyRead(c *gin.Context) {
id := c.Param("id")
if len(id) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
return
}
// if len(id) == 0 {
// c.JSON(http.StatusOK, model.Result{Success: oasis_err.INVALID_PARAMS, Message: oasis_err.GetMsg(oasis_err.INVALID_PARAMS)})
// return
// }
fmt.Println(id)
service.MyService.Notify().MarkRead(id, types.NOTIFY_READ)
}

803
route/v1/person.go Normal file
View File

@@ -0,0 +1,803 @@
package v1
import (
"bytes"
"encoding/base64"
"encoding/gob"
"encoding/json"
"io/ioutil"
"net"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"time"
natType "github.com/Curtis-Milo/nat-type-identifier-go"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/file"
"github.com/IceWhaleTech/CasaOS/pkg/utils/ip_helper"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/gin-gonic/gin"
uuid "github.com/satori/go.uuid"
)
// @Summary Retry the file that failed to download
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param uui path string true "download uuid"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/refile/{uuid} [get]
func GetPersonReFile(c *gin.Context) {
uid := c.Param("uuid")
_, err := uuid.FromString(uid)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
task := service.MyService.Download().GetDownloadById(uid)
if reflect.DeepEqual(task, model2.PersonDownloadDBModel{}) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
return
}
token := task.From
if _, ok := service.UDPAddressMap[token]; !ok {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
return
}
m := model.MessageModel{}
m.Data = task.Path
m.From = config.ServerInfo.Token
m.To = token
m.Type = types.PERSONDOWNLOAD
m.UUId = uid
go service.Dial(m, false)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary download file
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param share_id query string true "opponent share_id"
// @Param path query string true "file path"
// @Param file_name query string true "file name"
// @Param local_path query string true "local_path"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/file [get]
func GetPersonFile(c *gin.Context) {
path := c.Query("path")
localPath := c.Query("local_path")
token := c.Query("share_id")
fileName := c.Query("file_name")
_, err := uuid.FromString(token)
if len(path) == 0 || err != nil || len(localPath) == 0 || len(fileName) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
if file.CheckNotExist(localPath) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.DIR_NOT_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.DIR_NOT_EXISTS)})
return
}
if _, ok := service.UDPAddressMap[token]; !ok {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
return
}
if _, ok := service.UDPAddressMap[token]; !ok {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
return
}
// task id
uuid := uuid.NewV4().String()
task := model2.PersonDownloadDBModel{}
task.UUID = uuid
task.Name = fileName
task.Length = 0
task.From = token
task.Path = path
task.Size = 0
task.State = types.DOWNLOADAWAIT
task.Created = time.Now().Unix()
task.Type = types.PERSONFILEDOWNLOAD
task.LocalPath = localPath
if service.MyService.Download().GetDownloadListByPath(task) > 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_EXIST_DOWNLOAD, Message: oasis_err2.GetMsg(oasis_err2.PERSON_EXIST_DOWNLOAD)})
return
}
service.MyService.Download().AddDownloadTask(task)
m := model.MessageModel{}
m.Data = path
m.From = config.ServerInfo.Token
m.To = token
m.Type = types.PERSONDOWNLOAD
m.UUId = uuid
go service.Dial(m, false)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary delete download file records
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param uuid path string true "download uuid"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/file/{uuid} [delete]
func DeletePersonDownloadFile(c *gin.Context) {
id := c.Param("uuid")
_, err := uuid.FromString(id)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
task := service.MyService.Download().GetDownloadById(id)
if task.State == types.DOWNLOADING {
m := model.MessageModel{}
m.Data = ""
m.From = config.ServerInfo.Token
m.To = task.From
m.Type = types.PERSONCANCEL
m.UUId = task.UUID
service.CancelList[task.UUID] = task.UUID
service.Dial(m, false)
}
service.MyService.Download().DelDownload(id)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary Get file download list
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param state query int false "wait:0,downloading:1,pause:2,finish:3,error:4,finished:5" Enums(0,1,2,3,4,5)
// @Security ApiKeyAuth
// @Success 200 {object} []model2.PersonDownloadDBModel
// @Router /person/list [get]
func GetPersonDownloadList(c *gin.Context) {
state := c.DefaultQuery("state", "")
list := service.MyService.Download().GetDownloadListByState(state, types.PERSONFILEDOWNLOAD)
//if it is downloading, it need to add 'already'
for i := 0; i < len(list); i++ {
if list[i].State == types.DOWNLOADING {
tempDir := config.AppInfo.RootPath + "/temp" + "/" + list[i].UUID
files, err := ioutil.ReadDir(tempDir)
if err == nil {
list[i].Already = len(files)
}
}
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})
}
// @Summary edit friend's remarks
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param remarks formData string true "remarks name"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/remarks/{shareid} [put]
func PutPersonRemarks(c *gin.Context) {
token := c.Param("shareid")
_, err := uuid.FromString(token)
mark := c.PostForm("remarks")
if err != nil || len(mark) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
friend := model2.FriendModel{}
friend.Token = token
friend.Mark = mark
service.MyService.Friend().EditFriendMark(friend)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary edit friend's
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param write formData bool true "write"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/write/{shareid} [put]
func PutPersonWrite(c *gin.Context) {
token := c.Param("shareid")
_, err := uuid.FromString(token)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
write, _ := strconv.ParseBool(c.PostForm("write"))
friend := model2.FriendModel{}
friend.Token = token
friend.Write = write
service.MyService.Friend().EditFriendMark(friend)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary image thumbnail
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param write formData bool true "write"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/image/thumbnail/{shareid} [get]
func GetPersonImageThumbnail(c *gin.Context) {
token := c.Param("shareid")
path := c.Query("path")
_, err := uuid.FromString(token)
if err != nil || len(path) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
uuid := uuid.NewV4().String()
m := model.MessageModel{}
m.Data = path
m.From = config.ServerInfo.Token
m.To = token
m.Type = types.PERSONIMAGETHUMBNAIL
m.UUId = uuid
img, err := service.Dial(m, false)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
// var buf bytes.Buffer
//err = gob.NewEncoder(&buf).Encode(img.Data)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
var buf bytes.Buffer
err = gob.NewEncoder(&buf).Encode(img.Data)
if err != nil {
c.JSON(http.StatusInternalServerError, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
imageBuffer, _ := base64.StdEncoding.DecodeString(img.Data.(string))
c.Writer.WriteString(string(imageBuffer))
// c.String(http.StatusOK, "data:image/"+filesuffix+";base64,"+img.Data.(string))
//c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: img.Data.(string)})
}
// @Summary get my friend list
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {object} []model2.FriendModel
// @Router /person/users [get]
func GetPersonFriend(c *gin.Context) {
list := service.MyService.Friend().GetFriendList()
for i := 0; i < len(list); i++ {
if v, ok := service.UDPAddressMap[list[i].Token]; ok && len(v) > 0 {
list[i].OnLine = true
if ip_helper.HasLocalIP(net.ParseIP(strings.Split(v, ":")[0])) {
list[i].LocalIP = strings.Split(v, ":")[0]
}
}
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
}
// @Summary network type detection
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/detection [get]
func GetPersonDetection(c *gin.Context) {
// - Blocked
// - Open Internet
// - Full Cone
// - Symmetric UDP Firewall
// - Restric NAT
// - Restric Port NAT
// - Symmetric NAT
result, err := natType.GetDeterminedNatType(true, 5, "stun.l.google.com")
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
//result := service.MyService.Person().GetPersionNetWorkTypeDetection()
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: result})
}
// @Summary add friend
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/user/{shareids} [post]
func PostAddPersonFriend(c *gin.Context) {
token := c.Param("shareids")
tokenList := strings.Split(token, ",")
for _, v := range tokenList {
_, err := uuid.FromString(v)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
if v == config.ServerInfo.Token {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_MYSELF, Message: oasis_err2.GetMsg(oasis_err2.PERSON_MYSELF)})
return
}
udb := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: v})
if !reflect.DeepEqual(udb, model2.FriendModel{Token: v}) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_EXIST_FRIEND, Message: oasis_err2.GetMsg(oasis_err2.PERSON_EXIST_FRIEND)})
return
}
user := service.MyService.Casa().GetUserInfoByShareId(v)
if reflect.DeepEqual(user, model.UserInfo{}) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_NOT_EXIST_USER, Message: oasis_err2.GetMsg(oasis_err2.PERSON_NOT_EXIST_USER)})
return
}
message := model.MessageModel{}
message.Type = types.PERSONCONNECTION
message.Data = v
message.From = config.ServerInfo.Token
message.To = v
message.UUId = uuid.NewV4().String()
go service.Dial(message, true)
msg := model.MessageModel{}
msg.Type = types.PERSONGETIP
msg.Data = ""
msg.From = config.ServerInfo.Token
msg.To = v
msg.UUId = uuid.NewV4().String()
service.Dial(msg, true)
friend := model2.FriendModel{}
friend.Token = v
friend.Avatar = user.Avatar
friend.Block = false
friend.State = types.FRIENDSTATEWAIT
friend.NickName = user.NickName
friend.Profile = user.Desc
friend.Version = user.Version
service.MyService.Friend().AddFriend(friend)
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary Get a list of directories
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param share_id query string true "Opponent share_id"
// @Param path query string true "dir path"
// @Security ApiKeyAuth
// @Success 200 {object} []model.Path
// @Router /person/directory [get]
func GetPersonDirectory(c *gin.Context) {
path := c.Query("path")
token := c.Query("share_id")
_, err := uuid.FromString(token)
if len(path) == 0 || err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
if _, ok := service.UDPAddressMap[token]; !ok {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_REMOTE_ERROR, Message: oasis_err2.GetMsg(oasis_err2.PERSON_REMOTE_ERROR)})
return
}
uuid := uuid.NewV4().String()
m := model.MessageModel{}
m.Data = path
m.From = config.ServerInfo.Token
m.To = token
m.Type = types.PERSONDIRECTORY
m.UUId = uuid
result, err := service.Dial(m, false)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
dataModel := []model.Path{}
if uuid == m.UUId {
dataModelByte, _ := json.Marshal(result.Data)
err := json.Unmarshal(dataModelByte, &dataModel)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
return
}
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: dataModel})
}
// @Summary Modify the download storage directory
// @Produce application/json
// @Accept multipart/form-data
// @Tags person
// @Security ApiKeyAuth
// @Param path formData string true "path"
// @Success 200 {string} string "ok"
// @Router /person/down/dir [post]
func PostPersonDownDir(c *gin.Context) {
downPath := c.PostForm("path")
if len(downPath) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
if file.CheckNotExist(downPath) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.DIR_NOT_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.DIR_NOT_EXISTS)})
return
}
config.Cfg.Section("file").Key("DownloadDir").SetValue(downPath)
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
config.FileSettingInfo.DownloadDir = downPath
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary Get the download storage directory
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/down/dir [get]
func GetPersonDownDir(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: config.FileSettingInfo.DownloadDir})
}
// @Summary Modify the shared directory
// @Produce application/json
// @Accept multipart/form-data
// @Tags person
// @Security ApiKeyAuth
// @Param share formData string true "share"
// @Success 200 {string} string "ok"
// @Router /person/share [post]
func PostPersonShare(c *gin.Context) {
share := c.PostForm("share")
if len(share) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
var list []string
json.Unmarshal([]byte(share), &list)
if len(list) == 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
for _, v := range list {
if !file.Exists(v) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_ALREADY_EXISTS, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
return
}
}
config.Cfg.Section("file").Key("ShareDir").SetValue(strings.Join(list, "|"))
config.Cfg.SaveTo(config.SystemConfigInfo.ConfigPath)
config.FileSettingInfo.ShareDir = list
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary Get the shared directory
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/share [get]
func GetPersonShare(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: config.FileSettingInfo.ShareDir})
}
// @Summary Get the shareid
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/shareid [get]
func GetPersonShareId(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: config.ServerInfo.Token})
}
// @Summary Modify disabled status
// @Produce application/json
// @Accept application/json
// @Tags person
// @Param block formData bool false "Disable or not,Default:false "
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/block/{shareid} [put]
func PutPersonBlock(c *gin.Context) {
token := c.Param("shareid")
_, err := uuid.FromString(token)
block, _ := strconv.ParseBool(c.PostForm("block"))
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
friend := model2.FriendModel{}
friend.Token = token
friend.Block = block
service.MyService.Friend().EditFriendBlock(friend)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary Delete my friend
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/user/{shareid} [delete]
func DeletePersonFriend(c *gin.Context) {
token := c.Param("shareid")
_, err := uuid.FromString(token)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
friend := model2.FriendModel{}
friend.Token = token
service.MyService.Friend().DeleteFriend(friend)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary Get public person
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/public [get]
func GetPersonPublic(c *gin.Context) {
list := service.MyService.Casa().GetPersonPublic()
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: list})
}
// @Summary upload file to friend
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Param path formData string true "Destination path"
// @Param local_path formData string true "Full path of the file to be uploaded"
// @Success 200 {string} string "ok"
// @Router /person/file/{shareid} [post]
func PostPersonFile(c *gin.Context) {
token := c.Param("shareid")
_, err := uuid.FromString(token)
path := c.PostForm("path")
localPath := c.PostForm("local_path")
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
if !file.Exists(localPath) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.FILE_DOES_NOT_EXIST, Message: oasis_err2.GetMsg(oasis_err2.FILE_DOES_NOT_EXIST)})
return
}
uuid := uuid.NewV4().String()
m := model.MessageModel{}
m.Data = path
m.From = config.ServerInfo.Token
m.To = token
m.Type = types.PERSONUPLOAD
m.UUId = uuid
go service.UDPSendData(m, localPath)
f, _ := os.Stat(localPath)
task := model2.PersonDownloadDBModel{}
task.UUID = uuid
task.Name = f.Name()
task.Length = 0
task.From = token
task.Path = path
task.Size = f.Size()
task.State = types.DOWNLOADFINISHED
task.Created = time.Now().Unix()
task.Type = types.PERSONFILEUPLOAD
task.LocalPath = localPath
if service.MyService.Download().GetDownloadListByPath(task) > 0 {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.PERSON_EXIST_DOWNLOAD, Message: oasis_err2.GetMsg(oasis_err2.PERSON_EXIST_DOWNLOAD)})
return
}
service.MyService.Download().AddDownloadTask(task)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// @Summary agree add friend
// @Produce application/json
// @Accept application/json
// @Tags person
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /person/friend/{shareid} [put]
func PutPersonAgreeFriend(c *gin.Context) {
token := c.Param("shareid")
_, err := uuid.FromString(token)
if err != nil {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
return
}
user := service.MyService.Friend().GetFriendById(model2.FriendModel{Token: token})
if user.State != types.FRIENDSTATEREQUEST {
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.COMMAND_ERROR_INVALID_OPERATION, Message: oasis_err2.GetMsg(oasis_err2.COMMAND_ERROR_INVALID_OPERATION)})
return
}
service.MyService.Friend().AgreeFrined(user.Token)
uuid := uuid.NewV4().String()
m := model.MessageModel{}
m.Data = ""
m.From = config.ServerInfo.Token
m.To = token
m.Type = types.PERSONAGREEFRIEND
m.UUId = uuid
go service.Dial(m, true)
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
}
// // @Summary upload file
// // @Produce application/json
// // @Accept multipart/form-data
// // @Tags person
// // @Security ApiKeyAuth
// // @Param path formData string false "file path"
// // @Param file formData file true "file"
// // @Success 200 {string} string "ok"
// // @Router /person/upload/{shareid} [get]
// func GetPersonFileUpload(c *gin.Context) {
// token := c.Param("shareid")
// _, err := uuid.FromString(token)
// path := c.Query("path")
// if err != nil {
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
// return
// }
// relative := c.Query("relativePath")
// fileName := c.Query("filename")
// chunkNumber := c.Query("chunkNumber")
// totalChunks, _ := strconv.Atoi(c.DefaultQuery("totalChunks", "0"))
// dirPath := ""
// hash := file.GetHashByContent([]byte(fileName))
// tempDir := "/casaOS/temp/" + hash + strconv.Itoa(totalChunks) + "/"
// if fileName != relative {
// dirPath = strings.TrimSuffix(relative, fileName)
// tempDir += dirPath
// file.MkDir(path + "/" + dirPath)
// }
// tempDir += chunkNumber
// if !file.CheckNotExist(tempDir) {
// c.JSON(200, model.Result{Success: 200, Message: oasis_err2.GetMsg(oasis_err2.FILE_ALREADY_EXISTS)})
// return
// }
// c.JSON(204, model.Result{Success: 204, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
// }
// // @Summary upload file
// // @Produce application/json
// // @Accept multipart/form-data
// // @Tags person
// // @Security ApiKeyAuth
// // @Param path formData string false "file path"
// // @Param file formData file true "file"
// // @Success 200 {string} string "ok"
// // @Router /person/upload [post]
// func PostPersonFileUpload(c *gin.Context) {
// token := c.Param("shareid")
// _, err := uuid.FromString(token)
// if err != nil {
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
// return
// }
// f, _, _ := c.Request.FormFile("file")
// relative := c.PostForm("relativePath")
// fileName := c.PostForm("filename")
// totalChunks, _ := strconv.Atoi(c.DefaultPostForm("totalChunks", "0"))
// chunkNumber := c.PostForm("chunkNumber")
// dirPath := ""
// path := c.PostForm("path")
// hash := file.GetHashByContent([]byte(fileName))
// if len(path) == 0 {
// c.JSON(oasis_err2.INVALID_PARAMS, model.Result{Success: oasis_err2.INVALID_PARAMS, Message: oasis_err2.GetMsg(oasis_err2.INVALID_PARAMS)})
// return
// }
// tempDir := "/casaOS/temp/" + hash + strconv.Itoa(totalChunks) + "/"
// if fileName != relative {
// dirPath = strings.TrimSuffix(relative, fileName)
// tempDir += dirPath
// file.MkDir(path + "/" + dirPath)
// }
// path += "/" + relative
// if !file.CheckNotExist(tempDir + chunkNumber) {
// file.RMDir(tempDir + chunkNumber)
// }
// if totalChunks > 1 {
// file.IsNotExistMkDir(tempDir)
// out, _ := os.OpenFile(tempDir+chunkNumber, os.O_WRONLY|os.O_CREATE, 0644)
// defer out.Close()
// _, err := io.Copy(out, f)
// if err != nil {
// c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
// return
// }
// } else {
// out, _ := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)
// defer out.Close()
// _, err := io.Copy(out, f)
// if err != nil {
// c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
// return
// }
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
// return
// }
// fileNum, err := ioutil.ReadDir(tempDir)
// if err != nil {
// c.JSON(oasis_err2.ERROR, model.Result{Success: oasis_err2.ERROR, Message: oasis_err2.GetMsg(oasis_err2.ERROR), Data: err.Error()})
// return
// }
// if totalChunks == len(fileNum) {
// file.RMDir(tempDir)
// }
// c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS)})
// }

22
route/v1/search.go Normal file
View File

@@ -0,0 +1,22 @@
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})
}

35
route/v1/sync.go Normal file
View File

@@ -0,0 +1,35 @@
package v1
import (
"net/http"
"net/http/httputil"
"net/url"
"strings"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
"github.com/gin-gonic/gin"
)
func SyncToSyncthing(c *gin.Context) {
u := c.Param("url")
target := "http://" + strings.Split(c.Request.Host, ":")[0] + ":" + config.SystemConfigInfo.SyncPort
remote, err := url.Parse(target)
if err != nil {
return
}
proxy := httputil.NewSingleHostReverseProxy(remote)
c.Request.Header.Add("X-API-Key", config.SystemConfigInfo.SyncKey)
//c.Request.Header.Add("X-API-Key", config.SystemConfigInfo.SyncKey)
c.Request.URL.Path = u
proxy.ServeHTTP(c.Writer, c.Request)
}
func GetSyncConfig(c *gin.Context) {
data := make(map[string]string)
data["key"] = config.SystemConfigInfo.SyncKey
data["port"] = config.SystemConfigInfo.SyncPort
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
}

View File

@@ -1,21 +1,29 @@
package v1
import (
"encoding/json"
"fmt"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"time"
"unsafe"
"github.com/IceWhaleTech/CasaOS/model"
"github.com/IceWhaleTech/CasaOS/pkg/config"
"github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
oasis_err2 "github.com/IceWhaleTech/CasaOS/pkg/utils/oasis_err"
port2 "github.com/IceWhaleTech/CasaOS/pkg/utils/port"
"github.com/IceWhaleTech/CasaOS/pkg/utils/version"
"github.com/IceWhaleTech/CasaOS/service"
model2 "github.com/IceWhaleTech/CasaOS/service/model"
"github.com/IceWhaleTech/CasaOS/types"
"github.com/gin-gonic/gin"
"net/http"
"strconv"
"time"
)
// @Summary 系统信息
// @Summary check version
// @Produce application/json
// @Accept application/json
// @Tags sys
@@ -26,13 +34,12 @@ func CheckVersion(c *gin.Context) {
need, version := version.IsNeedUpdate()
if need {
installLog := model2.AppNotify{}
installLog.CustomId = ""
installLog.State = 0
installLog.Message = "New version " + version.Version + " is ready, ready to upgrade"
installLog.Speed = 100
installLog.Type = types.NOTIFY_TYPE_NEED_CONFIRM
installLog.CreatedAt = strconv.FormatInt(time.Now().Unix(), 10)
installLog.UpdatedAt = strconv.FormatInt(time.Now().Unix(), 10)
installLog.Name = "CasaOS System"
service.MyService.Notify().AddLog(installLog)
}
data := make(map[string]interface{}, 1)
@@ -43,6 +50,32 @@ func CheckVersion(c *gin.Context) {
return
}
// @Summary check client version
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/client/version [get]
func GetClientVersion(c *gin.Context) {
need, version := version.IsClientNeedUpdate()
if need {
installLog := model2.AppNotify{}
installLog.State = 0
installLog.Message = "New version " + version.Version + " is ready, ready to upgrade"
installLog.Type = types.NOTIFY_TYPE_NEED_CONFIRM
installLog.CreatedAt = strconv.FormatInt(time.Now().Unix(), 10)
installLog.UpdatedAt = strconv.FormatInt(time.Now().Unix(), 10)
installLog.Name = "CasaOS System"
service.MyService.Notify().AddLog(installLog)
}
data := make(map[string]interface{}, 1)
data["is_need"] = need
data["version"] = version
data["current_version"] = types.CURRENTVERSION
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: data})
}
// @Summary 系统信息
// @Produce application/json
// @Accept application/json
@@ -51,10 +84,8 @@ func CheckVersion(c *gin.Context) {
// @Success 200 {string} string "ok"
// @Router /sys/update [post]
func SystemUpdate(c *gin.Context) {
fmt.Println("开始更新")
need, version := version.IsNeedUpdate()
if need {
fmt.Println("进入更新")
service.MyService.System().UpdateSystemVersion(version.Version)
}
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS)})
@@ -62,28 +93,40 @@ func SystemUpdate(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: config.SystemConfigInfo})
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: json.RawMessage(config.SystemConfigInfo.ConfigStr)})
}
// @Summary get logs
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/error/logs [get]
func GetCasaOSErrorLogs(c *gin.Context) {
line, _ := strconv.Atoi(c.DefaultQuery("line", "100"))
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: service.MyService.System().GetCasaOSLogs(line)})
}
// @Summary 修改配置文件
// @Produce application/json
// @Accept multipart/form-data
// @Tags user
// @Param file formData file true "用户头像"
// @Tags sys
// @Param config formData string true "config json string"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /user/changhead [post]
// @Router /sys/changhead [post]
func PostSetSystemConfig(c *gin.Context) {
var systemConfig model.SystemConfig
c.BindJSON(&systemConfig)
service.MyService.System().UpSystemConfig(systemConfig)
buf := make([]byte, 1024)
n, _ := c.Request.Body.Read(buf)
service.MyService.System().UpSystemConfig(string(buf[0:n]), "")
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
Data: config.SystemConfigInfo,
Data: json.RawMessage(config.SystemConfigInfo.ConfigStr),
})
return
}
//系统配置
@@ -91,10 +134,349 @@ func GetSystemConfigDebug(c *gin.Context) {
array := service.MyService.System().GetSystemConfigDebug()
disk := service.MyService.ZiMa().GetDiskInfo()
array = append(array, fmt.Sprintf("disk,totle:%v,used:%v,UsedPercent:%v", disk.Total>>20, disk.Used>>20, disk.UsedPercent))
sys := service.MyService.ZiMa().GetSysInfo()
//todo 准备sync需要显示的数据(镜像,容器)
var systemAppStatus string
images := service.MyService.Docker().IsExistImage("linuxserver/syncthing")
systemAppStatus += "Sync img: " + strconv.FormatBool(images) + "\n\t"
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: array})
list := service.MyService.App().GetSystemAppList()
for _, v := range list {
systemAppStatus += v.Image + ",\n\t"
}
systemAppStatus += "Sync Key length: " + strconv.Itoa(len(config.SystemConfigInfo.SyncKey))
var bugContent string = fmt.Sprintf(`
- OS: %s
- CasaOS Version: %s
- Disk Total: %v
- Disk Used: %v
- Sync State: %s
- System Info: %s
- Browser: $Browser$
- Version: $Version$
`, sys.OS, types.CURRENTVERSION, disk.Total>>20, disk.Used>>20, systemAppStatus, array)
// 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})
}
func Sys(c *gin.Context) {
service.DockerPull()
//widget配置
func GetWidgetConfig(c *gin.Context) {
c.JSON(http.StatusOK, model.Result{Success: oasis_err.SUCCESS, Message: oasis_err.GetMsg(oasis_err.SUCCESS), Data: json.RawMessage(config.SystemConfigInfo.WidgetList)})
}
// @Summary 修改组件配置文件
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/widget/config [post]
func PostSetWidgetConfig(c *gin.Context) {
buf := make([]byte, 1024)
n, _ := c.Request.Body.Read(buf)
service.MyService.System().UpSystemConfig("", string(buf[0:n]))
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
Data: json.RawMessage(config.SystemConfigInfo.WidgetList),
})
}
// @Summary get casaos server port
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/port [get]
func GetCasaOSPort(c *gin.Context) {
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
Data: config.ServerInfo.HttpPort,
})
}
// @Summary edit casaos server port
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Param port formData string true "port"
// @Success 200 {string} string "ok"
// @Router /sys/port [put]
func PutCasaOSPort(c *gin.Context) {
port, err := strconv.Atoi(c.PostForm("port"))
if err != nil {
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.ERROR,
Message: err.Error(),
})
return
}
isAvailable := port2.IsPortAvailable(port, "tcp")
if !isAvailable {
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.PORT_IS_OCCUPIED,
Message: oasis_err.GetMsg(oasis_err.PORT_IS_OCCUPIED),
})
return
}
service.MyService.System().UpSystemPort(strconv.Itoa(port))
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
})
}
// @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 := false
if !config.UserInfo.Initialized {
initUser = true
}
data := make(map[string]interface{}, 1)
data["need_init_user"] = initUser
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
Data: data,
})
}
// @Summary active killing casaos
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/kill [post]
func PostKillCasaOS(c *gin.Context) {
os.Exit(0)
}
// @Summary Turn off usb auto-mount
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/usb/off [put]
func PutSystemOffUSBAutoMount(c *gin.Context) {
service.MyService.System().UpdateUSBAutoMount("False")
service.MyService.System().ExecUSBAutoMountShell("False")
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
})
}
// @Summary Turn off usb auto-mount
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/usb [get]
func GetSystemUSBAutoMount(c *gin.Context) {
state := "True"
if config.ServerInfo.USBAutoMount == "False" {
state = "False"
}
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
Data: state,
})
}
// @Summary get system hardware info
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/hardware/info [get]
func GetSystemHardwareInfo(c *gin.Context) {
data := make(map[string]string, 1)
data["drive_model"] = service.MyService.ZiMa().GetDeviceTree()
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
Data: data,
})
}
// @Summary Turn off usb auto-mount
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/usb/on [put]
func PutSystemOnUSBAutoMount(c *gin.Context) {
service.MyService.System().UpdateUSBAutoMount("True")
service.MyService.System().ExecUSBAutoMountShell("True")
c.JSON(http.StatusOK,
model.Result{
Success: oasis_err.SUCCESS,
Message: oasis_err.GetMsg(oasis_err.SUCCESS),
})
}
// @Summary system info
// @Produce application/json
// @Accept application/json
// @Tags sys
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /sys/info [get]
func Info(c *gin.Context) {
var data = make(map[string]interface{}, 6)
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" {
temp := service.MyService.Disk().SmartCTL(list[i].Path)
if reflect.DeepEqual(temp, model.SmartctlA{}) {
continue
}
//list[i].Temperature = temp.Temperature.Current
if !temp.SmartStatus.Passed {
healthy = false
}
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
data["disk"] = summary
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)
}
}
data["usb"] = usb
cpu := service.MyService.ZiMa().GetCpuPercent()
num := service.MyService.ZiMa().GetCpuCoreNum()
cpuData := make(map[string]interface{})
cpuData["percent"] = cpu
cpuData["num"] = num
data["cpu"] = cpuData
data["mem"] = service.MyService.ZiMa().GetMemInfo()
//拼装网络信息
netList := service.MyService.ZiMa().GetNetInfo()
newNet := []model.IOCountersStat{}
nets := service.MyService.ZiMa().GetNet(true)
for _, n := range netList {
for _, netCardName := range nets {
if n.Name == netCardName {
item := *(*model.IOCountersStat)(unsafe.Pointer(&n))
item.State = strings.TrimSpace(service.MyService.ZiMa().GetNetState(n.Name))
item.Time = time.Now().Unix()
newNet = append(newNet, item)
break
}
}
}
data["net"] = newNet
c.JSON(http.StatusOK, model.Result{Success: oasis_err2.SUCCESS, Message: oasis_err2.GetMsg(oasis_err2.SUCCESS), Data: data})
}

View File

@@ -19,7 +19,8 @@ import (
// @Success 200 {string} string "ok"
// @Router /task/list [get]
func GetTaskList(c *gin.Context) {
list := service.MyService.Task().List(true)
//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})
}

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