99 lines
2.4 KiB
Go
99 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"gitea.kleinsense.nl/DariusKlein/kleinTodo/client/todo/httpClient"
|
|
"gitea.kleinsense.nl/DariusKlein/kleinTodo/common"
|
|
"github.com/urfave/cli/v3"
|
|
)
|
|
|
|
// Sync Command
|
|
func Sync() *cli.Command {
|
|
return &cli.Command{
|
|
Name: "sync",
|
|
Usage: "sync with kleinTodo server",
|
|
Action: syncAction,
|
|
}
|
|
}
|
|
|
|
// syncAction logic for Template
|
|
func syncAction(context context.Context, c *cli.Command) error {
|
|
store, err := common.GetTodoDataStore()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
serverTodos := store.GetTodoList(cfg.Server.Credentials.Username)
|
|
|
|
var todos []common.Todo
|
|
|
|
for _, t := range serverTodos {
|
|
todos = append(todos, t)
|
|
}
|
|
|
|
payload, err := json.Marshal(common.TodoList{Todos: todos})
|
|
if err != nil {
|
|
return fmt.Errorf("error marshaling credentials: %w", err)
|
|
}
|
|
req, err := http.NewRequest("GET", cfg.Server.Url+"/sync", bytes.NewBuffer(payload))
|
|
if err != nil {
|
|
return fmt.Errorf("error creating request: %w", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := httpClient.GetHttpClient(cfg.Server.Token).Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("error sending request: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read response body: %w", err)
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("request failed with status %d: %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
var response common.SyncResponse
|
|
|
|
if err := json.Unmarshal(body, &response); err != nil {
|
|
return fmt.Errorf("failed to decode successful response: %w\n%s", err, string(body))
|
|
}
|
|
|
|
var index = 1
|
|
|
|
if len(response.MisMatchingTodos) > 0 {
|
|
for _, todo := range response.MisMatchingTodos {
|
|
fmt.Println("Mismatch between server and client")
|
|
fmt.Print("local:")
|
|
todo.LocalTodo.PrintIndexed(1)
|
|
fmt.Print("server:")
|
|
todo.ServerTodo.PrintIndexed(2)
|
|
if common.AskUserBool("Do you wish to override you local version with the server version?") {
|
|
response.SyncedTodos = append(response.SyncedTodos, todo.ServerTodo)
|
|
} else {
|
|
response.SyncedTodos = append(response.SyncedTodos, todo.LocalTodo)
|
|
}
|
|
}
|
|
}
|
|
|
|
fmt.Println("Successfully synced with the server:")
|
|
for _, todo := range response.SyncedTodos {
|
|
err := todo.Store(store, cfg.Server.Credentials.Username)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
todo.PrintIndexed(index)
|
|
index++
|
|
}
|
|
|
|
return nil
|
|
}
|