git.alexw.nyc home about git garden
    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
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
package main

import (
	"bytes"
	"context"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path"
	"strings"
	"text/template"
	"time"

	gmi "git.sr.ht/~adnano/go-gemini"
	"git.sr.ht/~adnano/go-gemini/certificate"
)

var gt *template.Template

func generateGemfeedPage(user string) string {
	feed := generateFeedFromUser(user)
	data := struct {
		Host        string
		Title       string
		FeedEntries []FeedEntry
	}{c.Host, feed.Title, feed.Entries}
	var buff bytes.Buffer
	gt.ExecuteTemplate(&buff, "gemfeed.gmi", data)
	return buff.String()
}

func generateFolderPage(fullpath string) string {
	files, _ := ioutil.ReadDir(fullpath)
	var renderedFiles = []File{}
	for _, file := range files {
		// Very awkward
		res := fileFromPath(path.Join(fullpath, file.Name()))
		renderedFiles = append(renderedFiles, res)
	}
	var buff bytes.Buffer
	data := struct {
		Host   string
		Folder string
		Files  []File
	}{c.Host, getLocalPath(fullpath), renderedFiles}
	err := gt.ExecuteTemplate(&buff, "folder.gmi", data)
	if err != nil {
		log.Println(err)
		return ""
	}
	return buff.String()
}

func gmiIndex(w gmi.ResponseWriter, r *gmi.Request) {
	t, err := template.ParseFiles("templates/index.gmi")
	if err != nil {
		log.Fatal(err)
	}
	files, err := getUpdatedFiles(false, "")
	users, err := getActiveUserNames(false)
	if err != nil {
		log.Println(err)
		w.WriteHeader(gmi.StatusTemporaryFailure, "Server Error")
	}
	data := struct {
		Host      string
		SiteTitle string
		Files     []*File
		Users     []string
	}{
		Host:      c.Host,
		SiteTitle: c.SiteTitle,
		Files:     files,
		Users:     users,
	}
	t.Execute(w, data)
}

func gmiPage(_ context.Context, w gmi.ResponseWriter, r *gmi.Request) {
	// redundant
	hostname := strings.SplitN(c.Host, ":", 2)[0]
	if r.URL.Host == hostname {
		gmiIndex(w, r)
		return
	}
	var userName string
	custom := domains[r.URL.Host]
	if custom != "" {
		userName = custom
	} else {
		userName = cleanPath(strings.Split(r.URL.Host, ".")[0])[1:] // clean probably unnecessary
	}
	fileName := cleanPath(r.URL.Path)
	if strings.HasPrefix(fileName, "/"+HiddenFolder) {
		w.WriteHeader(gmi.StatusNotFound, "Not found")
		return
	}
	fullPath := path.Join(c.FilesDirectory, userName, fileName)
	if fileName == "/gemlog" { // temp hack
		_, err := os.Stat(path.Join(fullPath, "index.gmi"))
		if err != nil {
			w.WriteHeader(gmi.StatusSuccess, "text/gemini")
			io.Copy(w, strings.NewReader(generateGemfeedPage(userName)))
			return
		}
	} else if fileName == "/gemlog/atom.xml" {
		_, err := os.Stat(fullPath)
		if err != nil {
			w.WriteHeader(gmi.StatusSuccess, "application/atom+xml")
			feed := generateFeedFromUser(userName)
			atomString := feed.toAtomFeed()
			io.Copy(w, strings.NewReader(atomString))
			return
		}
	}
	if fileName == "" { // mess
		fileName = "/"
	}

	gmi.ServeFile(w, os.DirFS(path.Join(c.FilesDirectory, userName)), fileName)
}

var certificates = certificate.Store{}

func runGeminiServer() {
	log.Println("Starting gemini server")
	var err error
	gt = template.New("main").Funcs(template.FuncMap{
		"urlencode": func(s string) string {
			// Only need to escape spaces to make gemini links not break
			return strings.Replace(s, " ", "%20", -1)
		},
	})
	gt, err = gt.ParseGlob(path.Join(c.TemplatesDirectory, "*.gmi"))
	if err != nil {
		log.Fatal(err)
	}
	var server gmi.Server
	server.ReadTimeout = 1 * time.Minute
	server.WriteTimeout = 2 * time.Minute

	hostname := strings.SplitN(c.Host, ":", 2)[0]
	// is this necc?
	err = certificates.Load(c.GeminiCertStore)
	if err != nil {
		log.Fatal(err)
	}
	certificates.Register("*." + hostname)
	certificates.Register(hostname)
	for k, _ := range domains {
		certificates.Register(k)
	}
	server.GetCertificate = certificates.Get

	var mux gmi.Mux

	mux.HandleFunc("/", gmiPage)
	server.Handler = gmi.LoggingMiddleware(&mux)

	err = server.ListenAndServe(context.Background())
	if err != nil {
		log.Fatal(err)
	}
}