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.
 
 
 
 
 

293 lines
7.4 KiB

  1. package writefreely
  2. import (
  3. "database/sql"
  4. "fmt"
  5. . "github.com/gorilla/feeds"
  6. "github.com/gorilla/mux"
  7. stripmd "github.com/writeas/go-strip-markdown"
  8. "github.com/writeas/impart"
  9. "github.com/writeas/web-core/log"
  10. "github.com/writeas/web-core/memo"
  11. "github.com/writeas/writefreely/page"
  12. "html/template"
  13. "math"
  14. "net/http"
  15. "strconv"
  16. "time"
  17. )
  18. const (
  19. tlFeedLimit = 100
  20. tlAPIPageLimit = 10
  21. tlMaxAuthorPosts = 5
  22. tlPostsPerPage = 16
  23. )
  24. type localTimeline struct {
  25. m *memo.Memo
  26. posts *[]PublicPost
  27. // Configuration values
  28. postsPerPage int
  29. }
  30. type readPublication struct {
  31. page.StaticPage
  32. Posts *[]PublicPost
  33. CurrentPage int
  34. TotalPages int
  35. }
  36. func initLocalTimeline(app *app) {
  37. app.timeline = &localTimeline{
  38. postsPerPage: tlPostsPerPage,
  39. m: memo.New(app.db.FetchPublicPosts, 10*time.Minute),
  40. }
  41. }
  42. // satisfies memo.Func
  43. func (db *datastore) FetchPublicPosts() (interface{}, error) {
  44. // Finds all public posts and posts in a public collection published during the owner's active subscription period and within the last 3 months
  45. rows, err := db.Query(`SELECT p.id, alias, c.title, p.slug, p.title, p.content, p.text_appearance, p.language, p.rtl, p.created, p.updated
  46. FROM collections c
  47. LEFT JOIN posts p ON p.collection_id = c.id
  48. WHERE c.privacy = 1 AND (p.created >= ` + db.dateSub(3, "month") + ` AND p.created <= ` + db.now() + ` AND pinned_position IS NULL)
  49. ORDER BY p.created DESC`)
  50. if err != nil {
  51. log.Error("Failed selecting from posts: %v", err)
  52. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts." + err.Error()}
  53. }
  54. defer rows.Close()
  55. ap := map[string]uint{}
  56. posts := []PublicPost{}
  57. for rows.Next() {
  58. p := &Post{}
  59. c := &Collection{}
  60. var alias, title sql.NullString
  61. err = rows.Scan(&p.ID, &alias, &title, &p.Slug, &p.Title, &p.Content, &p.Font, &p.Language, &p.RTL, &p.Created, &p.Updated)
  62. if err != nil {
  63. log.Error("[READ] Unable to scan row, skipping: %v", err)
  64. continue
  65. }
  66. isCollectionPost := alias.Valid
  67. if isCollectionPost {
  68. c.Alias = alias.String
  69. if c.Alias != "" && ap[c.Alias] == tlMaxAuthorPosts {
  70. // Don't add post if we've hit the post-per-author limit
  71. continue
  72. }
  73. c.Public = true
  74. c.Title = title.String
  75. }
  76. p.extractData()
  77. p.HTMLContent = template.HTML(applyMarkdown([]byte(p.Content)))
  78. fp := p.processPost()
  79. if isCollectionPost {
  80. fp.Collection = &CollectionObj{Collection: *c}
  81. }
  82. posts = append(posts, fp)
  83. ap[c.Alias]++
  84. }
  85. return posts, nil
  86. }
  87. func viewLocalTimelineAPI(app *app, w http.ResponseWriter, r *http.Request) error {
  88. updateTimelineCache(app.timeline)
  89. skip, _ := strconv.Atoi(r.FormValue("skip"))
  90. posts := []PublicPost{}
  91. for i := skip; i < skip+tlAPIPageLimit && i < len(*app.timeline.posts); i++ {
  92. posts = append(posts, (*app.timeline.posts)[i])
  93. }
  94. return impart.WriteSuccess(w, posts, http.StatusOK)
  95. }
  96. func viewLocalTimeline(app *app, w http.ResponseWriter, r *http.Request) error {
  97. if !app.cfg.App.LocalTimeline {
  98. return impart.HTTPError{http.StatusNotFound, "Page doesn't exist."}
  99. }
  100. vars := mux.Vars(r)
  101. var p int
  102. page := 1
  103. p, _ = strconv.Atoi(vars["page"])
  104. if p > 0 {
  105. page = p
  106. }
  107. return showLocalTimeline(app, w, r, page, vars["author"], vars["tag"])
  108. }
  109. func updateTimelineCache(tl *localTimeline) {
  110. // Fetch posts if enough time has passed since last cache
  111. if tl.posts == nil || tl.m.Invalidate() {
  112. log.Info("[READ] Updating post cache")
  113. var err error
  114. var postsInterfaces interface{}
  115. postsInterfaces, err = tl.m.Get()
  116. if err != nil {
  117. log.Error("[READ] Unable to cache posts: %v", err)
  118. } else {
  119. castPosts := postsInterfaces.([]PublicPost)
  120. tl.posts = &castPosts
  121. }
  122. }
  123. }
  124. func showLocalTimeline(app *app, w http.ResponseWriter, r *http.Request, page int, author, tag string) error {
  125. updateTimelineCache(app.timeline)
  126. pl := len(*(app.timeline.posts))
  127. ttlPages := int(math.Ceil(float64(pl) / float64(app.timeline.postsPerPage)))
  128. start := 0
  129. if page > 1 {
  130. start = app.timeline.postsPerPage * (page - 1)
  131. if start > pl {
  132. return impart.HTTPError{http.StatusFound, fmt.Sprintf("/read/p/%d", ttlPages)}
  133. }
  134. }
  135. end := app.timeline.postsPerPage * page
  136. if end > pl {
  137. end = pl
  138. }
  139. var posts []PublicPost
  140. if author != "" {
  141. posts = []PublicPost{}
  142. for _, p := range *app.timeline.posts {
  143. if author == "anonymous" {
  144. if p.Collection == nil {
  145. posts = append(posts, p)
  146. }
  147. } else if p.Collection != nil && p.Collection.Alias == author {
  148. posts = append(posts, p)
  149. }
  150. }
  151. } else if tag != "" {
  152. posts = []PublicPost{}
  153. for _, p := range *app.timeline.posts {
  154. if p.HasTag(tag) {
  155. posts = append(posts, p)
  156. }
  157. }
  158. } else {
  159. posts = *app.timeline.posts
  160. posts = posts[start:end]
  161. }
  162. d := &readPublication{
  163. pageForReq(app, r),
  164. &posts,
  165. page,
  166. ttlPages,
  167. }
  168. err := templates["read"].ExecuteTemplate(w, "base", d)
  169. if err != nil {
  170. log.Error("Unable to render reader: %v", err)
  171. fmt.Fprintf(w, ":(")
  172. }
  173. return nil
  174. }
  175. // NextPageURL provides a full URL for the next page of collection posts
  176. func (c *readPublication) NextPageURL(n int) string {
  177. return fmt.Sprintf("/read/p/%d", n+1)
  178. }
  179. // PrevPageURL provides a full URL for the previous page of collection posts,
  180. // returning a /page/N result for pages >1
  181. func (c *readPublication) PrevPageURL(n int) string {
  182. if n == 2 {
  183. // Previous page is 1; no need for /p/ prefix
  184. return "/read"
  185. }
  186. return fmt.Sprintf("/read/p/%d", n-1)
  187. }
  188. // handlePostIDRedirect handles a route where a post ID is given and redirects
  189. // the user to the canonical post URL.
  190. func handlePostIDRedirect(app *app, w http.ResponseWriter, r *http.Request) error {
  191. vars := mux.Vars(r)
  192. postID := vars["post"]
  193. p, err := app.db.GetPost(postID, 0)
  194. if err != nil {
  195. return err
  196. }
  197. if !p.CollectionID.Valid {
  198. // No collection; send to normal URL
  199. // NOTE: not handling single user blogs here since this handler is only used for the Reader
  200. return impart.HTTPError{http.StatusFound, app.cfg.App.Host + "/" + postID + ".md"}
  201. }
  202. c, err := app.db.GetCollectionBy("id = ?", fmt.Sprintf("%d", p.CollectionID.Int64))
  203. if err != nil {
  204. return err
  205. }
  206. // Retrieve collection information and send user to canonical URL
  207. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + p.Slug.String}
  208. }
  209. func viewLocalTimelineFeed(app *app, w http.ResponseWriter, req *http.Request) error {
  210. if !app.cfg.App.LocalTimeline {
  211. return impart.HTTPError{http.StatusNotFound, "Page doesn't exist."}
  212. }
  213. updateTimelineCache(app.timeline)
  214. feed := &Feed{
  215. Title: app.cfg.App.SiteName + " Reader",
  216. Link: &Link{Href: app.cfg.App.Host},
  217. Description: "Read the latest posts from " + app.cfg.App.SiteName + ".",
  218. Created: time.Now(),
  219. }
  220. c := 0
  221. var title, permalink, author string
  222. for _, p := range *app.timeline.posts {
  223. if c == tlFeedLimit {
  224. break
  225. }
  226. title = p.PlainDisplayTitle()
  227. permalink = p.CanonicalURL()
  228. if p.Collection != nil {
  229. author = p.Collection.Title
  230. } else {
  231. author = "Anonymous"
  232. permalink += ".md"
  233. }
  234. i := &Item{
  235. Id: app.cfg.App.Host + "/read/a/" + p.ID,
  236. Title: title,
  237. Link: &Link{Href: permalink},
  238. Description: "<![CDATA[" + stripmd.Strip(p.Content) + "]]>",
  239. Content: applyMarkdown([]byte(p.Content)),
  240. Author: &Author{author, ""},
  241. Created: p.Created,
  242. Updated: p.Updated,
  243. }
  244. feed.Items = append(feed.Items, i)
  245. c++
  246. }
  247. rss, err := feed.ToRss()
  248. if err != nil {
  249. return err
  250. }
  251. fmt.Fprint(w, rss)
  252. return nil
  253. }