~nromdotcom/gemif

ref: 4cd93f062e2ec8e1bdbda9794696807c3f66074a gemif/pkg/web/routes.go -rw-r--r-- 1.9 KiB
4cd93f06Norm MacLennan Remove the last of the pseudoPOSTs 1 year, 1 month ago
                                                                                
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package web

import (
	"fmt"
	"gemif/pkg/gamemanager"
	"io/ioutil"
	"net/url"
	"path"
	"path/filepath"

	"github.com/markbates/pkger"
	"github.com/pitr/gig"
)

func handleStatic(c gig.Context) error {
	p, err := url.PathUnescape(c.Param("*"))
	if err != nil {
		return fmt.Errorf("unable to parse url: %w", err)
	}

	if p == "/" {
		p = "/index.gmi"
	}

	name := filepath.Join("/static/docs", path.Clean("/"+p)) // "/"+ for security

	f, fileErr := pkger.Open(name)
	if fileErr != nil {
		return fmt.Errorf("couldn't open file: %w", fileErr)
	}

	sl, readErr := ioutil.ReadAll(f)
	if readErr != nil {
		return fmt.Errorf("couldn't read file: %w", readErr)
	}

	return c.Gemini(string(sl))
}

func handleHome(gm *gamemanager.GameManager) func(gig.Context) error {
	return func(c gig.Context) error {
		stories := gm.GetStories()

		startStates, startErr := gm.ConstructStartingState(stories)
		if startErr != nil {
			return fmt.Errorf("couldn't load game: %w", startErr)
		}

		return c.Render("gemif:/static/templates/index.gmi.tmpl", map[string]interface{}{
			"Stories": startStates,
			"Banner":  getRandomBanner(),
		})
	}
}

func handleGame(gm *gamemanager.GameManager) func(gig.Context) error {
	return func(c gig.Context) error {
		gameState, gameErr := gm.DeserializeState(c.Param("statetoken"))
		if gameErr != nil {
			return fmt.Errorf("could not deserialized game state: %w", gameErr)
		}

		currentRoom, roomErr := gm.GetRoomByID(gameState.StoryID, gameState.CurrentRoom)
		if roomErr != nil {
			return fmt.Errorf("could not find room: %w", roomErr)
		}

		speculativeStates, speculationErr := gm.ConstructSpeculativeStates(gameState, currentRoom)
		if speculationErr != nil {
			return fmt.Errorf("unable to render exits: %w", speculationErr)
		}

		return c.Render("gemif:/static/templates/room.gmi.tmpl", map[string]interface{}{
			"RoomName":    currentRoom.Name,
			"Description": currentRoom.Description,
			"Actions":     speculativeStates,
		})
	}
}