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.
 
 
 
 
 

303 lines
7.7 KiB

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