Initial release
This commit is contained in:
113
main.go
Normal file
113
main.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"TheAdversary/api"
|
||||
"TheAdversary/article"
|
||||
"TheAdversary/config"
|
||||
"TheAdversary/database"
|
||||
"TheAdversary/schema"
|
||||
"TheAdversary/server"
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func main() {
|
||||
r := mux.NewRouter()
|
||||
|
||||
r.HandleFunc("/api/recent", api.Recent).Methods(http.MethodGet)
|
||||
r.HandleFunc("/api/search", api.Search).Methods(http.MethodGet)
|
||||
|
||||
r.HandleFunc("/article/{article}", server.Article).Methods(http.MethodGet)
|
||||
|
||||
db, err := database.NewSqlite3Connection(config.DatabaseFile)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
database.SetGlobDB(db)
|
||||
|
||||
if err = checkArticles(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
if err := article.Notify(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}()
|
||||
|
||||
if err := http.ListenAndServe(fmt.Sprintf(":%s", config.ServerPort), r); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func checkArticles() error {
|
||||
var files []string
|
||||
err := filepath.Walk(config.ArticleRoot, func(path string, info fs.FileInfo, err error) error {
|
||||
if !info.IsDir() {
|
||||
files = append(files, filepath.Join(config.ArticleRoot, path))
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
articles, err := database.GetDB().GetArticles("", database.ArticleQueryOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
toAdd, toRemove := checkFiles(files, articles)
|
||||
|
||||
db := database.GetDB()
|
||||
|
||||
for _, addFile := range toAdd {
|
||||
a, err := article.LoadArticle(addFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = db.AddArticle(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(toRemove) > 0 {
|
||||
if err = db.DeleteArticlesByNames(toRemove...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func checkFiles(files []string, articles []*schema.Article) ([]string, []string) {
|
||||
toAdd := files
|
||||
for i, file := range files {
|
||||
articleName := article.ArticleName(file)
|
||||
for _, a := range articles {
|
||||
if articleName == a.Name {
|
||||
toAdd = append(toAdd[:i], toAdd[i+1:]...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var toRemove []string
|
||||
for _, a := range articles {
|
||||
var found bool
|
||||
for _, file := range files {
|
||||
if a.Name == article.ArticleName(file) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
toRemove = append(toRemove, a.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return toAdd, toRemove
|
||||
}
|
||||
Reference in New Issue
Block a user