Skip to content

Commit 1d37fdd

Browse files
author
NhanPT
committed
Merge branch 'main' of github.com:help-14/magma
2 parents 6859b42 + 692cd64 commit 1d37fdd

File tree

11 files changed

+303
-215
lines changed

11 files changed

+303
-215
lines changed

src/main.go

Lines changed: 22 additions & 181 deletions
Original file line numberDiff line numberDiff line change
@@ -1,220 +1,61 @@
11
package main
22

33
import (
4-
"html/template"
5-
"io/ioutil"
4+
"errors"
5+
"fmt"
66
"log"
77
"net/http"
8-
"net"
98
"os"
10-
"path"
119
"path/filepath"
12-
"strings"
13-
"time"
1410

15-
"github.com/fsnotify/fsnotify"
1611
docker "github.com/help-14/magma/addons/docker"
1712
healthcheckserver "github.com/help-14/magma/addons/health-check-server"
1813
"github.com/help-14/magma/modules"
1914
)
2015

21-
var pwd string
22-
var themeDir string
23-
var clientAddress string
24-
var appConfig modules.Config
25-
var websiteData = struct {
26-
Config modules.WebsiteConfig
27-
Language modules.Language
28-
Contents []modules.GroupData
29-
}{}
30-
var webTemplate *template.Template
31-
3216
func main() {
3317
prepare()
34-
loadData()
35-
go watchChanges()
36-
37-
commonfs := http.FileServer(http.Dir(filepath.Join(pwd, "data")))
38-
http.Handle("/common/", http.StripPrefix("/common/", commonfs))
39-
40-
languagefs := http.FileServer(http.Dir(filepath.Join(pwd, "languages")))
41-
http.Handle("/languages/", http.StripPrefix("/languages/", languagefs))
42-
43-
th := themeHandler{}
44-
http.Handle("/theme/", th)
45-
46-
http.HandleFunc("/weather", serveWeather)
47-
http.HandleFunc("/", serveTemplate)
18+
mux := http.NewServeMux()
4819

20+
modules.SetupLanguage(mux)
21+
modules.SetupTemplate(mux)
22+
modules.SetupWeather(mux)
4923
//loadAddons()
5024

25+
server := http.Server{
26+
Addr: fmt.Sprintf(":%d", 7001),
27+
Handler: mux,
28+
}
5129
log.Println("Listening on http://localhost:7001 ...")
52-
err := http.ListenAndServe(":7001", nil)
53-
if err != nil {
54-
log.Fatal(err)
30+
if err := server.ListenAndServe(); err != nil {
31+
if !errors.Is(err, http.ErrServerClosed) {
32+
fmt.Printf("error running http server: %s\n", err)
33+
}
5534
}
35+
// err := http.ListenAndServe(":7001", nil)
36+
// if err != nil {
37+
// log.Fatal(err)
38+
// }
5639
}
5740

5841
func prepare() {
59-
pwd, _ = os.Getwd()
60-
61-
dataPath := filepath.Join(pwd, "data")
42+
dataPath := filepath.Join(modules.CurrentPath(), "data")
6243
os.MkdirAll(dataPath, os.ModePerm)
6344

6445
iconPath := filepath.Join(dataPath, "icon")
6546
os.RemoveAll(iconPath)
6647
os.MkdirAll(iconPath, os.ModePerm)
6748

68-
modules.CopyDir(filepath.Join(pwd, "common"), dataPath, false)
69-
}
70-
71-
func RemoveIndex(s []modules.BookmarkData, index int) {
72-
copy(s[index:], s[index+1:])
73-
s[len(s)-1] = modules.BookmarkData{"", "", "", false}
74-
s = s[:len(s)-1]
75-
}
76-
77-
func pruneData() {
78-
// Remove local ressources access
79-
for group := 0; group < len(websiteData.Contents); group++ {
80-
for col := 0; col < len(websiteData.Contents[group].Columns); col++ {
81-
bookmarks := websiteData.Contents[group].Columns[col].Bookmarks
82-
for bookmark := 0; bookmark < len(websiteData.Contents[group].Columns[col].Bookmarks); bookmark++ {
83-
bookmarkData := websiteData.Contents[group].Columns[col].Bookmarks[bookmark]
84-
if bookmarkData.IsLocal {
85-
RemoveIndex(bookmarks, bookmark)
86-
bookmark--
87-
}
88-
}
89-
websiteData.Contents[group].Columns[col].Bookmarks = bookmarks
90-
}
91-
}
92-
loadTemplate()
93-
}
94-
95-
func loadData() {
96-
appConfig = modules.LoadConfig()
97-
websiteData.Config = appConfig.Website
98-
websiteData.Language = modules.LoadLanguage(appConfig.Website.Language)
99-
websiteData.Contents = modules.LoadContent().Data
100-
101-
// Download icon to local and remove local ressources access
102-
for group := 0; group < len(websiteData.Contents); group++ {
103-
for col := 0; col < len(websiteData.Contents[group].Columns); col++ {
104-
for bookmark := 0; bookmark < len(websiteData.Contents[group].Columns[col].Bookmarks); bookmark++ {
105-
bookmarkData := websiteData.Contents[group].Columns[col].Bookmarks[bookmark]
106-
if bookmarkData.IsImage() || bookmarkData.IsSVG() {
107-
iconPath := bookmarkData.Icon
108-
fileName := path.Base(iconPath)
109-
if modules.DownloadFile(iconPath, filepath.Join(pwd, "data", "icon", fileName)) {
110-
websiteData.Contents[group].Columns[col].Bookmarks[bookmark].Icon = "/common/icon/" + fileName
111-
}
112-
}
113-
}
114-
}
115-
}
116-
loadTemplate()
117-
}
118-
119-
func loadTemplate() {
120-
themeDir = filepath.Join(pwd, "themes", appConfig.Website.Theme)
121-
tmpl, _ := template.ParseFiles(filepath.Join(themeDir, "index.html"))
122-
webTemplate = tmpl
49+
modules.CopyDir(filepath.Join(modules.CurrentPath(), "common"), dataPath, false)
12350
}
12451

12552
func loadAddons() {
126-
for i := 0; i < len(appConfig.Addons); i++ {
127-
switch addonName := appConfig.Addons[i]; addonName {
53+
for i := 0; i < len(modules.AppConfig.Addons); i++ {
54+
switch addonName := modules.AppConfig.Addons[i]; addonName {
12855
case "docker":
12956
docker.Setup()
13057
case "health-check-server":
13158
healthcheckserver.Setup()
13259
}
13360
}
13461
}
135-
136-
func watchChanges() {
137-
watcher, err := fsnotify.NewWatcher()
138-
if err != nil {
139-
log.Fatal(err)
140-
}
141-
defer watcher.Close()
142-
143-
done := make(chan bool)
144-
go func() {
145-
for {
146-
select {
147-
case event, ok := <-watcher.Events:
148-
if !ok {
149-
return
150-
}
151-
log.Println("Modified file:", event.Name)
152-
loadData()
153-
case err, ok := <-watcher.Errors:
154-
if !ok {
155-
return
156-
}
157-
log.Println("error:", err)
158-
}
159-
}
160-
}()
161-
162-
watcher.Add(filepath.Join(pwd, "data", "data.yaml"))
163-
watcher.Add(filepath.Join(pwd, "data", "config.yaml"))
164-
watcher.Add(filepath.Join(pwd, "themes", appConfig.Website.Theme, "index.html"))
165-
<-done
166-
}
167-
168-
func ClientIsLocal(r *http.Request) bool {
169-
IPAddress := net.ParseIP(r.Header.Get("X-Real-Ip"))
170-
if IPAddress == nil {
171-
IPAddress = net.ParseIP(r.Header.Get("X-Forwarded-For"))
172-
}
173-
if IPAddress == nil {
174-
IPAddress = net.ParseIP(strings.Split(r.RemoteAddr, ":")[0])
175-
}
176-
return IPAddress.IsPrivate()
177-
}
178-
179-
func serveTemplate(w http.ResponseWriter, r *http.Request) {
180-
if ! ClientIsLocal(r) {
181-
pruneData()
182-
} else {
183-
loadData()
184-
}
185-
webTemplate.Execute(w, websiteData)
186-
}
187-
188-
type themeHandler struct {
189-
format string
190-
}
191-
192-
func (th themeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
193-
http.ServeFile(w, r, strings.Replace(r.URL.Path, "/theme", themeDir, 1))
194-
}
195-
196-
var weatherTimeOut int64
197-
var weatherCache []byte
198-
199-
func serveWeather(w http.ResponseWriter, r *http.Request) {
200-
w.Header().Set("Content-Type", "application/json")
201-
if appConfig.OpenWeatherMap.ApiKey == "demo" {
202-
w.Write([]byte("{\"coord\":{\"lon\":105.8085,\"lat\":21.0427},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04n\"}],\"base\":\"stations\",\"main\":{\"temp\":301.14,\"feels_like\":305.69,\"temp_min\":301.14,\"temp_max\":301.14,\"pressure\":1004,\"humidity\":83},\"visibility\":10000,\"wind\":{\"speed\":6.17,\"deg\":120},\"clouds\":{\"all\":75},\"dt\":1650981392,\"sys\":{\"type\":1,\"id\":9308,\"country\":\"VN\",\"sunrise\":1650925786,\"sunset\":1650971952},\"timezone\":25200,\"id\":1581130,\"name\":\"Hanoi\",\"cod\":200}"))
203-
} else {
204-
if time.Now().UnixMilli() >= weatherTimeOut {
205-
resp, err := http.Get("https://api.openweathermap.org/data/2.5/weather?lat=" + appConfig.OpenWeatherMap.Latitude + "&lon=" + appConfig.OpenWeatherMap.Longitude + "&limit=1&appid=" + appConfig.OpenWeatherMap.ApiKey)
206-
if err != nil {
207-
log.Fatalln(err)
208-
return
209-
}
210-
body, err := ioutil.ReadAll(resp.Body)
211-
if err != nil {
212-
log.Fatalln(err)
213-
return
214-
}
215-
weatherCache = body
216-
weatherTimeOut = time.Now().UnixMilli() + 1800000
217-
}
218-
w.Write(weatherCache)
219-
}
220-
}

src/modules/config.go

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package modules
22

33
import (
44
"fmt"
5-
"io/ioutil"
65
"path/filepath"
76

87
"gopkg.in/yaml.v2"
@@ -29,7 +28,9 @@ type OpenWeatherMapConfig struct {
2928
Latitude string `yaml:"lat"`
3029
}
3130

32-
func LoadConfig() Config {
31+
var AppConfig Config
32+
33+
func LoadConfig() {
3334
defaultConfig := Config{
3435
Website: WebsiteConfig{
3536
Title: "Magma Dashboard",
@@ -41,20 +42,21 @@ func LoadConfig() Config {
4142
},
4243
Addons: []string{},
4344
}
45+
AppConfig = defaultConfig
4446

45-
yamlFile, err := ioutil.ReadFile(filepath.Join("data", "config.yaml"))
47+
yamlFile, err := ReadFile(filepath.Join("data", "config.yaml"))
4648
if err != nil {
4749
fmt.Printf("Error reading YAML file: %s\n", err)
48-
return defaultConfig
50+
return
4951
}
5052

5153
var yamlConfig Config
5254
err = yaml.Unmarshal(yamlFile, &yamlConfig)
5355
if err != nil {
5456
fmt.Printf("Error parsing YAML file: %s\n", err)
55-
return defaultConfig
57+
return
5658
}
5759

5860
fmt.Println("Loaded config:", yamlConfig)
59-
return yamlConfig
61+
AppConfig = yamlConfig
6062
}

src/modules/content.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package modules
33
import (
44
"fmt"
55
"index/suffixarray"
6-
"io/ioutil"
76
"path/filepath"
87
"regexp"
98
"strings"
@@ -28,16 +27,17 @@ type ColumnData struct {
2827
}
2928

3029
type BookmarkData struct {
31-
Name string `yaml:"name"`
32-
Url string `yaml:"url"`
33-
Icon string `yaml:"icon"`
34-
IsLocal bool `yaml:"isLocal"`
30+
Name string `yaml:"name"`
31+
Url string `yaml:"url"`
32+
UrlLocal string `yaml:"urlLocal"`
33+
Icon string `yaml:"icon"`
34+
IsLocal bool `yaml:"isLocal"`
3535
}
3636

3737
func LoadContent() ContentData {
3838
emptyData := ContentData{}
3939

40-
yamlFile, err := ioutil.ReadFile(filepath.Join("data", "data.yaml"))
40+
yamlFile, err := ReadFile(filepath.Join("data", "data.yaml"))
4141
if err != nil {
4242
fmt.Printf("Error reading YAML file: %s\n", err)
4343
return emptyData

src/modules/file.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,36 @@ import (
77
"os"
88
)
99

10+
var pwd string
11+
12+
func CurrentPath() string {
13+
if len(pwd) <= 0 {
14+
pwd, _ = os.Getwd()
15+
}
16+
return pwd
17+
}
18+
1019
func Exists(path string) bool {
1120
if _, err := os.Stat(path); !os.IsNotExist(err) {
1221
return true
1322
}
1423
return false
1524
}
1625

26+
func ReadFile(path string) ([]byte, error) {
27+
file, err := os.Open(path)
28+
if err != nil {
29+
return nil, err
30+
}
31+
defer file.Close()
32+
return io.ReadAll(file)
33+
}
34+
1735
func CopyFile(source string, dest string) (err error) {
1836
sourcefile, err := os.Open(source)
1937
if err != nil {
2038
return err
2139
}
22-
2340
defer sourcefile.Close()
2441

2542
destfile, err := os.Create(dest)
@@ -33,7 +50,7 @@ func CopyFile(source string, dest string) (err error) {
3350
if err == nil {
3451
sourceinfo, err := os.Stat(source)
3552
if err != nil {
36-
err = os.Chmod(dest, sourceinfo.Mode())
53+
_ = os.Chmod(dest, sourceinfo.Mode())
3754
}
3855

3956
}

src/modules/language.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,17 @@ package modules
22

33
import (
44
"fmt"
5-
"io/ioutil"
5+
"net/http"
66
"path/filepath"
77

88
"gopkg.in/yaml.v2"
99
)
1010

11+
func SetupLanguage(mux *http.ServeMux) {
12+
languagefs := http.FileServer(http.Dir(filepath.Join(CurrentPath(), "languages")))
13+
mux.Handle("/languages/", http.StripPrefix("/languages/", languagefs))
14+
}
15+
1116
type Language struct {
1217
Greeting LanguageGreeting `yaml:"greeting"`
1318
Weather LanguageWeather `yaml:"weather"`
@@ -36,7 +41,7 @@ type LanguageWeather struct {
3641
}
3742

3843
func LoadLanguage(language string) Language {
39-
yamlFile, err := ioutil.ReadFile(filepath.Join("languages", language+".yaml"))
44+
yamlFile, err := ReadFile(filepath.Join("languages", language+".yaml"))
4045
if err != nil {
4146
fmt.Printf("Error reading YAML file: %s\n", err)
4247
return LoadLanguage("en")

0 commit comments

Comments
 (0)