app.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package main
import (
"context"
"github.com/adrg/xdg"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type AppConfig struct {
Title string
}
type App struct {
ctx context.Context
Config AppConfig
DB *gorm.DB
UserContact Contact
}
func NewApp(config AppConfig) *App {
app := &App{Config: config}
db, err := gorm.Open(sqlite.Open(app.GetDataFile()), &gorm.Config{})
if err != nil {
panic(err)
}
app.DB = db.Session(&gorm.Session{FullSaveAssociations: true})
app.migrate()
return app
}
func (app *App) startup(ctx context.Context) {
app.ctx = ctx
app.EstablishMailConnections()
}
func (app *App) shutdown(ctx context.Context) {
CloseMailConnections()
return
}
func (app *App) migrate() {
app.DB.AutoMigrate(&Contact{})
app.DB.AutoMigrate(&EmailAddress{})
app.DB.AutoMigrate(&PhoneNumber{})
app.DB.AutoMigrate(&URL{})
app.DB.AutoMigrate(&StreetAddress{})
app.DB.AutoMigrate(&Date{})
app.DB.AutoMigrate(&OtherField{})
app.DB.Preload(clause.Associations).
FirstOrCreate(
&app.UserContact,
Contact{Model: gorm.Model{ID: 1}},
)
app.DB.AutoMigrate(&MailAccountConnection{})
}
func (app *App) GetTitle() string {
return app.Config.Title
}
func (app *App) GetDataFile() string {
if file, err := xdg.DataFile(app.GetTitle() + "/data.db"); err != nil {
panic(err)
} else {
return file
}
}
func (app *App) GetMailPasswordKeyringService() string {
title := app.GetTitle()
return title + "-mail-password"
}
|