router.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "embed"
  6. "fmt"
  7. "html/template"
  8. "io"
  9. "io/ioutil"
  10. "log"
  11. "math/rand"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "time"
  18. "apiote.xyz/p/go-dirty"
  19. "github.com/bytesparadise/libasciidoc"
  20. "github.com/bytesparadise/libasciidoc/pkg/configuration"
  21. "golang.org/x/text/language"
  22. )
  23. //go:embed static
  24. var staticFS embed.FS
  25. //go:embed programs
  26. var programsFS embed.FS
  27. //go:embed templates
  28. var templatesFS embed.FS
  29. type Nil struct {
  30. Adr string
  31. }
  32. type PGP struct {
  33. Key string
  34. Adr string
  35. }
  36. type Redirection struct {
  37. ID string
  38. URL string
  39. Adr string
  40. }
  41. type Version struct {
  42. Description string
  43. Module string
  44. Content template.HTML
  45. }
  46. type Programs struct {
  47. Programs map[string]Program
  48. Adr string
  49. }
  50. type Program struct {
  51. Name string
  52. Tldr string
  53. DefaultVersion string
  54. Source string
  55. Versions map[string]Version
  56. Tag string
  57. Module string
  58. Content template.HTML
  59. }
  60. type Holiday struct {
  61. Name string
  62. Month int
  63. Day int
  64. Rrule string
  65. Year int
  66. }
  67. func (h Holiday) Format() string {
  68. var result string
  69. if h.Year > 0 {
  70. result = strconv.FormatInt(int64(h.Year), 10)
  71. } else {
  72. result = "2001"
  73. }
  74. if h.Month < 10 {
  75. result += "0"
  76. }
  77. result += strconv.FormatInt(int64(h.Month), 10)
  78. if h.Day < 10 {
  79. result += "0"
  80. }
  81. result += strconv.FormatInt(int64(h.Day), 10)
  82. return result
  83. }
  84. func (h Holiday) UID() string {
  85. uid := strings.ReplaceAll(h.Name, " ", "")
  86. uid = strings.ReplaceAll(uid, "’", "")
  87. uid = strings.ReplaceAll(uid, ".", "")
  88. uid = strings.ToLower(uid)
  89. if h.Year != 0 {
  90. uid = uid + "_" + strconv.FormatInt(int64(h.Year), 10)
  91. }
  92. return uid + "@apiote.xyz"
  93. }
  94. func chooseLanguage(name, acceptLanguage string) string {
  95. languagesSet := map[language.Tag]struct{}{}
  96. entries, err := templatesFS.ReadDir("templates")
  97. for _, entry := range entries {
  98. if entry.IsDir() {
  99. continue
  100. }
  101. nameParts := strings.Split(entry.Name(), ".")
  102. if len(nameParts) == 2 {
  103. continue
  104. }
  105. l, err := language.Parse(nameParts[1])
  106. if err != nil {
  107. continue
  108. }
  109. languagesSet[l] = struct{}{}
  110. }
  111. if len(languagesSet) == 0 {
  112. return name
  113. }
  114. acceptLanguages, _, err := language.ParseAcceptLanguage(acceptLanguage)
  115. if err != nil {
  116. return name
  117. }
  118. languages := make([]language.Tag, len(languagesSet)+1)
  119. languages[0] = language.English
  120. i := 1
  121. for l := range languagesSet {
  122. languages[i] = l
  123. i++
  124. }
  125. matcher := language.NewMatcher(languages)
  126. tag, _, _ := matcher.Match(acceptLanguages...)
  127. lang, _ := tag.Base()
  128. return name + "." + lang.String()
  129. }
  130. func showHtml(w http.ResponseWriter, name string, data any, acceptLanguage string) {
  131. name = chooseLanguage(name, acceptLanguage)
  132. t, err := template.ParseFS(templatesFS, "templates/"+name+".html", "templates/aside.html", "templates/header.html", "templates/nav.html", "templates/head.html", "templates/head_program.html")
  133. if err != nil {
  134. log.Println(err)
  135. if os.IsNotExist(err) {
  136. renderStatus(w, http.StatusNotImplemented, acceptLanguage)
  137. return
  138. }
  139. w.WriteHeader(http.StatusInternalServerError)
  140. fmt.Fprint(w, "Error 500")
  141. return
  142. }
  143. err = t.Execute(w, data)
  144. if err != nil {
  145. log.Println(err)
  146. w.WriteHeader(http.StatusInternalServerError)
  147. fmt.Fprint(w, "Error 500")
  148. return
  149. }
  150. }
  151. func renderStatus(w http.ResponseWriter, status int, acceptLanguage string) {
  152. w.WriteHeader(status)
  153. showHtml(w, fmt.Sprint(status), nil, acceptLanguage)
  154. }
  155. func index(w http.ResponseWriter, r *http.Request) {
  156. acceptLanguage := r.Header.Get("Accept-Language")
  157. path := strings.Split(r.URL.Path[1:], "/")
  158. if path[0] == "" {
  159. showHtml(w, "index", nil, acceptLanguage)
  160. }
  161. if path[0] != "" {
  162. renderStatus(w, http.StatusNotFound, acceptLanguage)
  163. }
  164. }
  165. func donate(w http.ResponseWriter, r *http.Request) {
  166. acceptLanguage := r.Header.Get("Accept-Language")
  167. showHtml(w, "donate", nil, acceptLanguage)
  168. }
  169. func readPrograms() (map[string]Program, error) {
  170. m := map[string]Program{}
  171. programs := []Program{}
  172. file, err := programsFS.Open("programs/index.dirty")
  173. if err != nil {
  174. log.Println(err)
  175. return m, err
  176. }
  177. defer file.Close()
  178. err = dirty.LoadStruct(file, &programs)
  179. if err != nil {
  180. log.Println(err)
  181. log.Println(programs)
  182. }
  183. for _, program := range programs {
  184. m[program.Name] = program
  185. }
  186. return m, err
  187. }
  188. func programs(w http.ResponseWriter, r *http.Request) {
  189. acceptLanguage := r.Header.Get("Accept-Language")
  190. path := strings.Split(r.URL.Path[1:], "/")
  191. programs, err := readPrograms()
  192. if err != nil {
  193. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  194. return
  195. }
  196. var (
  197. program Program
  198. version Version
  199. present bool
  200. )
  201. if path[1] == "" {
  202. showHtml(w, "programs", Programs{programs, "https://apiote.xyz/programs/"}, acceptLanguage)
  203. return
  204. } else if len(path) == 2 {
  205. name := path[1]
  206. program = programs[name]
  207. version, present = program.Versions[""]
  208. } else if len(path) == 3 {
  209. name := path[1]
  210. program = programs[name]
  211. version, present = program.Versions[path[2]]
  212. } else {
  213. renderStatus(w, http.StatusNotFound, acceptLanguage)
  214. return
  215. }
  216. if !present {
  217. renderStatus(w, http.StatusNotFound, acceptLanguage)
  218. return
  219. }
  220. file, err := programsFS.Open("programs/" + version.Description)
  221. if err != nil {
  222. if os.IsNotExist(err) {
  223. renderStatus(w, http.StatusNotFound, acceptLanguage)
  224. return
  225. } else {
  226. log.Println(err)
  227. }
  228. return
  229. }
  230. defer file.Close()
  231. content, err := io.ReadAll(file)
  232. if err != nil {
  233. log.Println(err)
  234. return
  235. }
  236. if len(path) > 2 {
  237. program.Tag = path[2]
  238. } else {
  239. program.Tag = ""
  240. }
  241. program.Module = version.Module
  242. reader := strings.NewReader(string(content))
  243. writer := bytes.NewBuffer([]byte{})
  244. config := configuration.NewConfiguration()
  245. libasciidoc.Convert(reader, writer, config)
  246. program.Content = template.HTML(writer.Bytes())
  247. showHtml(w, "program", program, acceptLanguage)
  248. }
  249. func blogEntries(w http.ResponseWriter, r *http.Request) {
  250. }
  251. func pgp(w http.ResponseWriter, r *http.Request) {
  252. acceptLanguage := r.Header.Get("Accept-Language")
  253. accept := r.Header["Accept"][0]
  254. path := strings.Split(r.URL.Path[1:], "/")
  255. if path[1] == "" {
  256. renderStatus(w, http.StatusNotFound, acceptLanguage)
  257. } else {
  258. file, err := staticFS.Open("static/" + path[1] + ".asc")
  259. defer file.Close()
  260. if err != nil && os.IsNotExist(err) {
  261. renderStatus(w, http.StatusNotFound, acceptLanguage)
  262. return
  263. } else if err != nil {
  264. log.Println(err)
  265. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  266. return
  267. }
  268. key, err := ioutil.ReadAll(file)
  269. if err != nil {
  270. log.Println(err)
  271. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  272. return
  273. }
  274. w.Header().Set("Vary", "Accept")
  275. if strings.Contains(accept, "text/html") {
  276. showHtml(w, "pgp", PGP{string(key), "https://apiote.xyz/pgp/me"}, acceptLanguage)
  277. } else {
  278. w.Header().Set("Content-Type", "application/pgp-key")
  279. fmt.Fprintf(w, "%s", key)
  280. }
  281. }
  282. }
  283. func easter(y int) []Holiday {
  284. a := y % 19
  285. b := y % 4
  286. c := y % 7
  287. p := y / 100
  288. q := (13 + (8 * p)) / 25
  289. m := (15 - q + p - (p / 4)) % 30
  290. n := (4 + p - (p / 4)) % 7
  291. d := (19*a + m) % 30
  292. e := (n + (2 * b) + (4 * c) + (6 * d)) % 7
  293. var easterDate time.Time
  294. if d == 29 && e == 6 {
  295. easterDate = time.Date(y, 4, 19, 0, 0, 0, 0, time.Local)
  296. } else if d == 28 && e == 6 {
  297. easterDate = time.Date(y, 4, 18, 0, 0, 0, 0, time.Local)
  298. } else {
  299. easterDate = time.Date(y, 3, 22, 0, 0, 0, 0, time.Local).AddDate(0, 0, d+e)
  300. }
  301. holidays := []Holiday{}
  302. holidays = append(holidays, Holiday{
  303. Name: "Easter",
  304. Month: int(easterDate.Month()),
  305. Day: easterDate.Day(),
  306. Year: y,
  307. })
  308. h := easterDate.AddDate(0, 0, -52)
  309. holidays = append(holidays, Holiday{
  310. Name: "Fat Thursday",
  311. Month: int(h.Month()),
  312. Day: h.Day(),
  313. Year: y,
  314. })
  315. h = easterDate.AddDate(0, 0, -47)
  316. holidays = append(holidays, Holiday{
  317. Name: "Shrove Tuesday",
  318. Month: int(h.Month()),
  319. Day: h.Day(),
  320. Year: y,
  321. })
  322. h = easterDate.AddDate(0, 0, -46)
  323. holidays = append(holidays, Holiday{
  324. Name: "Ash Wednesday",
  325. Month: int(h.Month()),
  326. Day: h.Day(),
  327. Year: y,
  328. })
  329. h = easterDate.AddDate(0, 0, -7)
  330. holidays = append(holidays, Holiday{
  331. Name: "Palm Sunday",
  332. Month: int(h.Month()),
  333. Day: h.Day(),
  334. Year: y,
  335. })
  336. h = easterDate.AddDate(0, 0, -3)
  337. holidays = append(holidays, Holiday{
  338. Name: "Maundy Thursday",
  339. Month: int(h.Month()),
  340. Day: h.Day(),
  341. Year: y,
  342. })
  343. h = easterDate.AddDate(0, 0, -2)
  344. holidays = append(holidays, Holiday{
  345. Name: "Good Friday",
  346. Month: int(h.Month()),
  347. Day: h.Day(),
  348. Year: y,
  349. })
  350. h = easterDate.AddDate(0, 0, -1)
  351. holidays = append(holidays, Holiday{
  352. Name: "Easter Eve",
  353. Month: int(h.Month()),
  354. Day: h.Day(),
  355. Year: y,
  356. })
  357. h = easterDate.AddDate(0, 0, 1)
  358. holidays = append(holidays, Holiday{
  359. Name: "Easter Monday",
  360. Month: int(h.Month()),
  361. Day: h.Day(),
  362. Year: y,
  363. })
  364. h = easterDate.AddDate(0, 0, 49)
  365. holidays = append(holidays, Holiday{
  366. Name: "Pentecost",
  367. Month: int(h.Month()),
  368. Day: h.Day(),
  369. Year: y,
  370. })
  371. h = easterDate.AddDate(0, 0, 60)
  372. holidays = append(holidays, Holiday{
  373. Name: "Corpus Christi",
  374. Month: int(h.Month()),
  375. Day: h.Day(),
  376. Year: y,
  377. })
  378. return holidays
  379. }
  380. func calendar(dataDir string) func(w http.ResponseWriter, r *http.Request) {
  381. return func(w http.ResponseWriter, r *http.Request) {
  382. acceptLanguage := r.Header.Get("Accept-Language")
  383. file, err := os.Open(filepath.Join(dataDir, "holidays.dirty"))
  384. if err != nil {
  385. if os.IsNotExist(err) {
  386. renderStatus(w, http.StatusNotFound, acceptLanguage)
  387. return
  388. } else {
  389. log.Println(err)
  390. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  391. return
  392. }
  393. }
  394. defer file.Close()
  395. holidays := []Holiday{}
  396. err = dirty.LoadStruct(file, &holidays)
  397. if err != nil {
  398. log.Println(err)
  399. log.Println(holidays)
  400. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  401. return
  402. }
  403. t, err := template.ParseFS(templatesFS, "templates/calendar.ics")
  404. if err != nil {
  405. log.Println(err)
  406. if os.IsNotExist(err) {
  407. renderStatus(w, http.StatusNotImplemented, acceptLanguage)
  408. return
  409. }
  410. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  411. return
  412. }
  413. thisYear := time.Now().Year()
  414. for i := 0; i < 10; i++ {
  415. holidays = append(holidays, easter(thisYear+i)...)
  416. }
  417. w.Header().Set("Content-Type", "text/calendar")
  418. err = t.Execute(w, holidays)
  419. if err != nil {
  420. log.Println(err)
  421. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  422. return
  423. }
  424. }
  425. }
  426. func shortRedirect(dataDir, stateDir string) func(w http.ResponseWriter, r *http.Request) {
  427. return func(w http.ResponseWriter, r *http.Request) {
  428. acceptLanguage := r.Header.Get("Accept-Language")
  429. path := strings.Split(r.URL.Path[1:], "/")
  430. if len(path) == 2 && path[1] == "" {
  431. if r.Method == "" || r.Method == "GET" {
  432. showHtml(w, "s", Nil{"https://apiote.xyz/s/"}, acceptLanguage)
  433. } else if r.Method == "POST" {
  434. r.ParseForm()
  435. id := r.PostForm.Get("id")
  436. url := r.PostForm.Get("url")
  437. password := r.PostForm.Get("password")
  438. if id == "" {
  439. var letters = []rune("3478ABCDEFHJKMNRTWXY")
  440. b := make([]rune, 6)
  441. for i := range b {
  442. b[i] = letters[rand.Intn(len(letters))]
  443. }
  444. id = string(b)
  445. } else {
  446. id = strings.ToUpper(id)
  447. }
  448. if url == "" {
  449. renderStatus(w, http.StatusBadRequest, acceptLanguage)
  450. return
  451. }
  452. hash, err := ioutil.ReadFile(filepath.Join(stateDir, "password"))
  453. if err != nil {
  454. log.Println(err)
  455. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  456. return
  457. }
  458. passMatch, err := ComparePasswordAndHash(password, string(hash))
  459. if err != nil {
  460. log.Println(err)
  461. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  462. return
  463. }
  464. if !passMatch {
  465. renderStatus(w, http.StatusForbidden, acceptLanguage)
  466. return
  467. }
  468. file, err := os.OpenFile(filepath.Join(stateDir, "s.toml"), os.O_RDONLY|os.O_CREATE, 0600)
  469. if err != nil {
  470. log.Println(err)
  471. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  472. return
  473. }
  474. defer file.Close()
  475. shorts := map[string]string{}
  476. scanner := bufio.NewScanner(file)
  477. for scanner.Scan() {
  478. line := strings.Split(scanner.Text(), " = ")
  479. shorts[line[0]] = line[1]
  480. }
  481. if err := scanner.Err(); err != nil {
  482. log.Println(err)
  483. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  484. return
  485. }
  486. file.Close()
  487. if _, ok := shorts[id]; ok {
  488. renderStatus(w, http.StatusConflict, acceptLanguage)
  489. return
  490. }
  491. shorts[id] = url
  492. file, err = os.OpenFile(filepath.Join(stateDir, "s.toml"), os.O_WRONLY|os.O_TRUNC, 0600)
  493. if err != nil {
  494. log.Println(err)
  495. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  496. return
  497. }
  498. defer file.Close()
  499. for shortID, shortURL := range shorts {
  500. _, err = file.WriteString(shortID + " = " + shortURL + "\n")
  501. if err != nil {
  502. log.Println(err)
  503. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  504. return
  505. }
  506. }
  507. w.Header().Add("X-Redirection", "https://apiote.xyz/s/"+id)
  508. w.WriteHeader(http.StatusCreated)
  509. showHtml(w, "s201", Redirection{id, url, "https://apiote.xyz/s/" + id}, acceptLanguage)
  510. }
  511. } else if len(path) != 2 {
  512. renderStatus(w, http.StatusNotFound, acceptLanguage)
  513. } else {
  514. id := strings.ToUpper(path[1])
  515. file, err := os.Open(filepath.Join(stateDir, "s.toml"))
  516. if err != nil {
  517. log.Println(err)
  518. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  519. return
  520. }
  521. defer file.Close()
  522. scanner := bufio.NewScanner(file)
  523. for scanner.Scan() {
  524. line := strings.Split(scanner.Text(), " = ")
  525. if len(line) < 2 {
  526. continue
  527. }
  528. if line[0] == id {
  529. http.Redirect(w, r, line[1], http.StatusMovedPermanently)
  530. return
  531. }
  532. }
  533. renderStatus(w, http.StatusNotFound, acceptLanguage)
  534. }
  535. }
  536. }
  537. func shortShow(stateDir string) func(w http.ResponseWriter, r *http.Request) {
  538. return func(w http.ResponseWriter, r *http.Request) {
  539. acceptLanguage := r.Header.Get("Accept-Language")
  540. path := strings.Split(r.URL.Path[1:], "/")
  541. if len(path) == 2 && path[1] != "" {
  542. id := strings.ToUpper(path[1])
  543. file, err := os.Open(filepath.Join(stateDir, "s.toml"))
  544. if err != nil {
  545. log.Println(err)
  546. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  547. return
  548. }
  549. defer file.Close()
  550. scanner := bufio.NewScanner(file)
  551. for scanner.Scan() {
  552. line := strings.Split(scanner.Text(), " = ")
  553. if len(line) < 2 {
  554. continue
  555. }
  556. if line[0] == id {
  557. showHtml(w, "short", Redirection{line[0], line[1], "https://apiote.xyz/short/" + line[0]}, acceptLanguage)
  558. return
  559. }
  560. }
  561. renderStatus(w, http.StatusNotFound, acceptLanguage)
  562. } else {
  563. renderStatus(w, http.StatusNotFound, acceptLanguage)
  564. }
  565. }
  566. }
  567. func wkd(w http.ResponseWriter, r *http.Request) {
  568. acceptLanguage := r.Header.Get("Accept-Language")
  569. path := strings.Split(r.URL.Path[1:], "/")
  570. if path[3] == "" {
  571. renderStatus(w, http.StatusNotFound, acceptLanguage)
  572. } else {
  573. file, err := staticFS.Open("static/" + path[3] + ".pgp")
  574. defer file.Close()
  575. if err != nil && os.IsNotExist(err) {
  576. renderStatus(w, http.StatusNotFound, acceptLanguage)
  577. return
  578. } else if err != nil {
  579. log.Println(err)
  580. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  581. return
  582. }
  583. w.Header().Set("Content-Type", "application/pgp-key")
  584. w.Header().Set("Access-Control-Allow-Origin", "*")
  585. _, err = io.Copy(w, file)
  586. if err != nil {
  587. log.Println(err)
  588. renderStatus(w, http.StatusInternalServerError, acceptLanguage)
  589. }
  590. }
  591. }
  592. func dogtag(w http.ResponseWriter, r *http.Request) {
  593. acceptLanguage := r.Header.Get("Accept-Language")
  594. showHtml(w, "dogtag", Nil{"https://apiote.xyz/tag"}, acceptLanguage)
  595. }
  596. func route(dataDir, stateDir string) {
  597. http.HandleFunc("/", index)
  598. http.Handle("/static/", http.FileServer(http.FS(staticFS)))
  599. http.HandleFunc("/b/", blogEntries)
  600. http.HandleFunc("/blog/", blogEntries)
  601. http.HandleFunc("/p/", programs)
  602. http.HandleFunc("/programs/", programs)
  603. http.HandleFunc("/donate", donate)
  604. http.HandleFunc("/pgp/", pgp)
  605. http.HandleFunc("/calendar", calendar(dataDir))
  606. http.HandleFunc("/tag", dogtag)
  607. http.HandleFunc("/s/", shortRedirect(dataDir, stateDir))
  608. http.HandleFunc("/short/", shortShow(stateDir))
  609. http.HandleFunc("/.well-known/openpgpkey/hu/", wkd)
  610. e := http.ListenAndServe("127.0.0.1:8080", nil)
  611. if e != nil {
  612. log.Println(e)
  613. }
  614. }