summaryrefslogtreecommitdiff
path: root/internal/client/tui/submit.go
blob: cc1ff0d7621d6d91efe775eea0f4ea96bdf979ae (plain)
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
package tui

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"codeberg.org/snonux/gos/internal/config/client"
	config "codeberg.org/snonux/gos/internal/config/client"
	"codeberg.org/snonux/gos/internal/easyhttp"
	"codeberg.org/snonux/gos/internal/types"
	tea "github.com/charmbracelet/bubbletea"
)

func submitActionCmd(ctx context.Context, conf config.ClientConfig) tea.Cmd {
	composeFile := fmt.Sprintf("%s/%s", conf.DataDir, conf.ComposeFile)
	log.Println("Submitting", composeFile)

	return submitEntryCmd(ctx, conf, composeFile, func() error {
		// This is the cb to call when the entry was submitted succesfully
		return nil
	})
}

func submitEntryCmd(ctx context.Context, conf client.ClientConfig, composeFile string, cb func() error) tea.Cmd {
	return finishedCmd(cb, submitEntry(ctx, conf, composeFile))
}

func submitEntry(ctx context.Context, conf client.ClientConfig, composeFile string) error {
	if len(conf.Servers) == 0 {
		return errors.New("no server configured")
	}

	entry, err := types.NewEntryFromTextFile(composeFile)
	if err != nil {
		return err
	}

	if err := easyhttp.PostData(ctx, "submit", conf.APIKey, &entry, conf.Servers...); err != nil {
		return err
	}

	timestamp := time.Now().Format("20060102-150405")
	submittedFile := fmt.Sprintf("%s/submitted-%s.txt", conf.DataDir, timestamp)

	log.Println("Renaming", composeFile, "to", submittedFile)
	return os.Rename(composeFile, submittedFile)
}