probo-app/app.go
2023-09-05 20:38:18 +02:00

110 lines
2.4 KiB
Go

package main
import (
"context"
"git.andreafazzi.eu/andrea/probo/client"
"git.andreafazzi.eu/andrea/probo/models"
"git.andreafazzi.eu/andrea/probo/store/file"
"github.com/fsnotify/fsnotify"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct
type App struct {
ctx context.Context
store *file.FileProboCollectorStore
watcher *fsnotify.Watcher
}
type Quiz struct {
Text string
}
// NewApp creates a new App application struct
func NewApp() *App {
store, err := file.NewFileProboCollectorStore("./data/quizzes")
if err != nil {
panic(err)
}
return &App{
store: store,
}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
}
func (a *App) onShutdown(ctx context.Context) {
a.watcher.Close()
}
func (a *App) onDomReady(ctx context.Context) {
var err error
// Create new watcher.
a.watcher, err = fsnotify.NewWatcher()
if err != nil {
runtime.LogFatal(ctx, err.Error())
}
// Start listening for events.
go func() {
runtime.LogDebug(ctx, "Filesystem watcher initialized...")
for {
select {
case event, ok := <-a.watcher.Events:
if !ok {
return
}
runtime.LogDebugf(ctx, "Event: %v", event)
if event.Has(fsnotify.Write) || event.Has(fsnotify.Remove) {
runtime.LogDebugf(ctx, "Modified or removed file: %v", event.Name)
runtime.EventsEmit(ctx, "fsChangeEvent")
}
case err, ok := <-a.watcher.Errors:
if !ok {
return
}
runtime.LogDebugf(ctx, "Error: %v", err)
}
}
}()
// Add a path.
runtime.LogDebugf(ctx, "Begin watching path %v", a.store.Dir)
err = a.watcher.Add(a.store.Dir)
if err != nil {
runtime.LogFatalf(ctx, "Error: %v", err)
}
}
func (a *App) ReadAllQuizzes() ([]*models.Quiz, error) {
return a.store.ReadAllQuizzes()
}
func (a *App) MarkdownFromQuiz(quiz *models.Quiz) (string, error) {
return file.MarkdownFromQuiz(quiz)
}
func (a *App) QuizFromMarkdown(markdown string) (*client.Quiz, error) {
return file.QuizFromMarkdown(markdown)
}
func (a *App) UpdateQuiz(quiz *client.Quiz, id string) (*models.Quiz, error) {
return a.store.UpdateQuiz(&client.CreateUpdateQuizRequest{Quiz: quiz}, id)
}
func (a *App) CreateQuiz(quiz *client.Quiz) (*models.Quiz, error) {
return a.store.CreateQuiz(&client.CreateUpdateQuizRequest{Quiz: quiz})
}
func (a *App) DeleteQuiz(id string) (*models.Quiz, error) {
return a.store.DeleteQuiz(&client.DeleteQuizRequest{ID: id})
}