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.
 
 
 
 
 

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