Skip to content

Commit e2f1148

Browse files
committed
Implement session export and session import commands
1 parent a668495 commit e2f1148

File tree

5 files changed

+181
-11
lines changed

5 files changed

+181
-11
lines changed

cmd/root.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ func abortf(format string, err error) {
4545
}
4646

4747
if _, ok := err.(*exec.ExitError); !ok && !errors.Is(err, cli.ErrCanceled) {
48-
cli.Error(err.Error())
48+
cli.Error(format, err)
4949
}
5050
os.Exit(1)
5151
}

cmd/session_export.go

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
package cmd
2+
3+
import (
4+
"bytes"
5+
"encoding/json"
6+
"net/http"
7+
8+
"github.com/Bananenpro/cli"
9+
"github.com/code-game-project/go-utils/sessions"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
// sessionExportCmd represents the session export command
14+
var sessionExportCmd = &cobra.Command{
15+
Use: "export",
16+
Short: "Export a session to share.code-game.org.",
17+
Args: cobra.RangeArgs(0, 2),
18+
Run: func(cmd *cobra.Command, args []string) {
19+
var gameURL string
20+
var username string
21+
if len(args) > 0 {
22+
gameURL = args[0]
23+
if len(args) > 1 {
24+
username = args[1]
25+
}
26+
}
27+
28+
if gameURL == "" {
29+
urls, err := sessions.ListGames()
30+
if err != nil {
31+
gameURL, err = cli.Input("Game URL:")
32+
} else {
33+
var index int
34+
index, err = cli.Select("Game URL:", urls)
35+
gameURL = urls[index]
36+
}
37+
if err != nil {
38+
return
39+
}
40+
}
41+
42+
if username == "" {
43+
usernames, err := sessions.ListUsernames(gameURL)
44+
if err != nil {
45+
username, err = cli.Input("Username:")
46+
} else {
47+
var index int
48+
index, err = cli.Select("Username:", usernames)
49+
username = usernames[index]
50+
}
51+
if err != nil {
52+
return
53+
}
54+
}
55+
56+
session, err := sessions.LoadSession(gameURL, username)
57+
abortf("Failed to load session: %s", err)
58+
59+
type reqSession struct {
60+
GameId string `json:"game_id"`
61+
PlayerId string `json:"player_id"`
62+
PlayerSecret string `json:"player_secret"`
63+
}
64+
65+
type request struct {
66+
GameURL string `json:"game_url"`
67+
Username string `json:"username"`
68+
Session reqSession `json:"session"`
69+
}
70+
71+
data := request{
72+
GameURL: gameURL,
73+
Username: username,
74+
Session: reqSession{
75+
GameId: session.GameId,
76+
PlayerId: session.PlayerId,
77+
PlayerSecret: session.PlayerSecret,
78+
},
79+
}
80+
81+
jsonData, err := json.Marshal(data)
82+
abort(err)
83+
84+
resp, err := http.Post("https://share.code-game.org/session", "application/json", bytes.NewBuffer(jsonData))
85+
if err != nil {
86+
cli.Error("Failed to upload session: %s", err)
87+
return
88+
}
89+
if resp.StatusCode != http.StatusCreated {
90+
type response struct {
91+
Error string `json:"error"`
92+
}
93+
var res response
94+
err = json.NewDecoder(resp.Body).Decode(&res)
95+
cli.Error(res.Error)
96+
return
97+
}
98+
99+
type response struct {
100+
Id string `json:"id"`
101+
}
102+
var res response
103+
err = json.NewDecoder(resp.Body).Decode(&res)
104+
abortf("Failed to decode session data from server: %s", err)
105+
cli.Success("Success! You can import your session with the following command:")
106+
cli.PrintColor(cli.Cyan, "codegame session import %s", res.Id)
107+
},
108+
}
109+
110+
func init() {
111+
sessionCmd.AddCommand(sessionExportCmd)
112+
}

cmd/session_import.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package cmd
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"net/http"
7+
8+
"github.com/Bananenpro/cli"
9+
"github.com/code-game-project/go-utils/sessions"
10+
"github.com/spf13/cobra"
11+
)
12+
13+
// sessionImportCmd represents the session import command
14+
var sessionImportCmd = &cobra.Command{
15+
Use: "import",
16+
Short: "Import a session from share.code-game.org.",
17+
Args: cobra.RangeArgs(0, 1),
18+
Run: func(cmd *cobra.Command, args []string) {
19+
var id string
20+
var err error
21+
if len(args) > 0 {
22+
id = args[0]
23+
} else {
24+
id, err = cli.Input("ID:")
25+
if err != nil {
26+
return
27+
}
28+
}
29+
30+
resp, err := http.Get(fmt.Sprintf("https://share.code-game.org/%s?type=session", id))
31+
abortf("Failed to contact share.code-game.org: %s", err)
32+
33+
type resSession struct {
34+
GameId string `json:"game_id"`
35+
PlayerId string `json:"player_id"`
36+
PlayerSecret string `json:"player_secret"`
37+
}
38+
39+
type response struct {
40+
Error string `json:"error"`
41+
GameURL string `json:"game_url"`
42+
Username string `json:"username"`
43+
Session resSession `json:"session"`
44+
}
45+
46+
var data response
47+
err = json.NewDecoder(resp.Body).Decode(&data)
48+
if err != nil {
49+
abortf("Failed to decode server response: %s", err)
50+
}
51+
if data.Error != "" {
52+
abort(fmt.Errorf(data.Error))
53+
}
54+
55+
session := sessions.NewSession(data.GameURL, data.Username, data.Session.GameId, data.Session.PlayerId, data.Session.PlayerSecret)
56+
err = session.Save()
57+
abortf("Failed to save session: %s", err)
58+
59+
cli.Success("Successfully imported %s@%s!", session.Username, session.GameURL)
60+
},
61+
}
62+
63+
func init() {
64+
sessionCmd.AddCommand(sessionImportCmd)
65+
}

cmd/session_list.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,7 @@ var sessionListCmd = &cobra.Command{
1212
Short: "List all available sessions.",
1313
Run: func(cmd *cobra.Command, args []string) {
1414
sessionList, err := sessions.ListSessions()
15-
if err != nil {
16-
cli.Error("Failed to retrieve session list: %s", err)
17-
return
18-
}
15+
abortf("Failed to retrieve session list: %s", err)
1916
for game, usernames := range sessionList {
2017
cli.PrintColor(cli.CyanBold, game)
2118
for _, u := range usernames {

cmd/session_remove.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ var sessionRemoveCmd = &cobra.Command{
1616
Run: func(cmd *cobra.Command, args []string) {
1717
var gameURL string
1818
var username string
19-
var err error
2019
if len(args) > 0 {
2120
gameURL = args[0]
2221
if len(args) > 1 {
@@ -52,7 +51,7 @@ var sessionRemoveCmd = &cobra.Command{
5251
}
5352
}
5453

55-
yes, err := cli.YesNo(fmt.Sprintf("Are you sure you want to remove '%s/%s'?", gameURL, username), false)
54+
yes, err := cli.YesNo(fmt.Sprintf("Are you sure you want to remove %s@%s?", username, gameURL), false)
5655
if !yes {
5756
if err == nil {
5857
cli.Error("Canceled.")
@@ -64,10 +63,7 @@ var sessionRemoveCmd = &cobra.Command{
6463
GameURL: gameURL,
6564
Username: username,
6665
}.Remove()
67-
if err != nil {
68-
cli.Error("Failed to remove session: %s", err)
69-
return
70-
}
66+
abortf("Failed to remove session: %s", err)
7167
cli.Success("Successfully removed session.")
7268
},
7369
}

0 commit comments

Comments
 (0)