knowyt/server/src/quote/quote.go

88 lines
1.5 KiB
Go
Raw Normal View History

package quote
import (
"encoding/json"
"fmt"
"os"
"path"
"strings"
"time"
)
func NewQuoteFromFile(fileName string) (*Quote, error) {
jsonBytes, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
var quJson QuoteJson
if err := json.Unmarshal(jsonBytes, &quJson); err != nil {
return nil, fmt.Errorf("%s: %v", fileName, err)
} else {
_, fileNameShort := path.Split(fileName)
id := strings.TrimSuffix(fileNameShort, ".json")
qu := &Quote{
2021-09-06 21:18:34 +00:00
id: id,
sourceId: quJson.SourceId,
quote: quJson.Quote,
created: quJson.Created,
2021-09-17 21:40:15 +00:00
isPlayed: false,
}
return qu, nil
}
}
2021-10-16 18:14:58 +00:00
func NewQuote(id, sourceId, quoteText string) *Quote {
return &Quote{
id: id,
sourceId: sourceId,
quote: quoteText,
created: time.Now().Unix(),
2021-10-16 18:14:58 +00:00
isPlayed: false,
}
}
2021-10-16 14:57:28 +00:00
func (qu *Quote) Save(fileName string) error {
quJson := QuoteJson{
Quote: qu.quote,
SourceId: qu.sourceId,
Created: qu.created,
2021-10-16 14:57:28 +00:00
}
quoteJson, err := json.MarshalIndent(quJson, "", "\t")
if err != nil {
return err
}
return os.WriteFile(fileName, quoteJson, 0666)
2021-10-16 14:57:28 +00:00
}
func (qu *Quote) GetId() string {
return qu.id
}
2021-09-06 21:18:34 +00:00
func (qu *Quote) GetSourceId() string {
return qu.sourceId
}
func (qu *Quote) GetQuote() string {
return qu.quote
}
2021-09-17 21:40:15 +00:00
2021-10-16 14:57:28 +00:00
func (qu *Quote) SetQuote(quote string) {
qu.quote = quote
}
2021-09-17 21:40:15 +00:00
func (qu *Quote) IsPlayed() bool {
return qu.isPlayed
}
func (qu *Quote) SetIsPlayed() {
qu.isPlayed = true
}
func (qu *Quote) GetCreated() int64 {
return qu.created
}