superhighway84/tui/helpers.go

95 lines
2.0 KiB
Go
Raw Normal View History

2021-12-26 03:02:56 +00:00
package tui
import (
"errors"
"fmt"
2021-12-26 03:02:56 +00:00
"io/ioutil"
"log"
"os"
"os/exec"
"strings"
"time"
2021-12-26 03:02:56 +00:00
"github.com/mrusme/superhighway84/models"
)
func MillisecondsToDate(ms int64) (string) {
return time.Unix(0, ms * int64(time.Millisecond)).Format("Mon Jan _2 15:04:05 2006")
}
2021-12-26 18:48:40 +00:00
func (t *TUI) OpenArticle(article *models.Article) (models.Article, error) {
2021-12-26 03:02:56 +00:00
tmpFile, err := ioutil.TempFile(os.TempDir(), "article-*.txt")
if err != nil {
return *article, err
}
defer os.Remove(tmpFile.Name())
2021-12-26 18:48:40 +00:00
tmpContent := []byte(fmt.Sprintf(
"Subject: %s\nNewsgroup: %s\n= = = = = =\n%s",
article.Subject, article.Newsgroup, article.Body))
2021-12-26 03:02:56 +00:00
if _, err = tmpFile.Write(tmpContent); err != nil {
return *article, err
}
if err := tmpFile.Close(); err != nil {
return *article, err
}
2021-12-26 18:48:40 +00:00
wasSuspended := t.App.Suspend(func() {
2021-12-26 03:02:56 +00:00
cmd := exec.Command(os.Getenv("EDITOR"), tmpFile.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err := cmd.Run()
if err != nil {
log.Println(err)
}
return
})
if wasSuspended == false {
return *article, err
}
tmpContent, err = os.ReadFile(tmpFile.Name())
if err != nil {
return *article, err
}
2021-12-26 18:48:40 +00:00
content := strings.SplitAfterN(string(tmpContent), "\n= = = = = =\n", 2)
if len(content) != 2 {
return *article, errors.New("Document malformatted")
}
2021-12-26 18:48:40 +00:00
newArticle := *article
headerPart := strings.TrimSpace(content[0])
2021-12-26 18:48:40 +00:00
headers := strings.Split(headerPart, "\n")
for _, header := range headers {
splitHeader := strings.SplitAfterN(header, ":", 2)
if len(splitHeader) < 2 {
continue
}
headerName := strings.ToLower(strings.TrimSpace(splitHeader[0]))
headerValue := strings.TrimSpace(splitHeader[1])
switch(headerName) {
case "subject:":
newArticle.Subject = headerValue
case "newsgroup:":
newArticle.Newsgroup = headerValue
}
}
2021-12-27 00:24:16 +00:00
newArticle.Body = strings.TrimSpace(content[1])
if valid, err := newArticle.IsValid(); valid == false {
return *article, err
}
2021-12-26 03:02:56 +00:00
return newArticle, nil
}