A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

335 linhas
8.6 KiB

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