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.
 
 
 
 
 

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