A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

110 lines
2.1 KiB

  1. /*
  2. * Copyright © 2018-2019 Musing Studio LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "fmt"
  13. "net/http"
  14. "time"
  15. "github.com/gorilla/mux"
  16. "github.com/ikeikeikeike/go-sitemap-generator/v2/stm"
  17. "github.com/writeas/web-core/log"
  18. )
  19. func buildSitemap(host, alias string) *stm.Sitemap {
  20. sm := stm.NewSitemap(0)
  21. sm.SetDefaultHost(host)
  22. if alias != "/" {
  23. sm.SetSitemapsPath(alias)
  24. }
  25. sm.Create()
  26. // Note: Do not call `sm.Finalize()` because it flushes
  27. // the underlying datastructure from memory to disk.
  28. return sm
  29. }
  30. func handleViewSitemap(app *App, w http.ResponseWriter, r *http.Request) error {
  31. vars := mux.Vars(r)
  32. // Determine canonical blog URL
  33. alias := vars["collection"]
  34. subdomain := vars["subdomain"]
  35. isSubdomain := subdomain != ""
  36. if isSubdomain {
  37. alias = subdomain
  38. }
  39. host := fmt.Sprintf("%s/%s/", app.cfg.App.Host, alias)
  40. var c *Collection
  41. var err error
  42. pre := "/"
  43. if app.cfg.App.SingleUser {
  44. c, err = app.db.GetCollectionByID(1)
  45. } else {
  46. c, err = app.db.GetCollection(alias)
  47. }
  48. if err != nil {
  49. return err
  50. }
  51. c.hostName = app.cfg.App.Host
  52. if !isSubdomain {
  53. pre += alias + "/"
  54. }
  55. host = c.CanonicalURL()
  56. sm := buildSitemap(host, pre)
  57. posts, err := app.db.GetPosts(app.cfg, c, 0, false, false, false)
  58. if err != nil {
  59. log.Error("Error getting posts: %v", err)
  60. return err
  61. }
  62. lastSiteMod := time.Now()
  63. for i, p := range *posts {
  64. if i == 0 {
  65. lastSiteMod = p.Updated
  66. }
  67. u := stm.URL{
  68. {"loc", p.Slug.String},
  69. {"changefreq", "weekly"},
  70. {"mobile", true},
  71. {"lastmod", p.Updated},
  72. }
  73. if len(p.Images) > 0 {
  74. imgs := []stm.URL{}
  75. for _, i := range p.Images {
  76. imgs = append(imgs, stm.URL{
  77. {"loc", i},
  78. {"title", ""},
  79. })
  80. }
  81. u = append(u, []interface{}{"image", imgs})
  82. }
  83. sm.Add(u)
  84. }
  85. // Add top URL
  86. sm.Add(stm.URL{
  87. {"loc", pre},
  88. {"changefreq", "daily"},
  89. {"priority", "1.0"},
  90. {"lastmod", lastSiteMod},
  91. })
  92. w.Write(sm.XMLContent())
  93. return nil
  94. }