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.
 
 
 
 
 

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