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.
 
 
 
 
 

1536 lines
40 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. "encoding/json"
  14. "fmt"
  15. "html/template"
  16. "net/http"
  17. "regexp"
  18. "strings"
  19. "time"
  20. "github.com/gorilla/mux"
  21. "github.com/guregu/null"
  22. "github.com/guregu/null/zero"
  23. "github.com/kylemcc/twitter-text-go/extract"
  24. "github.com/microcosm-cc/bluemonday"
  25. stripmd "github.com/writeas/go-strip-markdown"
  26. "github.com/writeas/impart"
  27. "github.com/writeas/monday"
  28. "github.com/writeas/slug"
  29. "github.com/writeas/web-core/activitystreams"
  30. "github.com/writeas/web-core/bots"
  31. "github.com/writeas/web-core/converter"
  32. "github.com/writeas/web-core/i18n"
  33. "github.com/writeas/web-core/log"
  34. "github.com/writeas/web-core/tags"
  35. "github.com/writeas/writefreely/config"
  36. "github.com/writeas/writefreely/page"
  37. "github.com/writeas/writefreely/parse"
  38. )
  39. const (
  40. // Post ID length bounds
  41. minIDLen = 10
  42. maxIDLen = 10
  43. userPostIDLen = 10
  44. postIDLen = 10
  45. postMetaDateFormat = "2006-01-02 15:04:05"
  46. )
  47. type (
  48. AnonymousPost struct {
  49. ID string
  50. Content string
  51. HTMLContent template.HTML
  52. Font string
  53. Language string
  54. Direction string
  55. Title string
  56. GenTitle string
  57. Description string
  58. Author string
  59. Views int64
  60. IsPlainText bool
  61. IsCode bool
  62. IsLinkable bool
  63. }
  64. AuthenticatedPost struct {
  65. ID string `json:"id" schema:"id"`
  66. Web bool `json:"web" schema:"web"`
  67. *SubmittedPost
  68. }
  69. // SubmittedPost represents a post supplied by a client for publishing or
  70. // updating. Since Title and Content can be updated to "", they are
  71. // pointers that can be easily tested to detect changes.
  72. SubmittedPost struct {
  73. Slug *string `json:"slug" schema:"slug"`
  74. Title *string `json:"title" schema:"title"`
  75. Content *string `json:"body" schema:"body"`
  76. Font string `json:"font" schema:"font"`
  77. IsRTL converter.NullJSONBool `json:"rtl" schema:"rtl"`
  78. Language converter.NullJSONString `json:"lang" schema:"lang"`
  79. Created *string `json:"created" schema:"created"`
  80. }
  81. // Post represents a post as found in the database.
  82. Post struct {
  83. ID string `db:"id" json:"id"`
  84. Slug null.String `db:"slug" json:"slug,omitempty"`
  85. Font string `db:"text_appearance" json:"appearance"`
  86. Language zero.String `db:"language" json:"language"`
  87. RTL zero.Bool `db:"rtl" json:"rtl"`
  88. Privacy int64 `db:"privacy" json:"-"`
  89. OwnerID null.Int `db:"owner_id" json:"-"`
  90. CollectionID null.Int `db:"collection_id" json:"-"`
  91. PinnedPosition null.Int `db:"pinned_position" json:"-"`
  92. Created time.Time `db:"created" json:"created"`
  93. Updated time.Time `db:"updated" json:"updated"`
  94. ViewCount int64 `db:"view_count" json:"-"`
  95. Title zero.String `db:"title" json:"title"`
  96. HTMLTitle template.HTML `db:"title" json:"-"`
  97. Content string `db:"content" json:"body"`
  98. HTMLContent template.HTML `db:"content" json:"-"`
  99. HTMLExcerpt template.HTML `db:"content" json:"-"`
  100. Tags []string `json:"tags"`
  101. Images []string `json:"images,omitempty"`
  102. OwnerName string `json:"owner,omitempty"`
  103. }
  104. // PublicPost holds properties for a publicly returned post, i.e. a post in
  105. // a context where the viewer may not be the owner. As such, sensitive
  106. // metadata for the post is hidden and properties supporting the display of
  107. // the post are added.
  108. PublicPost struct {
  109. *Post
  110. IsSubdomain bool `json:"-"`
  111. IsTopLevel bool `json:"-"`
  112. DisplayDate string `json:"-"`
  113. Views int64 `json:"views"`
  114. Owner *PublicUser `json:"-"`
  115. IsOwner bool `json:"-"`
  116. Collection *CollectionObj `json:"collection,omitempty"`
  117. }
  118. RawPost struct {
  119. Id, Slug string
  120. Title string
  121. Content string
  122. Views int64
  123. Font string
  124. Created time.Time
  125. IsRTL sql.NullBool
  126. Language sql.NullString
  127. OwnerID int64
  128. CollectionID sql.NullInt64
  129. Found bool
  130. Gone bool
  131. }
  132. AnonymousAuthPost struct {
  133. ID string `json:"id"`
  134. Token string `json:"token"`
  135. }
  136. ClaimPostRequest struct {
  137. *AnonymousAuthPost
  138. CollectionAlias string `json:"collection"`
  139. CreateCollection bool `json:"create_collection"`
  140. // Generated properties
  141. Slug string `json:"-"`
  142. }
  143. ClaimPostResult struct {
  144. ID string `json:"id,omitempty"`
  145. Code int `json:"code,omitempty"`
  146. ErrorMessage string `json:"error_msg,omitempty"`
  147. Post *PublicPost `json:"post,omitempty"`
  148. }
  149. )
  150. func (p *Post) Direction() string {
  151. if p.RTL.Valid {
  152. if p.RTL.Bool {
  153. return "rtl"
  154. }
  155. return "ltr"
  156. }
  157. return "auto"
  158. }
  159. // DisplayTitle dynamically generates a title from the Post's contents if it
  160. // doesn't already have an explicit title.
  161. func (p *Post) DisplayTitle() string {
  162. if p.Title.String != "" {
  163. return p.Title.String
  164. }
  165. t := friendlyPostTitle(p.Content, p.ID)
  166. return t
  167. }
  168. // PlainDisplayTitle dynamically generates a title from the Post's contents if it
  169. // doesn't already have an explicit title.
  170. func (p *Post) PlainDisplayTitle() string {
  171. if t := stripmd.Strip(p.DisplayTitle()); t != "" {
  172. return t
  173. }
  174. return p.ID
  175. }
  176. // FormattedDisplayTitle dynamically generates a title from the Post's contents if it
  177. // doesn't already have an explicit title.
  178. func (p *Post) FormattedDisplayTitle() template.HTML {
  179. if p.HTMLTitle != "" {
  180. return p.HTMLTitle
  181. }
  182. return template.HTML(p.DisplayTitle())
  183. }
  184. // Summary gives a shortened summary of the post based on the post's title,
  185. // especially for display in a longer list of posts. It extracts a summary for
  186. // posts in the Title\n\nBody format, returning nothing if the entire was short
  187. // enough that the extracted title == extracted summary.
  188. func (p Post) Summary() string {
  189. if p.Content == "" {
  190. return ""
  191. }
  192. // Strip out HTML
  193. p.Content = bluemonday.StrictPolicy().Sanitize(p.Content)
  194. // and Markdown
  195. p.Content = stripmd.Strip(p.Content)
  196. title := p.Title.String
  197. var desc string
  198. if title == "" {
  199. // No title, so generate one
  200. title = friendlyPostTitle(p.Content, p.ID)
  201. desc = postDescription(p.Content, title, p.ID)
  202. if desc == title {
  203. return ""
  204. }
  205. return desc
  206. }
  207. return shortPostDescription(p.Content)
  208. }
  209. // Excerpt shows any text that comes before a (more) tag.
  210. // TODO: use HTMLExcerpt in templates instead of this method
  211. func (p *Post) Excerpt() template.HTML {
  212. return p.HTMLExcerpt
  213. }
  214. func (p *Post) CreatedDate() string {
  215. return p.Created.Format("2006-01-02")
  216. }
  217. func (p *Post) Created8601() string {
  218. return p.Created.Format("2006-01-02T15:04:05Z")
  219. }
  220. func (p *Post) IsScheduled() bool {
  221. return p.Created.After(time.Now())
  222. }
  223. func (p *Post) HasTag(tag string) bool {
  224. // Regexp looks for tag and has a non-capturing group at the end looking
  225. // for the end of the word.
  226. // Assisted by: https://stackoverflow.com/a/35192941/1549194
  227. hasTag, _ := regexp.MatchString("#"+tag+`(?:[[:punct:]]|\s|\z)`, p.Content)
  228. return hasTag
  229. }
  230. func (p *Post) HasTitleLink() bool {
  231. if p.Title.String == "" {
  232. return false
  233. }
  234. hasLink, _ := regexp.MatchString(`([^!]+|^)\[.+\]\(.+\)`, p.Title.String)
  235. return hasLink
  236. }
  237. func handleViewPost(app *App, w http.ResponseWriter, r *http.Request) error {
  238. vars := mux.Vars(r)
  239. friendlyID := vars["post"]
  240. // NOTE: until this is done better, be sure to keep this in parity with
  241. // isRaw() and viewCollectionPost()
  242. isJSON := strings.HasSuffix(friendlyID, ".json")
  243. isXML := strings.HasSuffix(friendlyID, ".xml")
  244. isCSS := strings.HasSuffix(friendlyID, ".css")
  245. isMarkdown := strings.HasSuffix(friendlyID, ".md")
  246. isRaw := strings.HasSuffix(friendlyID, ".txt") || isJSON || isXML || isCSS || isMarkdown
  247. // Display reserved page if that is requested resource
  248. if t, ok := pages[r.URL.Path[1:]+".tmpl"]; ok {
  249. return handleTemplatedPage(app, w, r, t)
  250. } else if (strings.Contains(r.URL.Path, ".") && !isRaw && !isMarkdown) || r.URL.Path == "/robots.txt" || r.URL.Path == "/manifest.json" {
  251. // Serve static file
  252. app.shttp.ServeHTTP(w, r)
  253. return nil
  254. }
  255. // Display collection if this is a collection
  256. c, _ := app.db.GetCollection(friendlyID)
  257. if c != nil {
  258. return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s/", friendlyID)}
  259. }
  260. // Normalize the URL, redirecting user to consistent post URL
  261. if friendlyID != strings.ToLower(friendlyID) {
  262. return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s", strings.ToLower(friendlyID))}
  263. }
  264. ext := ""
  265. if isRaw {
  266. parts := strings.Split(friendlyID, ".")
  267. friendlyID = parts[0]
  268. if len(parts) > 1 {
  269. ext = "." + parts[1]
  270. }
  271. }
  272. var ownerID sql.NullInt64
  273. var title string
  274. var content string
  275. var font string
  276. var language []byte
  277. var rtl []byte
  278. var views int64
  279. var post *AnonymousPost
  280. var found bool
  281. var gone bool
  282. fixedID := slug.Make(friendlyID)
  283. if fixedID != friendlyID {
  284. return impart.HTTPError{http.StatusFound, fmt.Sprintf("/%s%s", fixedID, ext)}
  285. }
  286. err := app.db.QueryRow(fmt.Sprintf("SELECT owner_id, title, content, text_appearance, view_count, language, rtl FROM posts WHERE id = ?"), friendlyID).Scan(&ownerID, &title, &content, &font, &views, &language, &rtl)
  287. switch {
  288. case err == sql.ErrNoRows:
  289. found = false
  290. // Output the error in the correct format
  291. if isJSON {
  292. content = "{\"error\": \"Post not found.\"}"
  293. } else if isRaw {
  294. content = "Post not found."
  295. } else {
  296. return ErrPostNotFound
  297. }
  298. case err != nil:
  299. found = false
  300. log.Error("Post loading err: %s\n", err)
  301. return ErrInternalGeneral
  302. default:
  303. found = true
  304. var d string
  305. if len(rtl) == 0 {
  306. d = "auto"
  307. } else if rtl[0] == 49 {
  308. // TODO: find a cleaner way to get this (possibly NULL) value
  309. d = "rtl"
  310. } else {
  311. d = "ltr"
  312. }
  313. generatedTitle := friendlyPostTitle(content, friendlyID)
  314. sanitizedContent := content
  315. if font != "code" {
  316. sanitizedContent = template.HTMLEscapeString(content)
  317. }
  318. var desc string
  319. if title == "" {
  320. desc = postDescription(content, title, friendlyID)
  321. } else {
  322. desc = shortPostDescription(content)
  323. }
  324. post = &AnonymousPost{
  325. ID: friendlyID,
  326. Content: sanitizedContent,
  327. Title: title,
  328. GenTitle: generatedTitle,
  329. Description: desc,
  330. Author: "",
  331. Font: font,
  332. IsPlainText: isRaw,
  333. IsCode: font == "code",
  334. IsLinkable: font != "code",
  335. Views: views,
  336. Language: string(language),
  337. Direction: d,
  338. }
  339. if !isRaw {
  340. post.HTMLContent = template.HTML(applyMarkdown([]byte(content), "", app.cfg))
  341. }
  342. }
  343. var suspended bool
  344. if found {
  345. suspended, err = app.db.IsUserSuspended(ownerID.Int64)
  346. if err != nil {
  347. log.Error("view post: %v", err)
  348. }
  349. }
  350. // Check if post has been unpublished
  351. if content == "" {
  352. gone = true
  353. if isJSON {
  354. content = "{\"error\": \"Post was unpublished.\"}"
  355. } else if isCSS {
  356. content = ""
  357. } else if isRaw {
  358. content = "Post was unpublished."
  359. } else {
  360. return ErrPostUnpublished
  361. }
  362. }
  363. var u = &User{}
  364. if isRaw {
  365. contentType := "text/plain"
  366. if isJSON {
  367. contentType = "application/json"
  368. } else if isCSS {
  369. contentType = "text/css"
  370. } else if isXML {
  371. contentType = "application/xml"
  372. } else if isMarkdown {
  373. contentType = "text/markdown"
  374. }
  375. w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType))
  376. if isMarkdown && post.Title != "" {
  377. fmt.Fprintf(w, "%s\n", post.Title)
  378. for i := 1; i <= len(post.Title); i++ {
  379. fmt.Fprintf(w, "=")
  380. }
  381. fmt.Fprintf(w, "\n\n")
  382. }
  383. fmt.Fprint(w, content)
  384. if !found {
  385. return ErrPostNotFound
  386. } else if gone {
  387. return ErrPostUnpublished
  388. }
  389. } else {
  390. var err error
  391. page := struct {
  392. *AnonymousPost
  393. page.StaticPage
  394. Username string
  395. IsOwner bool
  396. SiteURL string
  397. Suspended bool
  398. }{
  399. AnonymousPost: post,
  400. StaticPage: pageForReq(app, r),
  401. SiteURL: app.cfg.App.Host,
  402. }
  403. if u = getUserSession(app, r); u != nil {
  404. page.Username = u.Username
  405. page.IsOwner = ownerID.Valid && ownerID.Int64 == u.ID
  406. }
  407. if !page.IsOwner && suspended {
  408. return ErrPostNotFound
  409. }
  410. page.Suspended = suspended
  411. err = templates["post"].ExecuteTemplate(w, "post", page)
  412. if err != nil {
  413. log.Error("Post template execute error: %v", err)
  414. }
  415. }
  416. go func() {
  417. if u != nil && ownerID.Valid && ownerID.Int64 == u.ID {
  418. // Post is owned by someone; skip view increment since that person is viewing this post.
  419. return
  420. }
  421. // Update stats for non-raw post views
  422. if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) {
  423. _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE id = ?", friendlyID)
  424. if err != nil {
  425. log.Error("Unable to update posts count: %v", err)
  426. }
  427. }
  428. }()
  429. return nil
  430. }
  431. // API v2 funcs
  432. // newPost creates a new post with or without an owning Collection.
  433. //
  434. // Endpoints:
  435. // /posts
  436. // /posts?collection={alias}
  437. // ? /collections/{alias}/posts
  438. func newPost(app *App, w http.ResponseWriter, r *http.Request) error {
  439. reqJSON := IsJSON(r)
  440. vars := mux.Vars(r)
  441. collAlias := vars["alias"]
  442. if collAlias == "" {
  443. collAlias = r.FormValue("collection")
  444. }
  445. accessToken := r.Header.Get("Authorization")
  446. if accessToken == "" {
  447. // TODO: remove this
  448. accessToken = r.FormValue("access_token")
  449. }
  450. // FIXME: determine web submission with Content-Type header
  451. var u *User
  452. var userID int64 = -1
  453. var username string
  454. if accessToken == "" {
  455. u = getUserSession(app, r)
  456. if u != nil {
  457. userID = u.ID
  458. username = u.Username
  459. }
  460. } else {
  461. userID = app.db.GetUserID(accessToken)
  462. }
  463. suspended, err := app.db.IsUserSuspended(userID)
  464. if err != nil {
  465. log.Error("new post: %v", err)
  466. }
  467. if suspended {
  468. return ErrUserSuspended
  469. }
  470. if userID == -1 {
  471. return ErrNotLoggedIn
  472. }
  473. if accessToken == "" && u == nil && collAlias != "" {
  474. return impart.HTTPError{http.StatusBadRequest, "Parameter `access_token` required."}
  475. }
  476. // Get post data
  477. var p *SubmittedPost
  478. if reqJSON {
  479. decoder := json.NewDecoder(r.Body)
  480. err = decoder.Decode(&p)
  481. if err != nil {
  482. log.Error("Couldn't parse new post JSON request: %v\n", err)
  483. return ErrBadJSON
  484. }
  485. if p.Title == nil {
  486. t := ""
  487. p.Title = &t
  488. }
  489. if strings.TrimSpace(*(p.Content)) == "" {
  490. return ErrNoPublishableContent
  491. }
  492. } else {
  493. post := r.FormValue("body")
  494. appearance := r.FormValue("font")
  495. title := r.FormValue("title")
  496. rtlValue := r.FormValue("rtl")
  497. langValue := r.FormValue("lang")
  498. if strings.TrimSpace(post) == "" {
  499. return ErrNoPublishableContent
  500. }
  501. var isRTL, rtlValid bool
  502. if rtlValue == "auto" && langValue != "" {
  503. isRTL = i18n.LangIsRTL(langValue)
  504. rtlValid = true
  505. } else {
  506. isRTL = rtlValue == "true"
  507. rtlValid = rtlValue != "" && langValue != ""
  508. }
  509. // Create a new post
  510. p = &SubmittedPost{
  511. Title: &title,
  512. Content: &post,
  513. Font: appearance,
  514. IsRTL: converter.NullJSONBool{sql.NullBool{Bool: isRTL, Valid: rtlValid}},
  515. Language: converter.NullJSONString{sql.NullString{String: langValue, Valid: langValue != ""}},
  516. }
  517. }
  518. if !p.isFontValid() {
  519. p.Font = "norm"
  520. }
  521. var newPost *PublicPost = &PublicPost{}
  522. var coll *Collection
  523. if accessToken != "" {
  524. newPost, err = app.db.CreateOwnedPost(p, accessToken, collAlias, app.cfg.App.Host)
  525. } else {
  526. //return ErrNotLoggedIn
  527. // TODO: verify user is logged in
  528. var collID int64
  529. if collAlias != "" {
  530. coll, err = app.db.GetCollection(collAlias)
  531. if err != nil {
  532. return err
  533. }
  534. coll.hostName = app.cfg.App.Host
  535. if coll.OwnerID != u.ID {
  536. return ErrForbiddenCollection
  537. }
  538. collID = coll.ID
  539. }
  540. // TODO: return PublicPost from createPost
  541. newPost.Post, err = app.db.CreatePost(userID, collID, p)
  542. }
  543. if err != nil {
  544. return err
  545. }
  546. if coll != nil {
  547. coll.ForPublic()
  548. newPost.Collection = &CollectionObj{Collection: *coll}
  549. }
  550. newPost.extractData()
  551. newPost.OwnerName = username
  552. // Write success now
  553. response := impart.WriteSuccess(w, newPost, http.StatusCreated)
  554. if newPost.Collection != nil && !app.cfg.App.Private && app.cfg.App.Federation && !newPost.Created.After(time.Now()) {
  555. go federatePost(app, newPost, newPost.Collection.ID, false)
  556. }
  557. return response
  558. }
  559. func existingPost(app *App, w http.ResponseWriter, r *http.Request) error {
  560. reqJSON := IsJSON(r)
  561. vars := mux.Vars(r)
  562. postID := vars["post"]
  563. p := AuthenticatedPost{ID: postID}
  564. var err error
  565. if reqJSON {
  566. // Decode JSON request
  567. decoder := json.NewDecoder(r.Body)
  568. err = decoder.Decode(&p)
  569. if err != nil {
  570. log.Error("Couldn't parse post update JSON request: %v\n", err)
  571. return ErrBadJSON
  572. }
  573. } else {
  574. err = r.ParseForm()
  575. if err != nil {
  576. log.Error("Couldn't parse post update form request: %v\n", err)
  577. return ErrBadFormData
  578. }
  579. // Can't decode to a nil SubmittedPost property, so create instance now
  580. p.SubmittedPost = &SubmittedPost{}
  581. err = app.formDecoder.Decode(&p, r.PostForm)
  582. if err != nil {
  583. log.Error("Couldn't decode post update form request: %v\n", err)
  584. return ErrBadFormData
  585. }
  586. }
  587. if p.Web {
  588. p.IsRTL.Valid = true
  589. }
  590. if p.SubmittedPost == nil {
  591. return ErrPostNoUpdatableVals
  592. }
  593. // Ensure an access token was given
  594. accessToken := r.Header.Get("Authorization")
  595. // Get user's cookie session if there's no token
  596. var u *User
  597. //var username string
  598. if accessToken == "" {
  599. u = getUserSession(app, r)
  600. if u != nil {
  601. //username = u.Username
  602. }
  603. }
  604. if u == nil && accessToken == "" {
  605. return ErrNoAccessToken
  606. }
  607. // Get user ID from current session or given access token, if one was given.
  608. var userID int64
  609. if u != nil {
  610. userID = u.ID
  611. } else if accessToken != "" {
  612. userID, err = AuthenticateUser(app.db, accessToken)
  613. if err != nil {
  614. return err
  615. }
  616. }
  617. suspended, err := app.db.IsUserSuspended(userID)
  618. if err != nil {
  619. log.Error("existing post: %v", err)
  620. }
  621. if suspended {
  622. return ErrUserSuspended
  623. }
  624. // Modify post struct
  625. p.ID = postID
  626. err = app.db.UpdateOwnedPost(&p, userID)
  627. if err != nil {
  628. if reqJSON {
  629. return err
  630. }
  631. if err, ok := err.(impart.HTTPError); ok {
  632. addSessionFlash(app, w, r, err.Message, nil)
  633. } else {
  634. addSessionFlash(app, w, r, err.Error(), nil)
  635. }
  636. }
  637. var pRes *PublicPost
  638. pRes, err = app.db.GetPost(p.ID, 0)
  639. if reqJSON {
  640. if err != nil {
  641. return err
  642. }
  643. pRes.extractData()
  644. }
  645. if pRes.CollectionID.Valid {
  646. coll, err := app.db.GetCollectionBy("id = ?", pRes.CollectionID.Int64)
  647. if err == nil && !app.cfg.App.Private && app.cfg.App.Federation {
  648. coll.hostName = app.cfg.App.Host
  649. pRes.Collection = &CollectionObj{Collection: *coll}
  650. go federatePost(app, pRes, pRes.Collection.ID, true)
  651. }
  652. }
  653. // Write success now
  654. if reqJSON {
  655. return impart.WriteSuccess(w, pRes, http.StatusOK)
  656. }
  657. addSessionFlash(app, w, r, "Changes saved.", nil)
  658. collectionAlias := vars["alias"]
  659. redirect := "/" + postID + "/meta"
  660. if collectionAlias != "" {
  661. collPre := "/" + collectionAlias
  662. if app.cfg.App.SingleUser {
  663. collPre = ""
  664. }
  665. redirect = collPre + "/" + pRes.Slug.String + "/edit/meta"
  666. } else {
  667. if app.cfg.App.SingleUser {
  668. redirect = "/d" + redirect
  669. }
  670. }
  671. w.Header().Set("Location", redirect)
  672. w.WriteHeader(http.StatusFound)
  673. return nil
  674. }
  675. func deletePost(app *App, w http.ResponseWriter, r *http.Request) error {
  676. vars := mux.Vars(r)
  677. friendlyID := vars["post"]
  678. editToken := r.FormValue("token")
  679. var ownerID int64
  680. var u *User
  681. accessToken := r.Header.Get("Authorization")
  682. if accessToken == "" && editToken == "" {
  683. u = getUserSession(app, r)
  684. if u == nil {
  685. return ErrNoAccessToken
  686. }
  687. }
  688. var res sql.Result
  689. var t *sql.Tx
  690. var err error
  691. var collID sql.NullInt64
  692. var coll *Collection
  693. var pp *PublicPost
  694. if editToken != "" {
  695. // TODO: SELECT owner_id, as well, and return appropriate error if NULL instead of running two queries
  696. var dummy int64
  697. err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ?", friendlyID).Scan(&dummy)
  698. switch {
  699. case err == sql.ErrNoRows:
  700. return impart.HTTPError{http.StatusNotFound, "Post not found."}
  701. }
  702. err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ? AND owner_id IS NULL", friendlyID).Scan(&dummy)
  703. switch {
  704. case err == sql.ErrNoRows:
  705. // Post already has an owner. This could provide a bad experience
  706. // for the user, but it's more important to ensure data isn't lost
  707. // unexpectedly. So prevent deletion via token.
  708. return impart.HTTPError{http.StatusConflict, "This post belongs to some user (hopefully yours). Please log in and delete it from that user's account."}
  709. }
  710. res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND modify_token = ? AND owner_id IS NULL", friendlyID, editToken)
  711. } else if accessToken != "" || u != nil {
  712. // Caller provided some way to authenticate; assume caller expects the
  713. // post to be deleted based on a specific post owner, thus we should
  714. // return corresponding errors.
  715. if accessToken != "" {
  716. ownerID = app.db.GetUserID(accessToken)
  717. if ownerID == -1 {
  718. return ErrBadAccessToken
  719. }
  720. } else {
  721. ownerID = u.ID
  722. }
  723. // TODO: don't make two queries
  724. var realOwnerID sql.NullInt64
  725. err = app.db.QueryRow("SELECT collection_id, owner_id FROM posts WHERE id = ?", friendlyID).Scan(&collID, &realOwnerID)
  726. if err != nil {
  727. return err
  728. }
  729. if !collID.Valid {
  730. // There's no collection; simply delete the post
  731. res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID)
  732. } else {
  733. // Post belongs to a collection; do any additional clean up
  734. coll, err = app.db.GetCollectionBy("id = ?", collID.Int64)
  735. if err != nil {
  736. log.Error("Unable to get collection: %v", err)
  737. return err
  738. }
  739. if app.cfg.App.Federation {
  740. // First fetch full post for federation
  741. pp, err = app.db.GetOwnedPost(friendlyID, ownerID)
  742. if err != nil {
  743. log.Error("Unable to get owned post: %v", err)
  744. return err
  745. }
  746. collObj := &CollectionObj{Collection: *coll}
  747. pp.Collection = collObj
  748. }
  749. t, err = app.db.Begin()
  750. if err != nil {
  751. log.Error("No begin: %v", err)
  752. return err
  753. }
  754. res, err = t.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID)
  755. }
  756. } else {
  757. return impart.HTTPError{http.StatusBadRequest, "No authenticated user or post token given."}
  758. }
  759. if err != nil {
  760. return err
  761. }
  762. affected, err := res.RowsAffected()
  763. if err != nil {
  764. if t != nil {
  765. t.Rollback()
  766. log.Error("Rows affected err! Rolling back")
  767. }
  768. return err
  769. } else if affected == 0 {
  770. if t != nil {
  771. t.Rollback()
  772. log.Error("No rows affected! Rolling back")
  773. }
  774. return impart.HTTPError{http.StatusForbidden, "Post not found, or you're not the owner."}
  775. }
  776. if t != nil {
  777. t.Commit()
  778. }
  779. if coll != nil && !app.cfg.App.Private && app.cfg.App.Federation {
  780. go deleteFederatedPost(app, pp, collID.Int64)
  781. }
  782. return impart.HTTPError{Status: http.StatusNoContent}
  783. }
  784. // addPost associates a post with the authenticated user.
  785. func addPost(app *App, w http.ResponseWriter, r *http.Request) error {
  786. var ownerID int64
  787. // Authenticate user
  788. at := r.Header.Get("Authorization")
  789. if at != "" {
  790. ownerID = app.db.GetUserID(at)
  791. if ownerID == -1 {
  792. return ErrBadAccessToken
  793. }
  794. } else {
  795. u := getUserSession(app, r)
  796. if u == nil {
  797. return ErrNotLoggedIn
  798. }
  799. ownerID = u.ID
  800. }
  801. suspended, err := app.db.IsUserSuspended(ownerID)
  802. if err != nil {
  803. log.Error("add post: %v", err)
  804. }
  805. if suspended {
  806. return ErrUserSuspended
  807. }
  808. // Parse claimed posts in format:
  809. // [{"id": "...", "token": "..."}]
  810. var claims *[]ClaimPostRequest
  811. decoder := json.NewDecoder(r.Body)
  812. err = decoder.Decode(&claims)
  813. if err != nil {
  814. return ErrBadJSONArray
  815. }
  816. vars := mux.Vars(r)
  817. collAlias := vars["alias"]
  818. // Update all given posts
  819. res, err := app.db.ClaimPosts(app.cfg, ownerID, collAlias, claims)
  820. if err != nil {
  821. return err
  822. }
  823. if !app.cfg.App.Private && app.cfg.App.Federation {
  824. for _, pRes := range *res {
  825. if pRes.Code != http.StatusOK {
  826. continue
  827. }
  828. if !pRes.Post.Created.After(time.Now()) {
  829. pRes.Post.Collection.hostName = app.cfg.App.Host
  830. go federatePost(app, pRes.Post, pRes.Post.Collection.ID, false)
  831. }
  832. }
  833. }
  834. return impart.WriteSuccess(w, res, http.StatusOK)
  835. }
  836. func dispersePost(app *App, w http.ResponseWriter, r *http.Request) error {
  837. var ownerID int64
  838. // Authenticate user
  839. at := r.Header.Get("Authorization")
  840. if at != "" {
  841. ownerID = app.db.GetUserID(at)
  842. if ownerID == -1 {
  843. return ErrBadAccessToken
  844. }
  845. } else {
  846. u := getUserSession(app, r)
  847. if u == nil {
  848. return ErrNotLoggedIn
  849. }
  850. ownerID = u.ID
  851. }
  852. // Parse posts in format:
  853. // ["..."]
  854. var postIDs []string
  855. decoder := json.NewDecoder(r.Body)
  856. err := decoder.Decode(&postIDs)
  857. if err != nil {
  858. return ErrBadJSONArray
  859. }
  860. // Update all given posts
  861. res, err := app.db.DispersePosts(ownerID, postIDs)
  862. if err != nil {
  863. return err
  864. }
  865. return impart.WriteSuccess(w, res, http.StatusOK)
  866. }
  867. type (
  868. PinPostResult struct {
  869. ID string `json:"id,omitempty"`
  870. Code int `json:"code,omitempty"`
  871. ErrorMessage string `json:"error_msg,omitempty"`
  872. }
  873. )
  874. // pinPost pins a post to a blog
  875. func pinPost(app *App, w http.ResponseWriter, r *http.Request) error {
  876. var userID int64
  877. // Authenticate user
  878. at := r.Header.Get("Authorization")
  879. if at != "" {
  880. userID = app.db.GetUserID(at)
  881. if userID == -1 {
  882. return ErrBadAccessToken
  883. }
  884. } else {
  885. u := getUserSession(app, r)
  886. if u == nil {
  887. return ErrNotLoggedIn
  888. }
  889. userID = u.ID
  890. }
  891. suspended, err := app.db.IsUserSuspended(userID)
  892. if err != nil {
  893. log.Error("pin post: %v", err)
  894. }
  895. if suspended {
  896. return ErrUserSuspended
  897. }
  898. // Parse request
  899. var posts []struct {
  900. ID string `json:"id"`
  901. Position int64 `json:"position"`
  902. }
  903. decoder := json.NewDecoder(r.Body)
  904. err = decoder.Decode(&posts)
  905. if err != nil {
  906. return ErrBadJSONArray
  907. }
  908. // Validate data
  909. vars := mux.Vars(r)
  910. collAlias := vars["alias"]
  911. coll, err := app.db.GetCollection(collAlias)
  912. if err != nil {
  913. return err
  914. }
  915. if coll.OwnerID != userID {
  916. return ErrForbiddenCollection
  917. }
  918. // Do (un)pinning
  919. isPinning := r.URL.Path[strings.LastIndex(r.URL.Path, "/"):] == "/pin"
  920. res := []PinPostResult{}
  921. for _, p := range posts {
  922. err = app.db.UpdatePostPinState(isPinning, p.ID, coll.ID, userID, p.Position)
  923. ppr := PinPostResult{ID: p.ID}
  924. if err != nil {
  925. ppr.Code = http.StatusInternalServerError
  926. // TODO: set error messsage
  927. } else {
  928. ppr.Code = http.StatusOK
  929. }
  930. res = append(res, ppr)
  931. }
  932. return impart.WriteSuccess(w, res, http.StatusOK)
  933. }
  934. func fetchPost(app *App, w http.ResponseWriter, r *http.Request) error {
  935. var collID int64
  936. var coll *Collection
  937. var err error
  938. vars := mux.Vars(r)
  939. if collAlias := vars["alias"]; collAlias != "" {
  940. // Fetch collection information, since an alias is provided
  941. coll, err = app.db.GetCollection(collAlias)
  942. if err != nil {
  943. return err
  944. }
  945. collID = coll.ID
  946. }
  947. p, err := app.db.GetPost(vars["post"], collID)
  948. if err != nil {
  949. return err
  950. }
  951. if coll == nil && p.CollectionID.Valid {
  952. // Collection post is getting fetched by post ID, not coll alias + post slug, so get coll info now.
  953. coll, err = app.db.GetCollectionByID(p.CollectionID.Int64)
  954. if err != nil {
  955. return err
  956. }
  957. }
  958. if coll != nil {
  959. coll.hostName = app.cfg.App.Host
  960. _, err = apiCheckCollectionPermissions(app, r, coll)
  961. if err != nil {
  962. return err
  963. }
  964. }
  965. suspended, err := app.db.IsUserSuspended(p.OwnerID.Int64)
  966. if err != nil {
  967. log.Error("fetch post: %v", err)
  968. }
  969. if suspended {
  970. return ErrPostNotFound
  971. }
  972. p.extractData()
  973. accept := r.Header.Get("Accept")
  974. if strings.Contains(accept, "application/activity+json") {
  975. if coll == nil {
  976. // This is a draft post; 404 for now
  977. // TODO: return ActivityObject
  978. return impart.HTTPError{http.StatusNotFound, ""}
  979. }
  980. p.Collection = &CollectionObj{Collection: *coll}
  981. po := p.ActivityObject(app.cfg)
  982. po.Context = []interface{}{activitystreams.Namespace}
  983. return impart.RenderActivityJSON(w, po, http.StatusOK)
  984. }
  985. return impart.WriteSuccess(w, p, http.StatusOK)
  986. }
  987. func fetchPostProperty(app *App, w http.ResponseWriter, r *http.Request) error {
  988. vars := mux.Vars(r)
  989. p, err := app.db.GetPostProperty(vars["post"], 0, vars["property"])
  990. if err != nil {
  991. return err
  992. }
  993. return impart.WriteSuccess(w, p, http.StatusOK)
  994. }
  995. func (p *Post) processPost() PublicPost {
  996. res := &PublicPost{Post: p, Views: 0}
  997. res.Views = p.ViewCount
  998. // TODO: move to own function
  999. loc := monday.FuzzyLocale(p.Language.String)
  1000. res.DisplayDate = monday.Format(p.Created, monday.LongFormatsByLocale[loc], loc)
  1001. return *res
  1002. }
  1003. func (p *PublicPost) CanonicalURL(hostName string) string {
  1004. if p.Collection == nil || p.Collection.Alias == "" {
  1005. return hostName + "/" + p.ID
  1006. }
  1007. return p.Collection.CanonicalURL() + p.Slug.String
  1008. }
  1009. func (p *PublicPost) ActivityObject(cfg *config.Config) *activitystreams.Object {
  1010. o := activitystreams.NewArticleObject()
  1011. o.ID = p.Collection.FederatedAPIBase() + "api/posts/" + p.ID
  1012. o.Published = p.Created
  1013. o.URL = p.CanonicalURL(cfg.App.Host)
  1014. o.AttributedTo = p.Collection.FederatedAccount()
  1015. o.CC = []string{
  1016. p.Collection.FederatedAccount() + "/followers",
  1017. }
  1018. o.Name = p.DisplayTitle()
  1019. if p.HTMLContent == template.HTML("") {
  1020. p.formatContent(cfg, false)
  1021. }
  1022. o.Content = string(p.HTMLContent)
  1023. if p.Language.Valid {
  1024. o.ContentMap = map[string]string{
  1025. p.Language.String: string(p.HTMLContent),
  1026. }
  1027. }
  1028. if len(p.Tags) == 0 {
  1029. o.Tag = []activitystreams.Tag{}
  1030. } else {
  1031. var tagBaseURL string
  1032. if isSingleUser {
  1033. tagBaseURL = p.Collection.CanonicalURL() + "tag:"
  1034. } else {
  1035. if cfg.App.Chorus {
  1036. tagBaseURL = fmt.Sprintf("%s/read/t/", p.Collection.hostName)
  1037. } else {
  1038. tagBaseURL = fmt.Sprintf("%s/%s/tag:", p.Collection.hostName, p.Collection.Alias)
  1039. }
  1040. }
  1041. for _, t := range p.Tags {
  1042. o.Tag = append(o.Tag, activitystreams.Tag{
  1043. Type: activitystreams.TagHashtag,
  1044. HRef: tagBaseURL + t,
  1045. Name: "#" + t,
  1046. })
  1047. }
  1048. }
  1049. return o
  1050. }
  1051. // TODO: merge this into getSlugFromPost or phase it out
  1052. func getSlug(title, lang string) string {
  1053. return getSlugFromPost("", title, lang)
  1054. }
  1055. func getSlugFromPost(title, body, lang string) string {
  1056. if title == "" {
  1057. title = postTitle(body, body)
  1058. }
  1059. title = parse.PostLede(title, false)
  1060. // Truncate lede if needed
  1061. title, _ = parse.TruncToWord(title, 80)
  1062. var s string
  1063. if lang != "" && len(lang) == 2 {
  1064. s = slug.MakeLang(title, lang)
  1065. } else {
  1066. s = slug.Make(title)
  1067. }
  1068. // Transliteration may cause the slug to expand past the limit, so truncate again
  1069. s, _ = parse.TruncToWord(s, 80)
  1070. return strings.TrimFunc(s, func(r rune) bool {
  1071. // TruncToWord doesn't respect words in a slug, since spaces are replaced
  1072. // with hyphens. So remove any trailing hyphens.
  1073. return r == '-'
  1074. })
  1075. }
  1076. // isFontValid returns whether or not the submitted post's appearance is valid.
  1077. func (p *SubmittedPost) isFontValid() bool {
  1078. validFonts := map[string]bool{
  1079. "norm": true,
  1080. "sans": true,
  1081. "mono": true,
  1082. "wrap": true,
  1083. "code": true,
  1084. }
  1085. _, valid := validFonts[p.Font]
  1086. return valid
  1087. }
  1088. func getRawPost(app *App, friendlyID string) *RawPost {
  1089. var content, font, title string
  1090. var isRTL sql.NullBool
  1091. var lang sql.NullString
  1092. var ownerID sql.NullInt64
  1093. var created time.Time
  1094. err := app.db.QueryRow("SELECT title, content, text_appearance, language, rtl, created, owner_id FROM posts WHERE id = ?", friendlyID).Scan(&title, &content, &font, &lang, &isRTL, &created, &ownerID)
  1095. switch {
  1096. case err == sql.ErrNoRows:
  1097. return &RawPost{Content: "", Found: false, Gone: false}
  1098. case err != nil:
  1099. return &RawPost{Content: "", Found: true, Gone: false}
  1100. }
  1101. return &RawPost{Title: title, Content: content, Font: font, Created: created, IsRTL: isRTL, Language: lang, OwnerID: ownerID.Int64, Found: true, Gone: content == ""}
  1102. }
  1103. // TODO; return a Post!
  1104. func getRawCollectionPost(app *App, slug, collAlias string) *RawPost {
  1105. var id, title, content, font string
  1106. var isRTL sql.NullBool
  1107. var lang sql.NullString
  1108. var created time.Time
  1109. var ownerID null.Int
  1110. var views int64
  1111. var err error
  1112. if app.cfg.App.SingleUser {
  1113. err = app.db.QueryRow("SELECT id, title, content, text_appearance, language, rtl, view_count, created, owner_id FROM posts WHERE slug = ? AND collection_id = 1", slug).Scan(&id, &title, &content, &font, &lang, &isRTL, &views, &created, &ownerID)
  1114. } else {
  1115. err = app.db.QueryRow("SELECT id, title, content, text_appearance, language, rtl, view_count, created, owner_id FROM posts WHERE slug = ? AND collection_id = (SELECT id FROM collections WHERE alias = ?)", slug, collAlias).Scan(&id, &title, &content, &font, &lang, &isRTL, &views, &created, &ownerID)
  1116. }
  1117. switch {
  1118. case err == sql.ErrNoRows:
  1119. return &RawPost{Content: "", Found: false, Gone: false}
  1120. case err != nil:
  1121. return &RawPost{Content: "", Found: true, Gone: false}
  1122. }
  1123. return &RawPost{
  1124. Id: id,
  1125. Slug: slug,
  1126. Title: title,
  1127. Content: content,
  1128. Font: font,
  1129. Created: created,
  1130. IsRTL: isRTL,
  1131. Language: lang,
  1132. OwnerID: ownerID.Int64,
  1133. Found: true,
  1134. Gone: content == "",
  1135. Views: views,
  1136. }
  1137. }
  1138. func isRaw(r *http.Request) bool {
  1139. vars := mux.Vars(r)
  1140. slug := vars["slug"]
  1141. // NOTE: until this is done better, be sure to keep this in parity with
  1142. // isRaw in viewCollectionPost() and handleViewPost()
  1143. isJSON := strings.HasSuffix(slug, ".json")
  1144. isXML := strings.HasSuffix(slug, ".xml")
  1145. isMarkdown := strings.HasSuffix(slug, ".md")
  1146. return strings.HasSuffix(slug, ".txt") || isJSON || isXML || isMarkdown
  1147. }
  1148. func viewCollectionPost(app *App, w http.ResponseWriter, r *http.Request) error {
  1149. vars := mux.Vars(r)
  1150. slug := vars["slug"]
  1151. // NOTE: until this is done better, be sure to keep this in parity with
  1152. // isRaw() and handleViewPost()
  1153. isJSON := strings.HasSuffix(slug, ".json")
  1154. isXML := strings.HasSuffix(slug, ".xml")
  1155. isMarkdown := strings.HasSuffix(slug, ".md")
  1156. isRaw := strings.HasSuffix(slug, ".txt") || isJSON || isXML || isMarkdown
  1157. cr := &collectionReq{}
  1158. err := processCollectionRequest(cr, vars, w, r)
  1159. if err != nil {
  1160. return err
  1161. }
  1162. // Check for hellbanned users
  1163. u, err := checkUserForCollection(app, cr, r, true)
  1164. if err != nil {
  1165. return err
  1166. }
  1167. // Normalize the URL, redirecting user to consistent post URL
  1168. if slug != strings.ToLower(slug) {
  1169. loc := fmt.Sprintf("/%s", strings.ToLower(slug))
  1170. if !app.cfg.App.SingleUser {
  1171. loc = "/" + cr.alias + loc
  1172. }
  1173. return impart.HTTPError{http.StatusMovedPermanently, loc}
  1174. }
  1175. // Display collection if this is a collection
  1176. var c *Collection
  1177. if app.cfg.App.SingleUser {
  1178. c, err = app.db.GetCollectionByID(1)
  1179. } else {
  1180. c, err = app.db.GetCollection(cr.alias)
  1181. }
  1182. if err != nil {
  1183. if err, ok := err.(impart.HTTPError); ok {
  1184. if err.Status == http.StatusNotFound {
  1185. // Redirect if necessary
  1186. newAlias := app.db.GetCollectionRedirect(cr.alias)
  1187. if newAlias != "" {
  1188. return impart.HTTPError{http.StatusFound, "/" + newAlias + "/" + slug}
  1189. }
  1190. }
  1191. }
  1192. return err
  1193. }
  1194. c.hostName = app.cfg.App.Host
  1195. suspended, err := app.db.IsUserSuspended(c.OwnerID)
  1196. if err != nil {
  1197. log.Error("view collection post: %v", err)
  1198. }
  1199. // Check collection permissions
  1200. if c.IsPrivate() && (u == nil || u.ID != c.OwnerID) {
  1201. return ErrPostNotFound
  1202. }
  1203. if c.IsProtected() && (u == nil || u.ID != c.OwnerID) {
  1204. if suspended {
  1205. return ErrPostNotFound
  1206. } else if !isAuthorizedForCollection(app, c.Alias, r) {
  1207. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "/?g=" + slug}
  1208. }
  1209. }
  1210. cr.isCollOwner = u != nil && c.OwnerID == u.ID
  1211. if isRaw {
  1212. slug = strings.Split(slug, ".")[0]
  1213. }
  1214. // Fetch extra data about the Collection
  1215. // TODO: refactor out this logic, shared in collection.go:fetchCollection()
  1216. coll := &CollectionObj{Collection: *c}
  1217. owner, err := app.db.GetUserByID(coll.OwnerID)
  1218. if err != nil {
  1219. // Log the error and just continue
  1220. log.Error("Error getting user for collection: %v", err)
  1221. } else {
  1222. coll.Owner = owner
  1223. }
  1224. postFound := true
  1225. p, err := app.db.GetPost(slug, coll.ID)
  1226. if err != nil {
  1227. if err == ErrCollectionPageNotFound {
  1228. postFound = false
  1229. if slug == "feed" {
  1230. // User tried to access blog feed without a trailing slash, and
  1231. // there's no post with a slug "feed"
  1232. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "/feed/"}
  1233. }
  1234. po := &Post{
  1235. Slug: null.NewString(slug, true),
  1236. Font: "norm",
  1237. Language: zero.NewString("en", true),
  1238. RTL: zero.NewBool(false, true),
  1239. Content: `<p class="msg">This page is missing.</p>
  1240. Are you sure it was ever here?`,
  1241. }
  1242. pp := po.processPost()
  1243. p = &pp
  1244. } else {
  1245. return err
  1246. }
  1247. }
  1248. p.IsOwner = owner != nil && p.OwnerID.Valid && owner.ID == p.OwnerID.Int64
  1249. p.Collection = coll
  1250. p.IsTopLevel = app.cfg.App.SingleUser
  1251. if !p.IsOwner && suspended {
  1252. return ErrPostNotFound
  1253. }
  1254. // Check if post has been unpublished
  1255. if p.Content == "" && p.Title.String == "" {
  1256. return impart.HTTPError{http.StatusGone, "Post was unpublished."}
  1257. }
  1258. // Serve collection post
  1259. if isRaw {
  1260. contentType := "text/plain"
  1261. if isJSON {
  1262. contentType = "application/json"
  1263. } else if isXML {
  1264. contentType = "application/xml"
  1265. } else if isMarkdown {
  1266. contentType = "text/markdown"
  1267. }
  1268. w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType))
  1269. if !postFound {
  1270. w.WriteHeader(http.StatusNotFound)
  1271. fmt.Fprintf(w, "Post not found.")
  1272. // TODO: return error instead, so status is correctly reflected in logs
  1273. return nil
  1274. }
  1275. if isMarkdown && p.Title.String != "" {
  1276. fmt.Fprintf(w, "# %s\n\n", p.Title.String)
  1277. }
  1278. fmt.Fprint(w, p.Content)
  1279. } else if strings.Contains(r.Header.Get("Accept"), "application/activity+json") {
  1280. if !postFound {
  1281. return ErrCollectionPageNotFound
  1282. }
  1283. p.extractData()
  1284. ap := p.ActivityObject(app.cfg)
  1285. ap.Context = []interface{}{activitystreams.Namespace}
  1286. return impart.RenderActivityJSON(w, ap, http.StatusOK)
  1287. } else {
  1288. p.extractData()
  1289. p.Content = strings.Replace(p.Content, "<!--more-->", "", 1)
  1290. // TODO: move this to function
  1291. p.formatContent(app.cfg, cr.isCollOwner)
  1292. tp := struct {
  1293. *PublicPost
  1294. page.StaticPage
  1295. IsOwner bool
  1296. IsPinned bool
  1297. IsCustomDomain bool
  1298. PinnedPosts *[]PublicPost
  1299. IsFound bool
  1300. IsAdmin bool
  1301. CanInvite bool
  1302. Suspended bool
  1303. }{
  1304. PublicPost: p,
  1305. StaticPage: pageForReq(app, r),
  1306. IsOwner: cr.isCollOwner,
  1307. IsCustomDomain: cr.isCustomDomain,
  1308. IsFound: postFound,
  1309. Suspended: suspended,
  1310. }
  1311. tp.IsAdmin = u != nil && u.IsAdmin()
  1312. tp.CanInvite = canUserInvite(app.cfg, tp.IsAdmin)
  1313. tp.PinnedPosts, _ = app.db.GetPinnedPosts(coll, p.IsOwner)
  1314. tp.IsPinned = len(*tp.PinnedPosts) > 0 && PostsContains(tp.PinnedPosts, p)
  1315. if !postFound {
  1316. w.WriteHeader(http.StatusNotFound)
  1317. }
  1318. postTmpl := "collection-post"
  1319. if app.cfg.App.Chorus {
  1320. postTmpl = "chorus-collection-post"
  1321. }
  1322. if err := templates[postTmpl].ExecuteTemplate(w, "post", tp); err != nil {
  1323. log.Error("Error in collection-post template: %v", err)
  1324. }
  1325. }
  1326. go func() {
  1327. if p.OwnerID.Valid {
  1328. // Post is owned by someone. Don't update stats if owner is viewing the post.
  1329. if u != nil && p.OwnerID.Int64 == u.ID {
  1330. return
  1331. }
  1332. }
  1333. // Update stats for non-raw post views
  1334. if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) {
  1335. _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE slug = ? AND collection_id = ?", slug, coll.ID)
  1336. if err != nil {
  1337. log.Error("Unable to update posts count: %v", err)
  1338. }
  1339. }
  1340. }()
  1341. return nil
  1342. }
  1343. // TODO: move this to utils after making it more generic
  1344. func PostsContains(sl *[]PublicPost, s *PublicPost) bool {
  1345. for _, e := range *sl {
  1346. if e.ID == s.ID {
  1347. return true
  1348. }
  1349. }
  1350. return false
  1351. }
  1352. func (p *Post) extractData() {
  1353. p.Tags = tags.Extract(p.Content)
  1354. p.extractImages()
  1355. }
  1356. func (rp *RawPost) UserFacingCreated() string {
  1357. return rp.Created.Format(postMetaDateFormat)
  1358. }
  1359. func (rp *RawPost) Created8601() string {
  1360. return rp.Created.Format("2006-01-02T15:04:05Z")
  1361. }
  1362. var imageURLRegex = regexp.MustCompile(`(?i)^https?:\/\/[^ ]*\.(gif|png|jpg|jpeg|image)$`)
  1363. func (p *Post) extractImages() {
  1364. matches := extract.ExtractUrls(p.Content)
  1365. urls := map[string]bool{}
  1366. for i := range matches {
  1367. u := matches[i].Text
  1368. if !imageURLRegex.MatchString(u) {
  1369. continue
  1370. }
  1371. urls[u] = true
  1372. }
  1373. resURLs := make([]string, 0)
  1374. for k := range urls {
  1375. resURLs = append(resURLs, k)
  1376. }
  1377. p.Images = resURLs
  1378. }