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.
 
 
 
 
 

341 lines
8.8 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. u := getUserSession(app, r)
  200. d.IsAdmin = u != nil && u.IsAdmin()
  201. d.CanInvite = canUserInvite(app.cfg, d.IsAdmin)
  202. c, err := getReaderSection(app)
  203. if err != nil {
  204. return err
  205. }
  206. d.ContentTitle = c.Title.String
  207. d.Content = template.HTML(applyMarkdown([]byte(c.Content), "", app.cfg))
  208. err = templates["read"].ExecuteTemplate(w, "base", d)
  209. if err != nil {
  210. log.Error("Unable to render reader: %v", err)
  211. fmt.Fprintf(w, ":(")
  212. }
  213. return nil
  214. }
  215. // NextPageURL provides a full URL for the next page of collection posts
  216. func (c *readPublication) NextPageURL(n int) string {
  217. return fmt.Sprintf("/read/p/%d", n+1)
  218. }
  219. // PrevPageURL provides a full URL for the previous page of collection posts,
  220. // returning a /page/N result for pages >1
  221. func (c *readPublication) PrevPageURL(n int) string {
  222. if n == 2 {
  223. // Previous page is 1; no need for /p/ prefix
  224. return "/read"
  225. }
  226. return fmt.Sprintf("/read/p/%d", n-1)
  227. }
  228. // handlePostIDRedirect handles a route where a post ID is given and redirects
  229. // the user to the canonical post URL.
  230. func handlePostIDRedirect(app *App, w http.ResponseWriter, r *http.Request) error {
  231. vars := mux.Vars(r)
  232. postID := vars["post"]
  233. p, err := app.db.GetPost(postID, 0)
  234. if err != nil {
  235. return err
  236. }
  237. if !p.CollectionID.Valid {
  238. // No collection; send to normal URL
  239. // NOTE: not handling single user blogs here since this handler is only used for the Reader
  240. return impart.HTTPError{http.StatusFound, app.cfg.App.Host + "/" + postID + ".md"}
  241. }
  242. c, err := app.db.GetCollectionBy("id = ?", fmt.Sprintf("%d", p.CollectionID.Int64))
  243. if err != nil {
  244. return err
  245. }
  246. c.hostName = app.cfg.App.Host
  247. // Retrieve collection information and send user to canonical URL
  248. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + p.Slug.String}
  249. }
  250. func viewLocalTimelineFeed(app *App, w http.ResponseWriter, req *http.Request) error {
  251. if !app.cfg.App.LocalTimeline {
  252. return impart.HTTPError{http.StatusNotFound, "Page doesn't exist."}
  253. }
  254. updateTimelineCache(app.timeline, false)
  255. feed := &Feed{
  256. Title: app.cfg.App.SiteName + " Reader",
  257. Link: &Link{Href: app.cfg.App.Host},
  258. Description: "Read the latest posts from " + app.cfg.App.SiteName + ".",
  259. Created: time.Now(),
  260. }
  261. c := 0
  262. var title, permalink, author string
  263. for _, p := range *app.timeline.posts {
  264. if c == tlFeedLimit {
  265. break
  266. }
  267. title = p.PlainDisplayTitle()
  268. permalink = p.CanonicalURL(app.cfg.App.Host)
  269. if p.Collection != nil {
  270. author = p.Collection.Title
  271. } else {
  272. author = "Anonymous"
  273. }
  274. i := &Item{
  275. Id: app.cfg.App.Host + "/read/a/" + p.ID,
  276. Title: title,
  277. Link: &Link{Href: permalink},
  278. Description: "<![CDATA[" + stripmd.Strip(p.Content) + "]]>",
  279. Content: applyMarkdown([]byte(p.Content), "", app.cfg),
  280. Author: &Author{author, ""},
  281. Created: p.Created,
  282. Updated: p.Updated,
  283. }
  284. feed.Items = append(feed.Items, i)
  285. c++
  286. }
  287. rss, err := feed.ToRss()
  288. if err != nil {
  289. return err
  290. }
  291. fmt.Fprint(w, rss)
  292. return nil
  293. }