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.
 
 
 
 
 

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