123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670 |
- package main
- import (
- "bufio"
- "bytes"
- "embed"
- "fmt"
- "html/template"
- "io"
- "io/ioutil"
- "log"
- "math/rand"
- "net/http"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
- "apiote.xyz/p/go-dirty"
- "github.com/bytesparadise/libasciidoc"
- "github.com/bytesparadise/libasciidoc/pkg/configuration"
- "golang.org/x/text/language"
- )
- //go:embed static
- var staticFS embed.FS
- //go:embed programs
- var programsFS embed.FS
- //go:embed templates
- var templatesFS embed.FS
- type Nil struct {
- Adr string
- }
- type PGP struct {
- Key string
- Adr string
- }
- type Redirection struct {
- ID string
- URL string
- Adr string
- }
- type Version struct {
- Description string
- Module string
- Content template.HTML
- }
- type Programs struct {
- Programs map[string]Program
- Adr string
- }
- type Program struct {
- Name string
- Tldr string
- DefaultVersion string
- Source string
- Versions map[string]Version
- Tag string
- Module string
- Content template.HTML
- }
- type Holiday struct {
- Name string
- Month int
- Day int
- Rrule string
- Year int
- }
- func (h Holiday) Format() string {
- var result string
- if h.Year > 0 {
- result = strconv.FormatInt(int64(h.Year), 10)
- } else {
- result = "2001"
- }
- if h.Month < 10 {
- result += "0"
- }
- result += strconv.FormatInt(int64(h.Month), 10)
- if h.Day < 10 {
- result += "0"
- }
- result += strconv.FormatInt(int64(h.Day), 10)
- return result
- }
- func (h Holiday) UID() string {
- uid := strings.ReplaceAll(h.Name, " ", "")
- uid = strings.ReplaceAll(uid, "’", "")
- uid = strings.ReplaceAll(uid, ".", "")
- uid = strings.ToLower(uid)
- if h.Year != 0 {
- uid = uid + "_" + strconv.FormatInt(int64(h.Year), 10)
- }
- return uid + "@apiote.xyz"
- }
- func chooseLanguage(name, acceptLanguage string) string {
- languagesSet := map[language.Tag]struct{}{}
- entries, err := templatesFS.ReadDir("templates")
- for _, entry := range entries {
- if entry.IsDir() {
- continue
- }
- nameParts := strings.Split(entry.Name(), ".")
- if len(nameParts) == 2 {
- continue
- }
- l, err := language.Parse(nameParts[1])
- if err != nil {
- continue
- }
- languagesSet[l] = struct{}{}
- }
- if len(languagesSet) == 0 {
- return name
- }
- acceptLanguages, _, err := language.ParseAcceptLanguage(acceptLanguage)
- if err != nil {
- return name
- }
- languages := make([]language.Tag, len(languagesSet)+1)
- languages[0] = language.English
- i := 1
- for l := range languagesSet {
- languages[i] = l
- i++
- }
- matcher := language.NewMatcher(languages)
- tag, _, _ := matcher.Match(acceptLanguages...)
- lang, _ := tag.Base()
- return name + "." + lang.String()
- }
- func showHtml(w http.ResponseWriter, name string, data any, acceptLanguage string) {
- name = chooseLanguage(name, acceptLanguage)
- t, err := template.ParseFS(templatesFS, "templates/"+name+".html", "templates/aside.html", "templates/header.html", "templates/nav.html", "templates/head.html", "templates/head_program.html")
- if err != nil {
- log.Println(err)
- if os.IsNotExist(err) {
- renderStatus(w, http.StatusNotImplemented, acceptLanguage)
- return
- }
- w.WriteHeader(http.StatusInternalServerError)
- fmt.Fprint(w, "Error 500")
- return
- }
- err = t.Execute(w, data)
- if err != nil {
- log.Println(err)
- w.WriteHeader(http.StatusInternalServerError)
- fmt.Fprint(w, "Error 500")
- return
- }
- }
- func renderStatus(w http.ResponseWriter, status int, acceptLanguage string) {
- w.WriteHeader(status)
- showHtml(w, fmt.Sprint(status), nil, acceptLanguage)
- }
- func index(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- path := strings.Split(r.URL.Path[1:], "/")
- if path[0] == "" {
- showHtml(w, "index", nil, acceptLanguage)
- }
- if path[0] != "" {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- }
- }
- func donate(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- showHtml(w, "donate", nil, acceptLanguage)
- }
- func readPrograms() (map[string]Program, error) {
- m := map[string]Program{}
- programs := []Program{}
- file, err := programsFS.Open("programs/index.dirty")
- if err != nil {
- log.Println(err)
- return m, err
- }
- defer file.Close()
- err = dirty.LoadStruct(file, &programs)
- if err != nil {
- log.Println(err)
- log.Println(programs)
- }
- for _, program := range programs {
- m[program.Name] = program
- }
- return m, err
- }
- func programs(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- path := strings.Split(r.URL.Path[1:], "/")
- programs, err := readPrograms()
- if err != nil {
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- var (
- program Program
- version Version
- present bool
- )
- if path[1] == "" {
- showHtml(w, "programs", Programs{programs, "https://apiote.xyz/programs/"}, acceptLanguage)
- return
- } else if len(path) == 2 {
- name := path[1]
- program = programs[name]
- version, present = program.Versions[""]
- } else if len(path) == 3 {
- name := path[1]
- program = programs[name]
- version, present = program.Versions[path[2]]
- } else {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- return
- }
- if !present {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- return
- }
- file, err := programsFS.Open("programs/" + version.Description)
- if err != nil {
- if os.IsNotExist(err) {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- return
- } else {
- log.Println(err)
- }
- return
- }
- defer file.Close()
- content, err := io.ReadAll(file)
- if err != nil {
- log.Println(err)
- return
- }
- if len(path) > 2 {
- program.Tag = path[2]
- } else {
- program.Tag = ""
- }
- program.Module = version.Module
- reader := strings.NewReader(string(content))
- writer := bytes.NewBuffer([]byte{})
- config := configuration.NewConfiguration()
- libasciidoc.Convert(reader, writer, config)
- program.Content = template.HTML(writer.Bytes())
- showHtml(w, "program", program, acceptLanguage)
- }
- func blogEntries(w http.ResponseWriter, r *http.Request) {
- }
- func pgp(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- accept := r.Header["Accept"][0]
- path := strings.Split(r.URL.Path[1:], "/")
- if path[1] == "" {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- } else {
- file, err := staticFS.Open("static/" + path[1] + ".asc")
- defer file.Close()
- if err != nil && os.IsNotExist(err) {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- return
- } else if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- key, err := ioutil.ReadAll(file)
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- w.Header().Set("Vary", "Accept")
- if strings.Contains(accept, "text/html") {
- showHtml(w, "pgp", PGP{string(key), "https://apiote.xyz/pgp/me"}, acceptLanguage)
- } else {
- w.Header().Set("Content-Type", "application/pgp-key")
- fmt.Fprintf(w, "%s", key)
- }
- }
- }
- func easter(y int) []Holiday {
- a := y % 19
- b := y % 4
- c := y % 7
- p := y / 100
- q := (13 + (8 * p)) / 25
- m := (15 - q + p - (p / 4)) % 30
- n := (4 + p - (p / 4)) % 7
- d := (19*a + m) % 30
- e := (n + (2 * b) + (4 * c) + (6 * d)) % 7
- var easterDate time.Time
- if d == 29 && e == 6 {
- easterDate = time.Date(y, 4, 19, 0, 0, 0, 0, time.Local)
- } else if d == 28 && e == 6 {
- easterDate = time.Date(y, 4, 18, 0, 0, 0, 0, time.Local)
- } else {
- easterDate = time.Date(y, 3, 22, 0, 0, 0, 0, time.Local).AddDate(0, 0, d+e)
- }
- holidays := []Holiday{}
- holidays = append(holidays, Holiday{
- Name: "Easter",
- Month: int(easterDate.Month()),
- Day: easterDate.Day(),
- Year: y,
- })
- h := easterDate.AddDate(0, 0, -52)
- holidays = append(holidays, Holiday{
- Name: "Fat Thursday",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, -47)
- holidays = append(holidays, Holiday{
- Name: "Shrove Tuesday",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, -46)
- holidays = append(holidays, Holiday{
- Name: "Ash Wednesday",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, -7)
- holidays = append(holidays, Holiday{
- Name: "Palm Sunday",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, -3)
- holidays = append(holidays, Holiday{
- Name: "Maundy Thursday",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, -2)
- holidays = append(holidays, Holiday{
- Name: "Good Friday",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, -1)
- holidays = append(holidays, Holiday{
- Name: "Easter Eve",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, 1)
- holidays = append(holidays, Holiday{
- Name: "Easter Monday",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, 49)
- holidays = append(holidays, Holiday{
- Name: "Pentecost",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- h = easterDate.AddDate(0, 0, 60)
- holidays = append(holidays, Holiday{
- Name: "Corpus Christi",
- Month: int(h.Month()),
- Day: h.Day(),
- Year: y,
- })
- return holidays
- }
- func calendar(dataDir string) func(w http.ResponseWriter, r *http.Request) {
- return func(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- file, err := os.Open(filepath.Join(dataDir, "holidays.dirty"))
- if err != nil {
- if os.IsNotExist(err) {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- return
- } else {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- }
- defer file.Close()
- holidays := []Holiday{}
- err = dirty.LoadStruct(file, &holidays)
- if err != nil {
- log.Println(err)
- log.Println(holidays)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- t, err := template.ParseFS(templatesFS, "templates/calendar.ics")
- if err != nil {
- log.Println(err)
- if os.IsNotExist(err) {
- renderStatus(w, http.StatusNotImplemented, acceptLanguage)
- return
- }
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- thisYear := time.Now().Year()
- for i := 0; i < 10; i++ {
- holidays = append(holidays, easter(thisYear+i)...)
- }
- w.Header().Set("Content-Type", "text/calendar")
- err = t.Execute(w, holidays)
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- }
- }
- func shortRedirect(dataDir, stateDir string) func(w http.ResponseWriter, r *http.Request) {
- return func(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- path := strings.Split(r.URL.Path[1:], "/")
- if len(path) == 2 && path[1] == "" {
- if r.Method == "" || r.Method == "GET" {
- showHtml(w, "s", Nil{"https://apiote.xyz/s/"}, acceptLanguage)
- } else if r.Method == "POST" {
- r.ParseForm()
- id := r.PostForm.Get("id")
- url := r.PostForm.Get("url")
- password := r.PostForm.Get("password")
- if id == "" {
- var letters = []rune("3478ABCDEFHJKMNRTWXY")
- b := make([]rune, 6)
- for i := range b {
- b[i] = letters[rand.Intn(len(letters))]
- }
- id = string(b)
- } else {
- id = strings.ToUpper(id)
- }
- if url == "" {
- renderStatus(w, http.StatusBadRequest, acceptLanguage)
- return
- }
- hash, err := ioutil.ReadFile(filepath.Join(stateDir, "password"))
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- passMatch, err := ComparePasswordAndHash(password, string(hash))
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- if !passMatch {
- renderStatus(w, http.StatusForbidden, acceptLanguage)
- return
- }
- file, err := os.OpenFile(filepath.Join(stateDir, "s.toml"), os.O_RDONLY|os.O_CREATE, 0600)
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- defer file.Close()
- shorts := map[string]string{}
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := strings.Split(scanner.Text(), " = ")
- shorts[line[0]] = line[1]
- }
- if err := scanner.Err(); err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- file.Close()
- if _, ok := shorts[id]; ok {
- renderStatus(w, http.StatusConflict, acceptLanguage)
- return
- }
- shorts[id] = url
- file, err = os.OpenFile(filepath.Join(stateDir, "s.toml"), os.O_WRONLY|os.O_TRUNC, 0600)
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- defer file.Close()
- for shortID, shortURL := range shorts {
- _, err = file.WriteString(shortID + " = " + shortURL + "\n")
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- }
- w.Header().Add("X-Redirection", "https://apiote.xyz/s/"+id)
- w.WriteHeader(http.StatusCreated)
- showHtml(w, "s201", Redirection{id, url, "https://apiote.xyz/s/" + id}, acceptLanguage)
- }
- } else if len(path) != 2 {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- } else {
- id := strings.ToUpper(path[1])
- file, err := os.Open(filepath.Join(stateDir, "s.toml"))
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := strings.Split(scanner.Text(), " = ")
- if len(line) < 2 {
- continue
- }
- if line[0] == id {
- http.Redirect(w, r, line[1], http.StatusMovedPermanently)
- return
- }
- }
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- }
- }
- }
- func shortShow(stateDir string) func(w http.ResponseWriter, r *http.Request) {
- return func(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- path := strings.Split(r.URL.Path[1:], "/")
- if len(path) == 2 && path[1] != "" {
- id := strings.ToUpper(path[1])
- file, err := os.Open(filepath.Join(stateDir, "s.toml"))
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := strings.Split(scanner.Text(), " = ")
- if len(line) < 2 {
- continue
- }
- if line[0] == id {
- showHtml(w, "short", Redirection{line[0], line[1], "https://apiote.xyz/short/" + line[0]}, acceptLanguage)
- return
- }
- }
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- } else {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- }
- }
- }
- func wkd(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- path := strings.Split(r.URL.Path[1:], "/")
- if path[3] == "" {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- } else {
- file, err := staticFS.Open("static/" + path[3] + ".pgp")
- defer file.Close()
- if err != nil && os.IsNotExist(err) {
- renderStatus(w, http.StatusNotFound, acceptLanguage)
- return
- } else if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- return
- }
- w.Header().Set("Content-Type", "application/pgp-key")
- w.Header().Set("Access-Control-Allow-Origin", "*")
- _, err = io.Copy(w, file)
- if err != nil {
- log.Println(err)
- renderStatus(w, http.StatusInternalServerError, acceptLanguage)
- }
- }
- }
- func dogtag(w http.ResponseWriter, r *http.Request) {
- acceptLanguage := r.Header.Get("Accept-Language")
- showHtml(w, "dogtag", Nil{"https://apiote.xyz/tag"}, acceptLanguage)
- }
- func route(dataDir, stateDir string) {
- http.HandleFunc("/", index)
- http.Handle("/static/", http.FileServer(http.FS(staticFS)))
- http.HandleFunc("/b/", blogEntries)
- http.HandleFunc("/blog/", blogEntries)
- http.HandleFunc("/p/", programs)
- http.HandleFunc("/programs/", programs)
- http.HandleFunc("/donate", donate)
- http.HandleFunc("/pgp/", pgp)
- http.HandleFunc("/calendar", calendar(dataDir))
- http.HandleFunc("/tag", dogtag)
- http.HandleFunc("/s/", shortRedirect(dataDir, stateDir))
- http.HandleFunc("/short/", shortShow(stateDir))
- http.HandleFunc("/.well-known/openpgpkey/hu/", wkd)
- e := http.ListenAndServe("127.0.0.1:8080", nil)
- if e != nil {
- log.Println(e)
- }
- }
|