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.
 
 
 
 
 

1213 lines
32 KiB

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