A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 

1063 řádky
28 KiB

  1. /*
  2. * Copyright © 2018 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. "math"
  17. "net/http"
  18. "net/url"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "unicode"
  23. "github.com/gorilla/mux"
  24. "github.com/writeas/impart"
  25. "github.com/writeas/web-core/activitystreams"
  26. "github.com/writeas/web-core/auth"
  27. "github.com/writeas/web-core/bots"
  28. "github.com/writeas/web-core/log"
  29. waposts "github.com/writeas/web-core/posts"
  30. "github.com/writeas/writefreely/author"
  31. "github.com/writeas/writefreely/page"
  32. )
  33. type (
  34. // TODO: add Direction to db
  35. // TODO: add Language to db
  36. Collection struct {
  37. ID int64 `datastore:"id" json:"-"`
  38. Alias string `datastore:"alias" schema:"alias" json:"alias"`
  39. Title string `datastore:"title" schema:"title" json:"title"`
  40. Description string `datastore:"description" schema:"description" json:"description"`
  41. Direction string `schema:"dir" json:"dir,omitempty"`
  42. Language string `schema:"lang" json:"lang,omitempty"`
  43. StyleSheet string `datastore:"style_sheet" schema:"style_sheet" json:"style_sheet"`
  44. Script string `datastore:"script" schema:"script" json:"script,omitempty"`
  45. Public bool `datastore:"public" json:"public"`
  46. Visibility collVisibility `datastore:"private" json:"-"`
  47. Format string `datastore:"format" json:"format,omitempty"`
  48. Views int64 `json:"views"`
  49. OwnerID int64 `datastore:"owner_id" json:"-"`
  50. PublicOwner bool `datastore:"public_owner" json:"-"`
  51. URL string `json:"url,omitempty"`
  52. db *datastore
  53. hostName string
  54. }
  55. CollectionObj struct {
  56. Collection
  57. TotalPosts int `json:"total_posts"`
  58. Owner *User `json:"owner,omitempty"`
  59. Posts *[]PublicPost `json:"posts,omitempty"`
  60. }
  61. DisplayCollection struct {
  62. *CollectionObj
  63. Prefix string
  64. IsTopLevel bool
  65. CurrentPage int
  66. TotalPages int
  67. Format *CollectionFormat
  68. }
  69. SubmittedCollection struct {
  70. // Data used for updating a given collection
  71. ID int64
  72. OwnerID uint64
  73. // Form helpers
  74. PreferURL string `schema:"prefer_url" json:"prefer_url"`
  75. Privacy int `schema:"privacy" json:"privacy"`
  76. Pass string `schema:"password" json:"password"`
  77. MathJax bool `schema:"mathjax" json:"mathjax"`
  78. Handle string `schema:"handle" json:"handle"`
  79. // Actual collection values updated in the DB
  80. Alias *string `schema:"alias" json:"alias"`
  81. Title *string `schema:"title" json:"title"`
  82. Description *string `schema:"description" json:"description"`
  83. StyleSheet *sql.NullString `schema:"style_sheet" json:"style_sheet"`
  84. Script *sql.NullString `schema:"script" json:"script"`
  85. Visibility *int `schema:"visibility" json:"public"`
  86. Format *sql.NullString `schema:"format" json:"format"`
  87. }
  88. CollectionFormat struct {
  89. Format string
  90. }
  91. collectionReq struct {
  92. // Information about the collection request itself
  93. prefix, alias, domain string
  94. isCustomDomain bool
  95. // User-related fields
  96. isCollOwner bool
  97. }
  98. )
  99. func (sc *SubmittedCollection) FediverseHandle() string {
  100. if sc.Handle == "" {
  101. return apCustomHandleDefault
  102. }
  103. return getSlug(sc.Handle, "")
  104. }
  105. // collVisibility represents the visibility level for the collection.
  106. type collVisibility int
  107. // Visibility levels. Values are bitmasks, stored in the database as
  108. // decimal numbers. If adding types, append them to this list. If removing,
  109. // replace the desired visibility with a new value.
  110. const CollUnlisted collVisibility = 0
  111. const (
  112. CollPublic collVisibility = 1 << iota
  113. CollPrivate
  114. CollProtected
  115. )
  116. func (cf *CollectionFormat) Ascending() bool {
  117. return cf.Format == "novel"
  118. }
  119. func (cf *CollectionFormat) ShowDates() bool {
  120. return cf.Format == "blog"
  121. }
  122. func (cf *CollectionFormat) PostsPerPage() int {
  123. if cf.Format == "novel" {
  124. return postsPerPage
  125. }
  126. return postsPerPage
  127. }
  128. // Valid returns whether or not a format value is valid.
  129. func (cf *CollectionFormat) Valid() bool {
  130. return cf.Format == "blog" ||
  131. cf.Format == "novel" ||
  132. cf.Format == "notebook"
  133. }
  134. // NewFormat creates a new CollectionFormat object from the Collection.
  135. func (c *Collection) NewFormat() *CollectionFormat {
  136. cf := &CollectionFormat{Format: c.Format}
  137. // Fill in default format
  138. if cf.Format == "" {
  139. cf.Format = "blog"
  140. }
  141. return cf
  142. }
  143. func (c *Collection) IsUnlisted() bool {
  144. return c.Visibility == 0
  145. }
  146. func (c *Collection) IsPrivate() bool {
  147. return c.Visibility&CollPrivate != 0
  148. }
  149. func (c *Collection) IsProtected() bool {
  150. return c.Visibility&CollProtected != 0
  151. }
  152. func (c *Collection) IsPublic() bool {
  153. return c.Visibility&CollPublic != 0
  154. }
  155. func (c *Collection) FriendlyVisibility() string {
  156. if c.IsPrivate() {
  157. return "Private"
  158. }
  159. if c.IsPublic() {
  160. return "Public"
  161. }
  162. if c.IsProtected() {
  163. return "Password-protected"
  164. }
  165. return "Unlisted"
  166. }
  167. func (c *Collection) ShowFooterBranding() bool {
  168. // TODO: implement this setting
  169. return true
  170. }
  171. // CanonicalURL returns a fully-qualified URL to the collection.
  172. func (c *Collection) CanonicalURL() string {
  173. return c.RedirectingCanonicalURL(false)
  174. }
  175. func (c *Collection) DisplayCanonicalURL() string {
  176. us := c.CanonicalURL()
  177. u, err := url.Parse(us)
  178. if err != nil {
  179. return us
  180. }
  181. p := u.Path
  182. if p == "/" {
  183. p = ""
  184. }
  185. return u.Hostname() + p
  186. }
  187. func (c *Collection) RedirectingCanonicalURL(isRedir bool) string {
  188. if isSingleUser {
  189. return c.hostName + "/"
  190. }
  191. return fmt.Sprintf("%s/%s/", c.hostName, c.Alias)
  192. }
  193. // PrevPageURL provides a full URL for the previous page of collection posts,
  194. // returning a /page/N result for pages >1
  195. func (c *Collection) PrevPageURL(prefix string, n int, tl bool) string {
  196. u := ""
  197. if n == 2 {
  198. // Previous page is 1; no need for /page/ prefix
  199. if prefix == "" {
  200. u = "/"
  201. }
  202. // Else leave off trailing slash
  203. } else {
  204. u = fmt.Sprintf("/page/%d", n-1)
  205. }
  206. if tl {
  207. return u
  208. }
  209. return "/" + prefix + c.Alias + u
  210. }
  211. // NextPageURL provides a full URL for the next page of collection posts
  212. func (c *Collection) NextPageURL(prefix string, n int, tl bool) string {
  213. if tl {
  214. return fmt.Sprintf("/page/%d", n+1)
  215. }
  216. return fmt.Sprintf("/%s%s/page/%d", prefix, c.Alias, n+1)
  217. }
  218. func (c *Collection) DisplayTitle() string {
  219. if c.Title != "" {
  220. return c.Title
  221. }
  222. return c.Alias
  223. }
  224. func (c *Collection) StyleSheetDisplay() template.CSS {
  225. return template.CSS(c.StyleSheet)
  226. }
  227. // ForPublic modifies the Collection for public consumption, such as via
  228. // the API.
  229. func (c *Collection) ForPublic() {
  230. c.URL = c.CanonicalURL()
  231. }
  232. var isAvatarChar = regexp.MustCompile("[a-z0-9]").MatchString
  233. func (c *Collection) PersonObject(ids ...int64) *activitystreams.Person {
  234. accountRoot := c.FederatedAccount()
  235. p := activitystreams.NewPerson(accountRoot)
  236. p.URL = c.CanonicalURL()
  237. uname := c.Alias
  238. p.PreferredUsername = uname
  239. p.Name = c.DisplayTitle()
  240. p.Summary = c.Description
  241. if p.Name != "" {
  242. if av := c.AvatarURL(); av != "" {
  243. p.Icon = activitystreams.Image{
  244. Type: "Image",
  245. MediaType: "image/png",
  246. URL: av,
  247. }
  248. }
  249. }
  250. collID := c.ID
  251. if len(ids) > 0 {
  252. collID = ids[0]
  253. }
  254. pub, priv := c.db.GetAPActorKeys(collID)
  255. if pub != nil {
  256. p.AddPubKey(pub)
  257. p.SetPrivKey(priv)
  258. }
  259. return p
  260. }
  261. func (c *Collection) AvatarURL() string {
  262. fl := string(unicode.ToLower([]rune(c.DisplayTitle())[0]))
  263. if !isAvatarChar(fl) {
  264. return ""
  265. }
  266. return c.hostName + "/img/avatars/" + fl + ".png"
  267. }
  268. func (c *Collection) FederatedAPIBase() string {
  269. return c.hostName + "/"
  270. }
  271. func (c *Collection) FederatedAccount() string {
  272. accountUser := c.Alias
  273. return c.FederatedAPIBase() + "api/collections/" + accountUser
  274. }
  275. func (c *Collection) RenderMathJax() bool {
  276. return c.db.CollectionHasAttribute(c.ID, "render_mathjax")
  277. }
  278. func newCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  279. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  280. alias := r.FormValue("alias")
  281. title := r.FormValue("title")
  282. var missingParams, accessToken string
  283. var u *User
  284. c := struct {
  285. Alias string `json:"alias" schema:"alias"`
  286. Title string `json:"title" schema:"title"`
  287. Web bool `json:"web" schema:"web"`
  288. }{}
  289. if reqJSON {
  290. // Decode JSON request
  291. decoder := json.NewDecoder(r.Body)
  292. err := decoder.Decode(&c)
  293. if err != nil {
  294. log.Error("Couldn't parse post update JSON request: %v\n", err)
  295. return ErrBadJSON
  296. }
  297. } else {
  298. // TODO: move form parsing to formDecoder
  299. c.Alias = alias
  300. c.Title = title
  301. }
  302. if c.Alias == "" {
  303. if c.Title != "" {
  304. // If only a title was given, just use it to generate the alias.
  305. c.Alias = getSlug(c.Title, "")
  306. } else {
  307. missingParams += "`alias` "
  308. }
  309. }
  310. if c.Title == "" {
  311. missingParams += "`title` "
  312. }
  313. if missingParams != "" {
  314. return impart.HTTPError{http.StatusBadRequest, fmt.Sprintf("Parameter(s) %srequired.", missingParams)}
  315. }
  316. if reqJSON && !c.Web {
  317. accessToken = r.Header.Get("Authorization")
  318. if accessToken == "" {
  319. return ErrNoAccessToken
  320. }
  321. } else {
  322. u = getUserSession(app, r)
  323. if u == nil {
  324. return ErrNotLoggedIn
  325. }
  326. }
  327. if !author.IsValidUsername(app.cfg, c.Alias) {
  328. return impart.HTTPError{http.StatusPreconditionFailed, "Collection alias isn't valid."}
  329. }
  330. var coll *Collection
  331. var err error
  332. if accessToken != "" {
  333. coll, err = app.db.CreateCollectionFromToken(c.Alias, c.Title, accessToken)
  334. if err != nil {
  335. // TODO: handle this
  336. return err
  337. }
  338. } else {
  339. coll, err = app.db.CreateCollection(c.Alias, c.Title, u.ID)
  340. if err != nil {
  341. // TODO: handle this
  342. return err
  343. }
  344. }
  345. res := &CollectionObj{Collection: *coll}
  346. if reqJSON {
  347. return impart.WriteSuccess(w, res, http.StatusCreated)
  348. }
  349. redirectTo := "/me/c/"
  350. // TODO: redirect to pad when necessary
  351. return impart.HTTPError{http.StatusFound, redirectTo}
  352. }
  353. func apiCheckCollectionPermissions(app *App, r *http.Request, c *Collection) (int64, error) {
  354. accessToken := r.Header.Get("Authorization")
  355. var userID int64 = -1
  356. if accessToken != "" {
  357. userID = app.db.GetUserID(accessToken)
  358. }
  359. isCollOwner := userID == c.OwnerID
  360. if c.IsPrivate() && !isCollOwner {
  361. // Collection is private, but user isn't authenticated
  362. return -1, ErrCollectionNotFound
  363. }
  364. if c.IsProtected() {
  365. // TODO: check access token
  366. return -1, ErrCollectionUnauthorizedRead
  367. }
  368. return userID, nil
  369. }
  370. // fetchCollection handles the API endpoint for retrieving collection data.
  371. func fetchCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  372. accept := r.Header.Get("Accept")
  373. if strings.Contains(accept, "application/activity+json") {
  374. return handleFetchCollectionActivities(app, w, r)
  375. }
  376. vars := mux.Vars(r)
  377. alias := vars["alias"]
  378. // TODO: move this logic into a common getCollection function
  379. // Get base Collection data
  380. c, err := app.db.GetCollection(alias)
  381. if err != nil {
  382. return err
  383. }
  384. c.hostName = app.cfg.App.Host
  385. // Redirect users who aren't requesting JSON
  386. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  387. if !reqJSON {
  388. return impart.HTTPError{http.StatusFound, c.CanonicalURL()}
  389. }
  390. // Check permissions
  391. userID, err := apiCheckCollectionPermissions(app, r, c)
  392. if err != nil {
  393. return err
  394. }
  395. isCollOwner := userID == c.OwnerID
  396. // Fetch extra data about the Collection
  397. res := &CollectionObj{Collection: *c}
  398. if c.PublicOwner {
  399. u, err := app.db.GetUserByID(res.OwnerID)
  400. if err != nil {
  401. // Log the error and just continue
  402. log.Error("Error getting user for collection: %v", err)
  403. } else {
  404. res.Owner = u
  405. }
  406. }
  407. app.db.GetPostsCount(res, isCollOwner)
  408. // Strip non-public information
  409. res.Collection.ForPublic()
  410. return impart.WriteSuccess(w, res, http.StatusOK)
  411. }
  412. // fetchCollectionPosts handles an API endpoint for retrieving a collection's
  413. // posts.
  414. func fetchCollectionPosts(app *App, w http.ResponseWriter, r *http.Request) error {
  415. vars := mux.Vars(r)
  416. alias := vars["alias"]
  417. c, err := app.db.GetCollection(alias)
  418. if err != nil {
  419. return err
  420. }
  421. c.hostName = app.cfg.App.Host
  422. // Check permissions
  423. userID, err := apiCheckCollectionPermissions(app, r, c)
  424. if err != nil {
  425. return err
  426. }
  427. isCollOwner := userID == c.OwnerID
  428. // Get page
  429. page := 1
  430. if p := r.FormValue("page"); p != "" {
  431. pInt, _ := strconv.Atoi(p)
  432. if pInt > 0 {
  433. page = pInt
  434. }
  435. }
  436. posts, err := app.db.GetPosts(c, page, isCollOwner, false, false)
  437. if err != nil {
  438. return err
  439. }
  440. coll := &CollectionObj{Collection: *c, Posts: posts}
  441. app.db.GetPostsCount(coll, isCollOwner)
  442. // Strip non-public information
  443. coll.Collection.ForPublic()
  444. // Transform post bodies if needed
  445. if r.FormValue("body") == "html" {
  446. for _, p := range *coll.Posts {
  447. p.Content = waposts.ApplyMarkdown([]byte(p.Content))
  448. }
  449. }
  450. return impart.WriteSuccess(w, coll, http.StatusOK)
  451. }
  452. type CollectionPage struct {
  453. page.StaticPage
  454. *DisplayCollection
  455. IsCustomDomain bool
  456. IsWelcome bool
  457. IsOwner bool
  458. CanPin bool
  459. Username string
  460. Collections *[]Collection
  461. PinnedPosts *[]PublicPost
  462. }
  463. func (c *CollectionObj) ScriptDisplay() template.JS {
  464. return template.JS(c.Script)
  465. }
  466. var jsSourceCommentReg = regexp.MustCompile("(?m)^// src:(.+)$")
  467. func (c *CollectionObj) ExternalScripts() []template.URL {
  468. scripts := []template.URL{}
  469. if c.Script == "" {
  470. return scripts
  471. }
  472. matches := jsSourceCommentReg.FindAllStringSubmatch(c.Script, -1)
  473. for _, m := range matches {
  474. scripts = append(scripts, template.URL(strings.TrimSpace(m[1])))
  475. }
  476. return scripts
  477. }
  478. func (c *CollectionObj) CanShowScript() bool {
  479. return false
  480. }
  481. func processCollectionRequest(cr *collectionReq, vars map[string]string, w http.ResponseWriter, r *http.Request) error {
  482. cr.prefix = vars["prefix"]
  483. cr.alias = vars["collection"]
  484. // Normalize the URL, redirecting user to consistent post URL
  485. if cr.alias != strings.ToLower(cr.alias) {
  486. return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s/", strings.ToLower(cr.alias))}
  487. }
  488. return nil
  489. }
  490. // processCollectionPermissions checks the permissions for the given
  491. // collectionReq, returning a Collection if access is granted; otherwise this
  492. // renders any necessary collection pages, for example, if requesting a custom
  493. // domain that doesn't yet have a collection associated, or if a collection
  494. // requires a password. In either case, this will return nil, nil -- thus both
  495. // values should ALWAYS be checked to determine whether or not to continue.
  496. func processCollectionPermissions(app *App, cr *collectionReq, u *User, w http.ResponseWriter, r *http.Request) (*Collection, error) {
  497. // Display collection if this is a collection
  498. var c *Collection
  499. var err error
  500. if app.cfg.App.SingleUser {
  501. c, err = app.db.GetCollectionByID(1)
  502. } else {
  503. c, err = app.db.GetCollection(cr.alias)
  504. }
  505. // TODO: verify we don't reveal the existence of a private collection with redirection
  506. if err != nil {
  507. if err, ok := err.(impart.HTTPError); ok {
  508. if err.Status == http.StatusNotFound {
  509. if cr.isCustomDomain {
  510. // User is on the site from a custom domain
  511. //tErr := pages["404-domain.tmpl"].ExecuteTemplate(w, "base", pageForHost(page.StaticPage{}, r))
  512. //if tErr != nil {
  513. //log.Error("Unable to render 404-domain page: %v", err)
  514. //}
  515. return nil, nil
  516. }
  517. if len(cr.alias) >= minIDLen && len(cr.alias) <= maxIDLen {
  518. // Alias is within post ID range, so just be sure this isn't a post
  519. if app.db.PostIDExists(cr.alias) {
  520. // TODO: use StatusFound for vanity post URLs when we implement them
  521. return nil, impart.HTTPError{http.StatusMovedPermanently, "/" + cr.alias}
  522. }
  523. }
  524. // Redirect if necessary
  525. newAlias := app.db.GetCollectionRedirect(cr.alias)
  526. if newAlias != "" {
  527. return nil, impart.HTTPError{http.StatusFound, "/" + newAlias + "/"}
  528. }
  529. }
  530. }
  531. return nil, err
  532. }
  533. c.hostName = app.cfg.App.Host
  534. // Update CollectionRequest to reflect owner status
  535. cr.isCollOwner = u != nil && u.ID == c.OwnerID
  536. // Check permissions
  537. if !cr.isCollOwner {
  538. if c.IsPrivate() {
  539. return nil, ErrCollectionNotFound
  540. } else if c.IsProtected() {
  541. uname := ""
  542. if u != nil {
  543. uname = u.Username
  544. }
  545. // See if we've authorized this collection
  546. authd := isAuthorizedForCollection(app, c.Alias, r)
  547. if !authd {
  548. p := struct {
  549. page.StaticPage
  550. *CollectionObj
  551. Username string
  552. Next string
  553. Flashes []template.HTML
  554. }{
  555. StaticPage: pageForReq(app, r),
  556. CollectionObj: &CollectionObj{Collection: *c},
  557. Username: uname,
  558. Next: r.FormValue("g"),
  559. Flashes: []template.HTML{},
  560. }
  561. // Get owner information
  562. p.CollectionObj.Owner, err = app.db.GetUserByID(c.OwnerID)
  563. if err != nil {
  564. // Log the error and just continue
  565. log.Error("Error getting user for collection: %v", err)
  566. }
  567. flashes, _ := getSessionFlashes(app, w, r, nil)
  568. for _, flash := range flashes {
  569. p.Flashes = append(p.Flashes, template.HTML(flash))
  570. }
  571. err = templates["password-collection"].ExecuteTemplate(w, "password-collection", p)
  572. if err != nil {
  573. log.Error("Unable to render password-collection: %v", err)
  574. return nil, err
  575. }
  576. return nil, nil
  577. }
  578. }
  579. }
  580. return c, nil
  581. }
  582. func checkUserForCollection(app *App, cr *collectionReq, r *http.Request, isPostReq bool) (*User, error) {
  583. u := getUserSession(app, r)
  584. return u, nil
  585. }
  586. func newDisplayCollection(c *Collection, cr *collectionReq, page int) *DisplayCollection {
  587. coll := &DisplayCollection{
  588. CollectionObj: &CollectionObj{Collection: *c},
  589. CurrentPage: page,
  590. Prefix: cr.prefix,
  591. IsTopLevel: isSingleUser,
  592. Format: c.NewFormat(),
  593. }
  594. c.db.GetPostsCount(coll.CollectionObj, cr.isCollOwner)
  595. return coll
  596. }
  597. func getCollectionPage(vars map[string]string) int {
  598. page := 1
  599. var p int
  600. p, _ = strconv.Atoi(vars["page"])
  601. if p > 0 {
  602. page = p
  603. }
  604. return page
  605. }
  606. // handleViewCollection displays the requested Collection
  607. func handleViewCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  608. vars := mux.Vars(r)
  609. cr := &collectionReq{}
  610. err := processCollectionRequest(cr, vars, w, r)
  611. if err != nil {
  612. return err
  613. }
  614. u, err := checkUserForCollection(app, cr, r, false)
  615. if err != nil {
  616. return err
  617. }
  618. page := getCollectionPage(vars)
  619. c, err := processCollectionPermissions(app, cr, u, w, r)
  620. if c == nil || err != nil {
  621. return err
  622. }
  623. // Serve ActivityStreams data now, if requested
  624. if strings.Contains(r.Header.Get("Accept"), "application/activity+json") {
  625. ac := c.PersonObject()
  626. ac.Context = []interface{}{activitystreams.Namespace}
  627. return impart.RenderActivityJSON(w, ac, http.StatusOK)
  628. }
  629. // Fetch extra data about the Collection
  630. // TODO: refactor out this logic, shared in collection.go:fetchCollection()
  631. coll := newDisplayCollection(c, cr, page)
  632. coll.TotalPages = int(math.Ceil(float64(coll.TotalPosts) / float64(coll.Format.PostsPerPage())))
  633. if coll.TotalPages > 0 && page > coll.TotalPages {
  634. redirURL := fmt.Sprintf("/page/%d", coll.TotalPages)
  635. if !app.cfg.App.SingleUser {
  636. redirURL = fmt.Sprintf("/%s%s%s", cr.prefix, coll.Alias, redirURL)
  637. }
  638. return impart.HTTPError{http.StatusFound, redirURL}
  639. }
  640. coll.Posts, _ = app.db.GetPosts(c, page, cr.isCollOwner, false, false)
  641. // Serve collection
  642. displayPage := CollectionPage{
  643. DisplayCollection: coll,
  644. StaticPage: pageForReq(app, r),
  645. IsCustomDomain: cr.isCustomDomain,
  646. IsWelcome: r.FormValue("greeting") != "",
  647. }
  648. var owner *User
  649. if u != nil {
  650. displayPage.Username = u.Username
  651. displayPage.IsOwner = u.ID == coll.OwnerID
  652. if displayPage.IsOwner {
  653. // Add in needed information for users viewing their own collection
  654. owner = u
  655. displayPage.CanPin = true
  656. pubColls, err := app.db.GetPublishableCollections(owner)
  657. if err != nil {
  658. log.Error("unable to fetch collections: %v", err)
  659. }
  660. displayPage.Collections = pubColls
  661. }
  662. }
  663. if owner == nil {
  664. // Current user doesn't own collection; retrieve owner information
  665. owner, err = app.db.GetUserByID(coll.OwnerID)
  666. if err != nil {
  667. // Log the error and just continue
  668. log.Error("Error getting user for collection: %v", err)
  669. }
  670. }
  671. displayPage.Owner = owner
  672. coll.Owner = displayPage.Owner
  673. // Add more data
  674. // TODO: fix this mess of collections inside collections
  675. displayPage.PinnedPosts, _ = app.db.GetPinnedPosts(coll.CollectionObj)
  676. err = templates["collection"].ExecuteTemplate(w, "collection", displayPage)
  677. if err != nil {
  678. log.Error("Unable to render collection index: %v", err)
  679. }
  680. // Update collection view count
  681. go func() {
  682. // Don't update if owner is viewing the collection.
  683. if u != nil && u.ID == coll.OwnerID {
  684. return
  685. }
  686. // Only update for human views
  687. if r.Method == "HEAD" || bots.IsBot(r.UserAgent()) {
  688. return
  689. }
  690. _, err := app.db.Exec("UPDATE collections SET view_count = view_count + 1 WHERE id = ?", coll.ID)
  691. if err != nil {
  692. log.Error("Unable to update collections count: %v", err)
  693. }
  694. }()
  695. return err
  696. }
  697. func handleViewCollectionTag(app *App, w http.ResponseWriter, r *http.Request) error {
  698. vars := mux.Vars(r)
  699. tag := vars["tag"]
  700. cr := &collectionReq{}
  701. err := processCollectionRequest(cr, vars, w, r)
  702. if err != nil {
  703. return err
  704. }
  705. u, err := checkUserForCollection(app, cr, r, false)
  706. if err != nil {
  707. return err
  708. }
  709. page := getCollectionPage(vars)
  710. c, err := processCollectionPermissions(app, cr, u, w, r)
  711. if c == nil || err != nil {
  712. return err
  713. }
  714. coll := newDisplayCollection(c, cr, page)
  715. coll.Posts, _ = app.db.GetPostsTagged(c, tag, page, cr.isCollOwner)
  716. if coll.Posts != nil && len(*coll.Posts) == 0 {
  717. return ErrCollectionPageNotFound
  718. }
  719. // Serve collection
  720. displayPage := struct {
  721. CollectionPage
  722. Tag string
  723. }{
  724. CollectionPage: CollectionPage{
  725. DisplayCollection: coll,
  726. StaticPage: pageForReq(app, r),
  727. IsCustomDomain: cr.isCustomDomain,
  728. },
  729. Tag: tag,
  730. }
  731. var owner *User
  732. if u != nil {
  733. displayPage.Username = u.Username
  734. displayPage.IsOwner = u.ID == coll.OwnerID
  735. if displayPage.IsOwner {
  736. // Add in needed information for users viewing their own collection
  737. owner = u
  738. displayPage.CanPin = true
  739. pubColls, err := app.db.GetPublishableCollections(owner)
  740. if err != nil {
  741. log.Error("unable to fetch collections: %v", err)
  742. }
  743. displayPage.Collections = pubColls
  744. }
  745. }
  746. if owner == nil {
  747. // Current user doesn't own collection; retrieve owner information
  748. owner, err = app.db.GetUserByID(coll.OwnerID)
  749. if err != nil {
  750. // Log the error and just continue
  751. log.Error("Error getting user for collection: %v", err)
  752. }
  753. }
  754. displayPage.Owner = owner
  755. coll.Owner = displayPage.Owner
  756. // Add more data
  757. // TODO: fix this mess of collections inside collections
  758. displayPage.PinnedPosts, _ = app.db.GetPinnedPosts(coll.CollectionObj)
  759. err = templates["collection-tags"].ExecuteTemplate(w, "collection-tags", displayPage)
  760. if err != nil {
  761. log.Error("Unable to render collection tag page: %v", err)
  762. }
  763. return nil
  764. }
  765. func handleCollectionPostRedirect(app *App, w http.ResponseWriter, r *http.Request) error {
  766. vars := mux.Vars(r)
  767. slug := vars["slug"]
  768. cr := &collectionReq{}
  769. err := processCollectionRequest(cr, vars, w, r)
  770. if err != nil {
  771. return err
  772. }
  773. // Normalize the URL, redirecting user to consistent post URL
  774. loc := fmt.Sprintf("/%s", slug)
  775. if !app.cfg.App.SingleUser {
  776. loc = fmt.Sprintf("/%s/%s", cr.alias, slug)
  777. }
  778. return impart.HTTPError{http.StatusFound, loc}
  779. }
  780. func existingCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  781. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  782. vars := mux.Vars(r)
  783. collAlias := vars["alias"]
  784. isWeb := r.FormValue("web") == "1"
  785. var u *User
  786. if reqJSON && !isWeb {
  787. // Ensure an access token was given
  788. accessToken := r.Header.Get("Authorization")
  789. u = &User{}
  790. u.ID = app.db.GetUserID(accessToken)
  791. if u.ID == -1 {
  792. return ErrBadAccessToken
  793. }
  794. } else {
  795. u = getUserSession(app, r)
  796. if u == nil {
  797. return ErrNotLoggedIn
  798. }
  799. }
  800. if r.Method == "DELETE" {
  801. err := app.db.DeleteCollection(collAlias, u.ID)
  802. if err != nil {
  803. // TODO: if not HTTPError, report error to admin
  804. log.Error("Unable to delete collection: %s", err)
  805. return err
  806. }
  807. addSessionFlash(app, w, r, "Deleted your blog, "+collAlias+".", nil)
  808. return impart.HTTPError{Status: http.StatusNoContent}
  809. }
  810. c := SubmittedCollection{OwnerID: uint64(u.ID)}
  811. var err error
  812. if reqJSON {
  813. // Decode JSON request
  814. decoder := json.NewDecoder(r.Body)
  815. err = decoder.Decode(&c)
  816. if err != nil {
  817. log.Error("Couldn't parse collection update JSON request: %v\n", err)
  818. return ErrBadJSON
  819. }
  820. } else {
  821. err = r.ParseForm()
  822. if err != nil {
  823. log.Error("Couldn't parse collection update form request: %v\n", err)
  824. return ErrBadFormData
  825. }
  826. err = app.formDecoder.Decode(&c, r.PostForm)
  827. if err != nil {
  828. log.Error("Couldn't decode collection update form request: %v\n", err)
  829. return ErrBadFormData
  830. }
  831. }
  832. err = app.db.UpdateCollection(&c, collAlias)
  833. if err != nil {
  834. if err, ok := err.(impart.HTTPError); ok {
  835. if reqJSON {
  836. return err
  837. }
  838. addSessionFlash(app, w, r, err.Message, nil)
  839. return impart.HTTPError{http.StatusFound, "/me/c/" + collAlias}
  840. } else {
  841. log.Error("Couldn't update collection: %v\n", err)
  842. return err
  843. }
  844. }
  845. if reqJSON {
  846. return impart.WriteSuccess(w, struct {
  847. }{}, http.StatusOK)
  848. }
  849. addSessionFlash(app, w, r, "Blog updated!", nil)
  850. return impart.HTTPError{http.StatusFound, "/me/c/" + collAlias}
  851. }
  852. // collectionAliasFromReq takes a request and returns the collection alias
  853. // if it can be ascertained, as well as whether or not the collection uses a
  854. // custom domain.
  855. func collectionAliasFromReq(r *http.Request) string {
  856. vars := mux.Vars(r)
  857. alias := vars["subdomain"]
  858. isSubdomain := alias != ""
  859. if !isSubdomain {
  860. // Fall back to write.as/{collection} since this isn't a custom domain
  861. alias = vars["collection"]
  862. }
  863. return alias
  864. }
  865. func handleWebCollectionUnlock(app *App, w http.ResponseWriter, r *http.Request) error {
  866. var readReq struct {
  867. Alias string `schema:"alias" json:"alias"`
  868. Pass string `schema:"password" json:"password"`
  869. Next string `schema:"to" json:"to"`
  870. }
  871. // Get params
  872. if impart.ReqJSON(r) {
  873. decoder := json.NewDecoder(r.Body)
  874. err := decoder.Decode(&readReq)
  875. if err != nil {
  876. log.Error("Couldn't parse readReq JSON request: %v\n", err)
  877. return ErrBadJSON
  878. }
  879. } else {
  880. err := r.ParseForm()
  881. if err != nil {
  882. log.Error("Couldn't parse readReq form request: %v\n", err)
  883. return ErrBadFormData
  884. }
  885. err = app.formDecoder.Decode(&readReq, r.PostForm)
  886. if err != nil {
  887. log.Error("Couldn't decode readReq form request: %v\n", err)
  888. return ErrBadFormData
  889. }
  890. }
  891. if readReq.Alias == "" {
  892. return impart.HTTPError{http.StatusBadRequest, "Need a collection `alias` to read."}
  893. }
  894. if readReq.Pass == "" {
  895. return impart.HTTPError{http.StatusBadRequest, "Please supply a password."}
  896. }
  897. var collHashedPass []byte
  898. err := app.db.QueryRow("SELECT password FROM collectionpasswords INNER JOIN collections ON id = collection_id WHERE alias = ?", readReq.Alias).Scan(&collHashedPass)
  899. if err != nil {
  900. if err == sql.ErrNoRows {
  901. log.Error("No collectionpassword found when trying to read collection %s", readReq.Alias)
  902. return impart.HTTPError{http.StatusInternalServerError, "Something went very wrong. The humans have been alerted."}
  903. }
  904. return err
  905. }
  906. if !auth.Authenticated(collHashedPass, []byte(readReq.Pass)) {
  907. return impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  908. }
  909. // Success; set cookie
  910. session, err := app.sessionStore.Get(r, blogPassCookieName)
  911. if err == nil {
  912. session.Values[readReq.Alias] = true
  913. err = session.Save(r, w)
  914. if err != nil {
  915. log.Error("Didn't save unlocked blog '%s': %v", readReq.Alias, err)
  916. }
  917. }
  918. next := "/" + readReq.Next
  919. if !app.cfg.App.SingleUser {
  920. next = "/" + readReq.Alias + next
  921. }
  922. return impart.HTTPError{http.StatusFound, next}
  923. }
  924. func isAuthorizedForCollection(app *App, alias string, r *http.Request) bool {
  925. authd := false
  926. session, err := app.sessionStore.Get(r, blogPassCookieName)
  927. if err == nil {
  928. _, authd = session.Values[alias]
  929. }
  930. return authd
  931. }