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.
 
 
 
 
 

343 lines
8.9 KiB

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