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.
 
 
 
 
 

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