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.
 
 
 
 
 

1436 lines
38 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. // Check if post has been unpublished
  344. if content == "" {
  345. gone = true
  346. if isJSON {
  347. content = "{\"error\": \"Post was unpublished.\"}"
  348. } else if isCSS {
  349. content = ""
  350. } else if isRaw {
  351. content = "Post was unpublished."
  352. } else {
  353. return ErrPostUnpublished
  354. }
  355. }
  356. var u = &User{}
  357. if isRaw {
  358. contentType := "text/plain"
  359. if isJSON {
  360. contentType = "application/json"
  361. } else if isCSS {
  362. contentType = "text/css"
  363. } else if isXML {
  364. contentType = "application/xml"
  365. } else if isMarkdown {
  366. contentType = "text/markdown"
  367. }
  368. w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType))
  369. if isMarkdown && post.Title != "" {
  370. fmt.Fprintf(w, "%s\n", post.Title)
  371. for i := 1; i <= len(post.Title); i++ {
  372. fmt.Fprintf(w, "=")
  373. }
  374. fmt.Fprintf(w, "\n\n")
  375. }
  376. fmt.Fprint(w, content)
  377. if !found {
  378. return ErrPostNotFound
  379. } else if gone {
  380. return ErrPostUnpublished
  381. }
  382. } else {
  383. var err error
  384. page := struct {
  385. *AnonymousPost
  386. page.StaticPage
  387. Username string
  388. IsOwner bool
  389. SiteURL string
  390. }{
  391. AnonymousPost: post,
  392. StaticPage: pageForReq(app, r),
  393. SiteURL: app.cfg.App.Host,
  394. }
  395. if u = getUserSession(app, r); u != nil {
  396. page.Username = u.Username
  397. page.IsOwner = ownerID.Valid && ownerID.Int64 == u.ID
  398. }
  399. err = templates["post"].ExecuteTemplate(w, "post", page)
  400. if err != nil {
  401. log.Error("Post template execute error: %v", err)
  402. }
  403. }
  404. go func() {
  405. if u != nil && ownerID.Valid && ownerID.Int64 == u.ID {
  406. // Post is owned by someone; skip view increment since that person is viewing this post.
  407. return
  408. }
  409. // Update stats for non-raw post views
  410. if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) {
  411. _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE id = ?", friendlyID)
  412. if err != nil {
  413. log.Error("Unable to update posts count: %v", err)
  414. }
  415. }
  416. }()
  417. return nil
  418. }
  419. // API v2 funcs
  420. // newPost creates a new post with or without an owning Collection.
  421. //
  422. // Endpoints:
  423. // /posts
  424. // /posts?collection={alias}
  425. // ? /collections/{alias}/posts
  426. func newPost(app *App, w http.ResponseWriter, r *http.Request) error {
  427. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  428. vars := mux.Vars(r)
  429. collAlias := vars["alias"]
  430. if collAlias == "" {
  431. collAlias = r.FormValue("collection")
  432. }
  433. accessToken := r.Header.Get("Authorization")
  434. if accessToken == "" {
  435. // TODO: remove this
  436. accessToken = r.FormValue("access_token")
  437. }
  438. // FIXME: determine web submission with Content-Type header
  439. var u *User
  440. var userID int64 = -1
  441. var username string
  442. if accessToken == "" {
  443. u = getUserSession(app, r)
  444. if u != nil {
  445. userID = u.ID
  446. username = u.Username
  447. }
  448. } else {
  449. userID = app.db.GetUserID(accessToken)
  450. }
  451. if userID == -1 {
  452. return ErrNotLoggedIn
  453. }
  454. if accessToken == "" && u == nil && collAlias != "" {
  455. return impart.HTTPError{http.StatusBadRequest, "Parameter `access_token` required."}
  456. }
  457. // Get post data
  458. var p *SubmittedPost
  459. if reqJSON {
  460. decoder := json.NewDecoder(r.Body)
  461. err := decoder.Decode(&p)
  462. if err != nil {
  463. log.Error("Couldn't parse new post JSON request: %v\n", err)
  464. return ErrBadJSON
  465. }
  466. if p.Title == nil {
  467. t := ""
  468. p.Title = &t
  469. }
  470. if strings.TrimSpace(*(p.Content)) == "" {
  471. return ErrNoPublishableContent
  472. }
  473. } else {
  474. post := r.FormValue("body")
  475. appearance := r.FormValue("font")
  476. title := r.FormValue("title")
  477. rtlValue := r.FormValue("rtl")
  478. langValue := r.FormValue("lang")
  479. if strings.TrimSpace(post) == "" {
  480. return ErrNoPublishableContent
  481. }
  482. var isRTL, rtlValid bool
  483. if rtlValue == "auto" && langValue != "" {
  484. isRTL = i18n.LangIsRTL(langValue)
  485. rtlValid = true
  486. } else {
  487. isRTL = rtlValue == "true"
  488. rtlValid = rtlValue != "" && langValue != ""
  489. }
  490. // Create a new post
  491. p = &SubmittedPost{
  492. Title: &title,
  493. Content: &post,
  494. Font: appearance,
  495. IsRTL: converter.NullJSONBool{sql.NullBool{Bool: isRTL, Valid: rtlValid}},
  496. Language: converter.NullJSONString{sql.NullString{String: langValue, Valid: langValue != ""}},
  497. }
  498. }
  499. if !p.isFontValid() {
  500. p.Font = "norm"
  501. }
  502. var newPost *PublicPost = &PublicPost{}
  503. var coll *Collection
  504. var err error
  505. if accessToken != "" {
  506. newPost, err = app.db.CreateOwnedPost(p, accessToken, collAlias)
  507. } else {
  508. //return ErrNotLoggedIn
  509. // TODO: verify user is logged in
  510. var collID int64
  511. if collAlias != "" {
  512. coll, err = app.db.GetCollection(collAlias)
  513. if err != nil {
  514. return err
  515. }
  516. coll.hostName = app.cfg.App.Host
  517. if coll.OwnerID != u.ID {
  518. return ErrForbiddenCollection
  519. }
  520. collID = coll.ID
  521. }
  522. // TODO: return PublicPost from createPost
  523. newPost.Post, err = app.db.CreatePost(userID, collID, p)
  524. }
  525. if err != nil {
  526. return err
  527. }
  528. if coll != nil {
  529. coll.ForPublic()
  530. newPost.Collection = &CollectionObj{Collection: *coll}
  531. }
  532. newPost.extractData()
  533. newPost.OwnerName = username
  534. // Write success now
  535. response := impart.WriteSuccess(w, newPost, http.StatusCreated)
  536. if newPost.Collection != nil && !app.cfg.App.Private && app.cfg.App.Federation && !newPost.Created.After(time.Now()) {
  537. go federatePost(app, newPost, newPost.Collection.ID, false)
  538. }
  539. return response
  540. }
  541. func existingPost(app *App, w http.ResponseWriter, r *http.Request) error {
  542. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  543. vars := mux.Vars(r)
  544. postID := vars["post"]
  545. p := AuthenticatedPost{ID: postID}
  546. var err error
  547. if reqJSON {
  548. // Decode JSON request
  549. decoder := json.NewDecoder(r.Body)
  550. err = decoder.Decode(&p)
  551. if err != nil {
  552. log.Error("Couldn't parse post update JSON request: %v\n", err)
  553. return ErrBadJSON
  554. }
  555. } else {
  556. err = r.ParseForm()
  557. if err != nil {
  558. log.Error("Couldn't parse post update form request: %v\n", err)
  559. return ErrBadFormData
  560. }
  561. // Can't decode to a nil SubmittedPost property, so create instance now
  562. p.SubmittedPost = &SubmittedPost{}
  563. err = app.formDecoder.Decode(&p, r.PostForm)
  564. if err != nil {
  565. log.Error("Couldn't decode post update form request: %v\n", err)
  566. return ErrBadFormData
  567. }
  568. }
  569. if p.Web {
  570. p.IsRTL.Valid = true
  571. }
  572. if p.SubmittedPost == nil {
  573. return ErrPostNoUpdatableVals
  574. }
  575. // Ensure an access token was given
  576. accessToken := r.Header.Get("Authorization")
  577. // Get user's cookie session if there's no token
  578. var u *User
  579. //var username string
  580. if accessToken == "" {
  581. u = getUserSession(app, r)
  582. if u != nil {
  583. //username = u.Username
  584. }
  585. }
  586. if u == nil && accessToken == "" {
  587. return ErrNoAccessToken
  588. }
  589. // Get user ID from current session or given access token, if one was given.
  590. var userID int64
  591. if u != nil {
  592. userID = u.ID
  593. } else if accessToken != "" {
  594. userID, err = AuthenticateUser(app.db, accessToken)
  595. if err != nil {
  596. return err
  597. }
  598. }
  599. // Modify post struct
  600. p.ID = postID
  601. err = app.db.UpdateOwnedPost(&p, userID)
  602. if err != nil {
  603. if reqJSON {
  604. return err
  605. }
  606. if err, ok := err.(impart.HTTPError); ok {
  607. addSessionFlash(app, w, r, err.Message, nil)
  608. } else {
  609. addSessionFlash(app, w, r, err.Error(), nil)
  610. }
  611. }
  612. var pRes *PublicPost
  613. pRes, err = app.db.GetPost(p.ID, 0)
  614. if reqJSON {
  615. if err != nil {
  616. return err
  617. }
  618. pRes.extractData()
  619. }
  620. if pRes.CollectionID.Valid {
  621. coll, err := app.db.GetCollectionBy("id = ?", pRes.CollectionID.Int64)
  622. if err == nil && !app.cfg.App.Private && app.cfg.App.Federation {
  623. coll.hostName = app.cfg.App.Host
  624. pRes.Collection = &CollectionObj{Collection: *coll}
  625. go federatePost(app, pRes, pRes.Collection.ID, true)
  626. }
  627. }
  628. // Write success now
  629. if reqJSON {
  630. return impart.WriteSuccess(w, pRes, http.StatusOK)
  631. }
  632. addSessionFlash(app, w, r, "Changes saved.", nil)
  633. collectionAlias := vars["alias"]
  634. redirect := "/" + postID + "/meta"
  635. if collectionAlias != "" {
  636. collPre := "/" + collectionAlias
  637. if app.cfg.App.SingleUser {
  638. collPre = ""
  639. }
  640. redirect = collPre + "/" + pRes.Slug.String + "/edit/meta"
  641. } else {
  642. if app.cfg.App.SingleUser {
  643. redirect = "/d" + redirect
  644. }
  645. }
  646. w.Header().Set("Location", redirect)
  647. w.WriteHeader(http.StatusFound)
  648. return nil
  649. }
  650. func deletePost(app *App, w http.ResponseWriter, r *http.Request) error {
  651. vars := mux.Vars(r)
  652. friendlyID := vars["post"]
  653. editToken := r.FormValue("token")
  654. var ownerID int64
  655. var u *User
  656. accessToken := r.Header.Get("Authorization")
  657. if accessToken == "" && editToken == "" {
  658. u = getUserSession(app, r)
  659. if u == nil {
  660. return ErrNoAccessToken
  661. }
  662. }
  663. var res sql.Result
  664. var t *sql.Tx
  665. var err error
  666. var collID sql.NullInt64
  667. var coll *Collection
  668. var pp *PublicPost
  669. if editToken != "" {
  670. // TODO: SELECT owner_id, as well, and return appropriate error if NULL instead of running two queries
  671. var dummy int64
  672. err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ?", friendlyID).Scan(&dummy)
  673. switch {
  674. case err == sql.ErrNoRows:
  675. return impart.HTTPError{http.StatusNotFound, "Post not found."}
  676. }
  677. err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ? AND owner_id IS NULL", friendlyID).Scan(&dummy)
  678. switch {
  679. case err == sql.ErrNoRows:
  680. // Post already has an owner. This could provide a bad experience
  681. // for the user, but it's more important to ensure data isn't lost
  682. // unexpectedly. So prevent deletion via token.
  683. return impart.HTTPError{http.StatusConflict, "This post belongs to some user (hopefully yours). Please log in and delete it from that user's account."}
  684. }
  685. res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND modify_token = ? AND owner_id IS NULL", friendlyID, editToken)
  686. } else if accessToken != "" || u != nil {
  687. // Caller provided some way to authenticate; assume caller expects the
  688. // post to be deleted based on a specific post owner, thus we should
  689. // return corresponding errors.
  690. if accessToken != "" {
  691. ownerID = app.db.GetUserID(accessToken)
  692. if ownerID == -1 {
  693. return ErrBadAccessToken
  694. }
  695. } else {
  696. ownerID = u.ID
  697. }
  698. // TODO: don't make two queries
  699. var realOwnerID sql.NullInt64
  700. err = app.db.QueryRow("SELECT collection_id, owner_id FROM posts WHERE id = ?", friendlyID).Scan(&collID, &realOwnerID)
  701. if err != nil {
  702. return err
  703. }
  704. if !collID.Valid {
  705. // There's no collection; simply delete the post
  706. res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID)
  707. } else {
  708. // Post belongs to a collection; do any additional clean up
  709. coll, err = app.db.GetCollectionBy("id = ?", collID.Int64)
  710. if err != nil {
  711. log.Error("Unable to get collection: %v", err)
  712. return err
  713. }
  714. if app.cfg.App.Federation {
  715. // First fetch full post for federation
  716. pp, err = app.db.GetOwnedPost(friendlyID, ownerID)
  717. if err != nil {
  718. log.Error("Unable to get owned post: %v", err)
  719. return err
  720. }
  721. collObj := &CollectionObj{Collection: *coll}
  722. pp.Collection = collObj
  723. }
  724. t, err = app.db.Begin()
  725. if err != nil {
  726. log.Error("No begin: %v", err)
  727. return err
  728. }
  729. res, err = t.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID)
  730. }
  731. } else {
  732. return impart.HTTPError{http.StatusBadRequest, "No authenticated user or post token given."}
  733. }
  734. if err != nil {
  735. return err
  736. }
  737. affected, err := res.RowsAffected()
  738. if err != nil {
  739. if t != nil {
  740. t.Rollback()
  741. log.Error("Rows affected err! Rolling back")
  742. }
  743. return err
  744. } else if affected == 0 {
  745. if t != nil {
  746. t.Rollback()
  747. log.Error("No rows affected! Rolling back")
  748. }
  749. return impart.HTTPError{http.StatusForbidden, "Post not found, or you're not the owner."}
  750. }
  751. if t != nil {
  752. t.Commit()
  753. }
  754. if coll != nil && !app.cfg.App.Private && app.cfg.App.Federation {
  755. go deleteFederatedPost(app, pp, collID.Int64)
  756. }
  757. return impart.HTTPError{Status: http.StatusNoContent}
  758. }
  759. // addPost associates a post with the authenticated user.
  760. func addPost(app *App, w http.ResponseWriter, r *http.Request) error {
  761. var ownerID int64
  762. // Authenticate user
  763. at := r.Header.Get("Authorization")
  764. if at != "" {
  765. ownerID = app.db.GetUserID(at)
  766. if ownerID == -1 {
  767. return ErrBadAccessToken
  768. }
  769. } else {
  770. u := getUserSession(app, r)
  771. if u == nil {
  772. return ErrNotLoggedIn
  773. }
  774. ownerID = u.ID
  775. }
  776. // Parse claimed posts in format:
  777. // [{"id": "...", "token": "..."}]
  778. var claims *[]ClaimPostRequest
  779. decoder := json.NewDecoder(r.Body)
  780. err := decoder.Decode(&claims)
  781. if err != nil {
  782. return ErrBadJSONArray
  783. }
  784. vars := mux.Vars(r)
  785. collAlias := vars["alias"]
  786. // Update all given posts
  787. res, err := app.db.ClaimPosts(ownerID, collAlias, claims)
  788. if err != nil {
  789. return err
  790. }
  791. if !app.cfg.App.Private && app.cfg.App.Federation {
  792. for _, pRes := range *res {
  793. if pRes.Code != http.StatusOK {
  794. continue
  795. }
  796. if !pRes.Post.Created.After(time.Now()) {
  797. pRes.Post.Collection.hostName = app.cfg.App.Host
  798. go federatePost(app, pRes.Post, pRes.Post.Collection.ID, false)
  799. }
  800. }
  801. }
  802. return impart.WriteSuccess(w, res, http.StatusOK)
  803. }
  804. func dispersePost(app *App, w http.ResponseWriter, r *http.Request) error {
  805. var ownerID int64
  806. // Authenticate user
  807. at := r.Header.Get("Authorization")
  808. if at != "" {
  809. ownerID = app.db.GetUserID(at)
  810. if ownerID == -1 {
  811. return ErrBadAccessToken
  812. }
  813. } else {
  814. u := getUserSession(app, r)
  815. if u == nil {
  816. return ErrNotLoggedIn
  817. }
  818. ownerID = u.ID
  819. }
  820. // Parse posts in format:
  821. // ["..."]
  822. var postIDs []string
  823. decoder := json.NewDecoder(r.Body)
  824. err := decoder.Decode(&postIDs)
  825. if err != nil {
  826. return ErrBadJSONArray
  827. }
  828. // Update all given posts
  829. res, err := app.db.DispersePosts(ownerID, postIDs)
  830. if err != nil {
  831. return err
  832. }
  833. return impart.WriteSuccess(w, res, http.StatusOK)
  834. }
  835. type (
  836. PinPostResult struct {
  837. ID string `json:"id,omitempty"`
  838. Code int `json:"code,omitempty"`
  839. ErrorMessage string `json:"error_msg,omitempty"`
  840. }
  841. )
  842. // pinPost pins a post to a blog
  843. func pinPost(app *App, w http.ResponseWriter, r *http.Request) error {
  844. var userID int64
  845. // Authenticate user
  846. at := r.Header.Get("Authorization")
  847. if at != "" {
  848. userID = app.db.GetUserID(at)
  849. if userID == -1 {
  850. return ErrBadAccessToken
  851. }
  852. } else {
  853. u := getUserSession(app, r)
  854. if u == nil {
  855. return ErrNotLoggedIn
  856. }
  857. userID = u.ID
  858. }
  859. // Parse request
  860. var posts []struct {
  861. ID string `json:"id"`
  862. Position int64 `json:"position"`
  863. }
  864. decoder := json.NewDecoder(r.Body)
  865. err := decoder.Decode(&posts)
  866. if err != nil {
  867. return ErrBadJSONArray
  868. }
  869. // Validate data
  870. vars := mux.Vars(r)
  871. collAlias := vars["alias"]
  872. coll, err := app.db.GetCollection(collAlias)
  873. if err != nil {
  874. return err
  875. }
  876. if coll.OwnerID != userID {
  877. return ErrForbiddenCollection
  878. }
  879. // Do (un)pinning
  880. isPinning := r.URL.Path[strings.LastIndex(r.URL.Path, "/"):] == "/pin"
  881. res := []PinPostResult{}
  882. for _, p := range posts {
  883. err = app.db.UpdatePostPinState(isPinning, p.ID, coll.ID, userID, p.Position)
  884. ppr := PinPostResult{ID: p.ID}
  885. if err != nil {
  886. ppr.Code = http.StatusInternalServerError
  887. // TODO: set error messsage
  888. } else {
  889. ppr.Code = http.StatusOK
  890. }
  891. res = append(res, ppr)
  892. }
  893. return impart.WriteSuccess(w, res, http.StatusOK)
  894. }
  895. func fetchPost(app *App, w http.ResponseWriter, r *http.Request) error {
  896. var collID int64
  897. var coll *Collection
  898. var err error
  899. vars := mux.Vars(r)
  900. if collAlias := vars["alias"]; collAlias != "" {
  901. // Fetch collection information, since an alias is provided
  902. coll, err = app.db.GetCollection(collAlias)
  903. if err != nil {
  904. return err
  905. }
  906. coll.hostName = app.cfg.App.Host
  907. _, err = apiCheckCollectionPermissions(app, r, coll)
  908. if err != nil {
  909. return err
  910. }
  911. collID = coll.ID
  912. }
  913. p, err := app.db.GetPost(vars["post"], collID)
  914. if err != nil {
  915. return err
  916. }
  917. p.extractData()
  918. accept := r.Header.Get("Accept")
  919. if strings.Contains(accept, "application/activity+json") {
  920. // Fetch information about the collection this belongs to
  921. if coll == nil && p.CollectionID.Valid {
  922. coll, err = app.db.GetCollectionByID(p.CollectionID.Int64)
  923. if err != nil {
  924. return err
  925. }
  926. }
  927. if coll == nil {
  928. // This is a draft post; 404 for now
  929. // TODO: return ActivityObject
  930. return impart.HTTPError{http.StatusNotFound, ""}
  931. }
  932. p.Collection = &CollectionObj{Collection: *coll}
  933. po := p.ActivityObject(app.cfg)
  934. po.Context = []interface{}{activitystreams.Namespace}
  935. return impart.RenderActivityJSON(w, po, http.StatusOK)
  936. }
  937. return impart.WriteSuccess(w, p, http.StatusOK)
  938. }
  939. func fetchPostProperty(app *App, w http.ResponseWriter, r *http.Request) error {
  940. vars := mux.Vars(r)
  941. p, err := app.db.GetPostProperty(vars["post"], 0, vars["property"])
  942. if err != nil {
  943. return err
  944. }
  945. return impart.WriteSuccess(w, p, http.StatusOK)
  946. }
  947. func (p *Post) processPost() PublicPost {
  948. res := &PublicPost{Post: p, Views: 0}
  949. res.Views = p.ViewCount
  950. // TODO: move to own function
  951. loc := monday.FuzzyLocale(p.Language.String)
  952. res.DisplayDate = monday.Format(p.Created, monday.LongFormatsByLocale[loc], loc)
  953. return *res
  954. }
  955. func (p *PublicPost) CanonicalURL() string {
  956. if p.Collection == nil || p.Collection.Alias == "" {
  957. return p.Collection.hostName + "/" + p.ID
  958. }
  959. return p.Collection.CanonicalURL() + p.Slug.String
  960. }
  961. func (p *PublicPost) ActivityObject(cfg *config.Config) *activitystreams.Object {
  962. o := activitystreams.NewArticleObject()
  963. o.ID = p.Collection.FederatedAPIBase() + "api/posts/" + p.ID
  964. o.Published = p.Created
  965. o.URL = p.CanonicalURL()
  966. o.AttributedTo = p.Collection.FederatedAccount()
  967. o.CC = []string{
  968. p.Collection.FederatedAccount() + "/followers",
  969. }
  970. o.Name = p.DisplayTitle()
  971. if p.HTMLContent == template.HTML("") {
  972. p.formatContent(cfg, false)
  973. }
  974. o.Content = string(p.HTMLContent)
  975. if p.Language.Valid {
  976. o.ContentMap = map[string]string{
  977. p.Language.String: string(p.HTMLContent),
  978. }
  979. }
  980. if len(p.Tags) == 0 {
  981. o.Tag = []activitystreams.Tag{}
  982. } else {
  983. var tagBaseURL string
  984. if isSingleUser {
  985. tagBaseURL = p.Collection.CanonicalURL() + "tag:"
  986. } else {
  987. if cfg.App.Chorus {
  988. tagBaseURL = fmt.Sprintf("%s/read/t/", p.Collection.hostName)
  989. } else {
  990. tagBaseURL = fmt.Sprintf("%s/%s/tag:", p.Collection.hostName, p.Collection.Alias)
  991. }
  992. }
  993. for _, t := range p.Tags {
  994. o.Tag = append(o.Tag, activitystreams.Tag{
  995. Type: activitystreams.TagHashtag,
  996. HRef: tagBaseURL + t,
  997. Name: "#" + t,
  998. })
  999. }
  1000. }
  1001. return o
  1002. }
  1003. // TODO: merge this into getSlugFromPost or phase it out
  1004. func getSlug(title, lang string) string {
  1005. return getSlugFromPost("", title, lang)
  1006. }
  1007. func getSlugFromPost(title, body, lang string) string {
  1008. if title == "" {
  1009. title = postTitle(body, body)
  1010. }
  1011. title = parse.PostLede(title, false)
  1012. // Truncate lede if needed
  1013. title, _ = parse.TruncToWord(title, 80)
  1014. var s string
  1015. if lang != "" && len(lang) == 2 {
  1016. s = slug.MakeLang(title, lang)
  1017. } else {
  1018. s = slug.Make(title)
  1019. }
  1020. // Transliteration may cause the slug to expand past the limit, so truncate again
  1021. s, _ = parse.TruncToWord(s, 80)
  1022. return strings.TrimFunc(s, func(r rune) bool {
  1023. // TruncToWord doesn't respect words in a slug, since spaces are replaced
  1024. // with hyphens. So remove any trailing hyphens.
  1025. return r == '-'
  1026. })
  1027. }
  1028. // isFontValid returns whether or not the submitted post's appearance is valid.
  1029. func (p *SubmittedPost) isFontValid() bool {
  1030. validFonts := map[string]bool{
  1031. "norm": true,
  1032. "sans": true,
  1033. "mono": true,
  1034. "wrap": true,
  1035. "code": true,
  1036. }
  1037. _, valid := validFonts[p.Font]
  1038. return valid
  1039. }
  1040. func getRawPost(app *App, friendlyID string) *RawPost {
  1041. var content, font, title string
  1042. var isRTL sql.NullBool
  1043. var lang sql.NullString
  1044. var ownerID sql.NullInt64
  1045. var created time.Time
  1046. 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)
  1047. switch {
  1048. case err == sql.ErrNoRows:
  1049. return &RawPost{Content: "", Found: false, Gone: false}
  1050. case err != nil:
  1051. return &RawPost{Content: "", Found: true, Gone: false}
  1052. }
  1053. return &RawPost{Title: title, Content: content, Font: font, Created: created, IsRTL: isRTL, Language: lang, OwnerID: ownerID.Int64, Found: true, Gone: content == ""}
  1054. }
  1055. // TODO; return a Post!
  1056. func getRawCollectionPost(app *App, slug, collAlias string) *RawPost {
  1057. var id, title, content, font string
  1058. var isRTL sql.NullBool
  1059. var lang sql.NullString
  1060. var created time.Time
  1061. var ownerID null.Int
  1062. var views int64
  1063. var err error
  1064. if app.cfg.App.SingleUser {
  1065. 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)
  1066. } else {
  1067. 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)
  1068. }
  1069. switch {
  1070. case err == sql.ErrNoRows:
  1071. return &RawPost{Content: "", Found: false, Gone: false}
  1072. case err != nil:
  1073. return &RawPost{Content: "", Found: true, Gone: false}
  1074. }
  1075. return &RawPost{
  1076. Id: id,
  1077. Slug: slug,
  1078. Title: title,
  1079. Content: content,
  1080. Font: font,
  1081. Created: created,
  1082. IsRTL: isRTL,
  1083. Language: lang,
  1084. OwnerID: ownerID.Int64,
  1085. Found: true,
  1086. Gone: content == "",
  1087. Views: views,
  1088. }
  1089. }
  1090. func isRaw(r *http.Request) bool {
  1091. vars := mux.Vars(r)
  1092. slug := vars["slug"]
  1093. // NOTE: until this is done better, be sure to keep this in parity with
  1094. // isRaw in viewCollectionPost() and handleViewPost()
  1095. isJSON := strings.HasSuffix(slug, ".json")
  1096. isXML := strings.HasSuffix(slug, ".xml")
  1097. isMarkdown := strings.HasSuffix(slug, ".md")
  1098. return strings.HasSuffix(slug, ".txt") || isJSON || isXML || isMarkdown
  1099. }
  1100. func viewCollectionPost(app *App, w http.ResponseWriter, r *http.Request) error {
  1101. vars := mux.Vars(r)
  1102. slug := vars["slug"]
  1103. // NOTE: until this is done better, be sure to keep this in parity with
  1104. // isRaw() and handleViewPost()
  1105. isJSON := strings.HasSuffix(slug, ".json")
  1106. isXML := strings.HasSuffix(slug, ".xml")
  1107. isMarkdown := strings.HasSuffix(slug, ".md")
  1108. isRaw := strings.HasSuffix(slug, ".txt") || isJSON || isXML || isMarkdown
  1109. cr := &collectionReq{}
  1110. err := processCollectionRequest(cr, vars, w, r)
  1111. if err != nil {
  1112. return err
  1113. }
  1114. // Check for hellbanned users
  1115. u, err := checkUserForCollection(app, cr, r, true)
  1116. if err != nil {
  1117. return err
  1118. }
  1119. // Normalize the URL, redirecting user to consistent post URL
  1120. if slug != strings.ToLower(slug) {
  1121. loc := fmt.Sprintf("/%s", strings.ToLower(slug))
  1122. if !app.cfg.App.SingleUser {
  1123. loc = "/" + cr.alias + loc
  1124. }
  1125. return impart.HTTPError{http.StatusMovedPermanently, loc}
  1126. }
  1127. // Display collection if this is a collection
  1128. var c *Collection
  1129. if app.cfg.App.SingleUser {
  1130. c, err = app.db.GetCollectionByID(1)
  1131. } else {
  1132. c, err = app.db.GetCollection(cr.alias)
  1133. }
  1134. if err != nil {
  1135. if err, ok := err.(impart.HTTPError); ok {
  1136. if err.Status == http.StatusNotFound {
  1137. // Redirect if necessary
  1138. newAlias := app.db.GetCollectionRedirect(cr.alias)
  1139. if newAlias != "" {
  1140. return impart.HTTPError{http.StatusFound, "/" + newAlias + "/" + slug}
  1141. }
  1142. }
  1143. }
  1144. return err
  1145. }
  1146. c.hostName = app.cfg.App.Host
  1147. // Check collection permissions
  1148. if c.IsPrivate() && (u == nil || u.ID != c.OwnerID) {
  1149. return ErrPostNotFound
  1150. }
  1151. if c.IsProtected() && ((u == nil || u.ID != c.OwnerID) && !isAuthorizedForCollection(app, c.Alias, r)) {
  1152. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "/?g=" + slug}
  1153. }
  1154. cr.isCollOwner = u != nil && c.OwnerID == u.ID
  1155. if isRaw {
  1156. slug = strings.Split(slug, ".")[0]
  1157. }
  1158. // Fetch extra data about the Collection
  1159. // TODO: refactor out this logic, shared in collection.go:fetchCollection()
  1160. coll := &CollectionObj{Collection: *c}
  1161. owner, err := app.db.GetUserByID(coll.OwnerID)
  1162. if err != nil {
  1163. // Log the error and just continue
  1164. log.Error("Error getting user for collection: %v", err)
  1165. } else {
  1166. coll.Owner = owner
  1167. }
  1168. p, err := app.db.GetPost(slug, coll.ID)
  1169. if err != nil {
  1170. if err == ErrCollectionPageNotFound && slug == "feed" {
  1171. // User tried to access blog feed without a trailing slash, and
  1172. // there's no post with a slug "feed"
  1173. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "/feed/"}
  1174. }
  1175. return err
  1176. }
  1177. p.IsOwner = owner != nil && p.OwnerID.Valid && owner.ID == p.OwnerID.Int64
  1178. p.Collection = coll
  1179. p.IsTopLevel = app.cfg.App.SingleUser
  1180. // Check if post has been unpublished
  1181. if p.Content == "" && p.Title.String == "" {
  1182. return impart.HTTPError{http.StatusGone, "Post was unpublished."}
  1183. }
  1184. // Serve collection post
  1185. if isRaw {
  1186. contentType := "text/plain"
  1187. if isJSON {
  1188. contentType = "application/json"
  1189. } else if isXML {
  1190. contentType = "application/xml"
  1191. } else if isMarkdown {
  1192. contentType = "text/markdown"
  1193. }
  1194. w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType))
  1195. if isMarkdown && p.Title.String != "" {
  1196. fmt.Fprintf(w, "# %s\n\n", p.Title.String)
  1197. }
  1198. fmt.Fprint(w, p.Content)
  1199. } else if strings.Contains(r.Header.Get("Accept"), "application/activity+json") {
  1200. p.extractData()
  1201. ap := p.ActivityObject(app.cfg)
  1202. ap.Context = []interface{}{activitystreams.Namespace}
  1203. return impart.RenderActivityJSON(w, ap, http.StatusOK)
  1204. } else {
  1205. p.extractData()
  1206. p.Content = strings.Replace(p.Content, "<!--more-->", "", 1)
  1207. // TODO: move this to function
  1208. p.formatContent(app.cfg, cr.isCollOwner)
  1209. tp := struct {
  1210. *PublicPost
  1211. page.StaticPage
  1212. IsOwner bool
  1213. IsPinned bool
  1214. IsCustomDomain bool
  1215. PinnedPosts *[]PublicPost
  1216. IsAdmin bool
  1217. CanInvite bool
  1218. }{
  1219. PublicPost: p,
  1220. StaticPage: pageForReq(app, r),
  1221. IsOwner: cr.isCollOwner,
  1222. IsCustomDomain: cr.isCustomDomain,
  1223. }
  1224. tp.IsAdmin = u != nil && u.IsAdmin()
  1225. tp.CanInvite = canUserInvite(app.cfg, tp.IsAdmin)
  1226. tp.PinnedPosts, _ = app.db.GetPinnedPosts(coll)
  1227. tp.IsPinned = len(*tp.PinnedPosts) > 0 && PostsContains(tp.PinnedPosts, p)
  1228. postTmpl := "collection-post"
  1229. if app.cfg.App.Chorus {
  1230. postTmpl = "chorus-collection-post"
  1231. }
  1232. if err := templates[postTmpl].ExecuteTemplate(w, "post", tp); err != nil {
  1233. log.Error("Error in collection-post template: %v", err)
  1234. }
  1235. }
  1236. go func() {
  1237. if p.OwnerID.Valid {
  1238. // Post is owned by someone. Don't update stats if owner is viewing the post.
  1239. if u != nil && p.OwnerID.Int64 == u.ID {
  1240. return
  1241. }
  1242. }
  1243. // Update stats for non-raw post views
  1244. if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) {
  1245. _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE slug = ? AND collection_id = ?", slug, coll.ID)
  1246. if err != nil {
  1247. log.Error("Unable to update posts count: %v", err)
  1248. }
  1249. }
  1250. }()
  1251. return nil
  1252. }
  1253. // TODO: move this to utils after making it more generic
  1254. func PostsContains(sl *[]PublicPost, s *PublicPost) bool {
  1255. for _, e := range *sl {
  1256. if e.ID == s.ID {
  1257. return true
  1258. }
  1259. }
  1260. return false
  1261. }
  1262. func (p *Post) extractData() {
  1263. p.Tags = tags.Extract(p.Content)
  1264. p.extractImages()
  1265. }
  1266. func (rp *RawPost) UserFacingCreated() string {
  1267. return rp.Created.Format(postMetaDateFormat)
  1268. }
  1269. func (rp *RawPost) Created8601() string {
  1270. return rp.Created.Format("2006-01-02T15:04:05Z")
  1271. }
  1272. var imageURLRegex = regexp.MustCompile(`(?i)^https?:\/\/[^ ]*\.(gif|png|jpg|jpeg|image)$`)
  1273. func (p *Post) extractImages() {
  1274. matches := extract.ExtractUrls(p.Content)
  1275. urls := map[string]bool{}
  1276. for i := range matches {
  1277. u := matches[i].Text
  1278. if !imageURLRegex.MatchString(u) {
  1279. continue
  1280. }
  1281. urls[u] = true
  1282. }
  1283. resURLs := make([]string, 0)
  1284. for k := range urls {
  1285. resURLs = append(resURLs, k)
  1286. }
  1287. p.Images = resURLs
  1288. }