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.
 
 
 
 
 

308 lines
7.8 KiB

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