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.
 
 
 
 
 

1091 regels
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. if reqJSON && !c.Web {
  336. accessToken = r.Header.Get("Authorization")
  337. if accessToken == "" {
  338. return ErrNoAccessToken
  339. }
  340. userID = app.db.GetUserID(accessToken)
  341. if userID == -1 {
  342. return ErrBadAccessToken
  343. }
  344. } else {
  345. u = getUserSession(app, r)
  346. if u == nil {
  347. return ErrNotLoggedIn
  348. }
  349. userID = u.ID
  350. }
  351. if !author.IsValidUsername(app.cfg, c.Alias) {
  352. return impart.HTTPError{http.StatusPreconditionFailed, "Collection alias isn't valid."}
  353. }
  354. coll, err := app.db.CreateCollection(app.cfg, c.Alias, c.Title, userID)
  355. if err != nil {
  356. // TODO: handle this
  357. return err
  358. }
  359. res := &CollectionObj{Collection: *coll}
  360. if reqJSON {
  361. return impart.WriteSuccess(w, res, http.StatusCreated)
  362. }
  363. redirectTo := "/me/c/"
  364. // TODO: redirect to pad when necessary
  365. return impart.HTTPError{http.StatusFound, redirectTo}
  366. }
  367. func apiCheckCollectionPermissions(app *App, r *http.Request, c *Collection) (int64, error) {
  368. accessToken := r.Header.Get("Authorization")
  369. var userID int64 = -1
  370. if accessToken != "" {
  371. userID = app.db.GetUserID(accessToken)
  372. }
  373. isCollOwner := userID == c.OwnerID
  374. if c.IsPrivate() && !isCollOwner {
  375. // Collection is private, but user isn't authenticated
  376. return -1, ErrCollectionNotFound
  377. }
  378. if c.IsProtected() {
  379. // TODO: check access token
  380. return -1, ErrCollectionUnauthorizedRead
  381. }
  382. return userID, nil
  383. }
  384. // fetchCollection handles the API endpoint for retrieving collection data.
  385. func fetchCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  386. accept := r.Header.Get("Accept")
  387. if strings.Contains(accept, "application/activity+json") {
  388. return handleFetchCollectionActivities(app, w, r)
  389. }
  390. vars := mux.Vars(r)
  391. alias := vars["alias"]
  392. // TODO: move this logic into a common getCollection function
  393. // Get base Collection data
  394. c, err := app.db.GetCollection(alias)
  395. if err != nil {
  396. return err
  397. }
  398. c.hostName = app.cfg.App.Host
  399. // Redirect users who aren't requesting JSON
  400. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  401. if !reqJSON {
  402. return impart.HTTPError{http.StatusFound, c.CanonicalURL()}
  403. }
  404. // Check permissions
  405. userID, err := apiCheckCollectionPermissions(app, r, c)
  406. if err != nil {
  407. return err
  408. }
  409. isCollOwner := userID == c.OwnerID
  410. // Fetch extra data about the Collection
  411. res := &CollectionObj{Collection: *c}
  412. if c.PublicOwner {
  413. u, err := app.db.GetUserByID(res.OwnerID)
  414. if err != nil {
  415. // Log the error and just continue
  416. log.Error("Error getting user for collection: %v", err)
  417. } else {
  418. res.Owner = u
  419. }
  420. }
  421. app.db.GetPostsCount(res, isCollOwner)
  422. // Strip non-public information
  423. res.Collection.ForPublic()
  424. return impart.WriteSuccess(w, res, http.StatusOK)
  425. }
  426. // fetchCollectionPosts handles an API endpoint for retrieving a collection's
  427. // posts.
  428. func fetchCollectionPosts(app *App, w http.ResponseWriter, r *http.Request) error {
  429. vars := mux.Vars(r)
  430. alias := vars["alias"]
  431. c, err := app.db.GetCollection(alias)
  432. if err != nil {
  433. return err
  434. }
  435. c.hostName = app.cfg.App.Host
  436. // Check permissions
  437. userID, err := apiCheckCollectionPermissions(app, r, c)
  438. if err != nil {
  439. return err
  440. }
  441. isCollOwner := userID == c.OwnerID
  442. // Get page
  443. page := 1
  444. if p := r.FormValue("page"); p != "" {
  445. pInt, _ := strconv.Atoi(p)
  446. if pInt > 0 {
  447. page = pInt
  448. }
  449. }
  450. posts, err := app.db.GetPosts(app.cfg, c, page, isCollOwner, false, false)
  451. if err != nil {
  452. return err
  453. }
  454. coll := &CollectionObj{Collection: *c, Posts: posts}
  455. app.db.GetPostsCount(coll, isCollOwner)
  456. // Strip non-public information
  457. coll.Collection.ForPublic()
  458. // Transform post bodies if needed
  459. if r.FormValue("body") == "html" {
  460. for _, p := range *coll.Posts {
  461. p.Content = waposts.ApplyMarkdown([]byte(p.Content))
  462. }
  463. }
  464. return impart.WriteSuccess(w, coll, http.StatusOK)
  465. }
  466. type CollectionPage struct {
  467. page.StaticPage
  468. *DisplayCollection
  469. IsCustomDomain bool
  470. IsWelcome bool
  471. IsOwner bool
  472. CanPin bool
  473. Username string
  474. Collections *[]Collection
  475. PinnedPosts *[]PublicPost
  476. IsAdmin bool
  477. CanInvite bool
  478. }
  479. func (c *CollectionObj) ScriptDisplay() template.JS {
  480. return template.JS(c.Script)
  481. }
  482. var jsSourceCommentReg = regexp.MustCompile("(?m)^// src:(.+)$")
  483. func (c *CollectionObj) ExternalScripts() []template.URL {
  484. scripts := []template.URL{}
  485. if c.Script == "" {
  486. return scripts
  487. }
  488. matches := jsSourceCommentReg.FindAllStringSubmatch(c.Script, -1)
  489. for _, m := range matches {
  490. scripts = append(scripts, template.URL(strings.TrimSpace(m[1])))
  491. }
  492. return scripts
  493. }
  494. func (c *CollectionObj) CanShowScript() bool {
  495. return false
  496. }
  497. func processCollectionRequest(cr *collectionReq, vars map[string]string, w http.ResponseWriter, r *http.Request) error {
  498. cr.prefix = vars["prefix"]
  499. cr.alias = vars["collection"]
  500. // Normalize the URL, redirecting user to consistent post URL
  501. if cr.alias != strings.ToLower(cr.alias) {
  502. return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s/", strings.ToLower(cr.alias))}
  503. }
  504. return nil
  505. }
  506. // processCollectionPermissions checks the permissions for the given
  507. // collectionReq, returning a Collection if access is granted; otherwise this
  508. // renders any necessary collection pages, for example, if requesting a custom
  509. // domain that doesn't yet have a collection associated, or if a collection
  510. // requires a password. In either case, this will return nil, nil -- thus both
  511. // values should ALWAYS be checked to determine whether or not to continue.
  512. func processCollectionPermissions(app *App, cr *collectionReq, u *User, w http.ResponseWriter, r *http.Request) (*Collection, error) {
  513. // Display collection if this is a collection
  514. var c *Collection
  515. var err error
  516. if app.cfg.App.SingleUser {
  517. c, err = app.db.GetCollectionByID(1)
  518. } else {
  519. c, err = app.db.GetCollection(cr.alias)
  520. }
  521. // TODO: verify we don't reveal the existence of a private collection with redirection
  522. if err != nil {
  523. if err, ok := err.(impart.HTTPError); ok {
  524. if err.Status == http.StatusNotFound {
  525. if cr.isCustomDomain {
  526. // User is on the site from a custom domain
  527. //tErr := pages["404-domain.tmpl"].ExecuteTemplate(w, "base", pageForHost(page.StaticPage{}, r))
  528. //if tErr != nil {
  529. //log.Error("Unable to render 404-domain page: %v", err)
  530. //}
  531. return nil, nil
  532. }
  533. if len(cr.alias) >= minIDLen && len(cr.alias) <= maxIDLen {
  534. // Alias is within post ID range, so just be sure this isn't a post
  535. if app.db.PostIDExists(cr.alias) {
  536. // TODO: use StatusFound for vanity post URLs when we implement them
  537. return nil, impart.HTTPError{http.StatusMovedPermanently, "/" + cr.alias}
  538. }
  539. }
  540. // Redirect if necessary
  541. newAlias := app.db.GetCollectionRedirect(cr.alias)
  542. if newAlias != "" {
  543. return nil, impart.HTTPError{http.StatusFound, "/" + newAlias + "/"}
  544. }
  545. }
  546. }
  547. return nil, err
  548. }
  549. c.hostName = app.cfg.App.Host
  550. // Update CollectionRequest to reflect owner status
  551. cr.isCollOwner = u != nil && u.ID == c.OwnerID
  552. // Check permissions
  553. if !cr.isCollOwner {
  554. if c.IsPrivate() {
  555. return nil, ErrCollectionNotFound
  556. } else if c.IsProtected() {
  557. uname := ""
  558. if u != nil {
  559. uname = u.Username
  560. }
  561. // See if we've authorized this collection
  562. authd := isAuthorizedForCollection(app, c.Alias, r)
  563. if !authd {
  564. p := struct {
  565. page.StaticPage
  566. *CollectionObj
  567. Username string
  568. Next string
  569. Flashes []template.HTML
  570. }{
  571. StaticPage: pageForReq(app, r),
  572. CollectionObj: &CollectionObj{Collection: *c},
  573. Username: uname,
  574. Next: r.FormValue("g"),
  575. Flashes: []template.HTML{},
  576. }
  577. // Get owner information
  578. p.CollectionObj.Owner, err = app.db.GetUserByID(c.OwnerID)
  579. if err != nil {
  580. // Log the error and just continue
  581. log.Error("Error getting user for collection: %v", err)
  582. }
  583. flashes, _ := getSessionFlashes(app, w, r, nil)
  584. for _, flash := range flashes {
  585. p.Flashes = append(p.Flashes, template.HTML(flash))
  586. }
  587. err = templates["password-collection"].ExecuteTemplate(w, "password-collection", p)
  588. if err != nil {
  589. log.Error("Unable to render password-collection: %v", err)
  590. return nil, err
  591. }
  592. return nil, nil
  593. }
  594. }
  595. }
  596. return c, nil
  597. }
  598. func checkUserForCollection(app *App, cr *collectionReq, r *http.Request, isPostReq bool) (*User, error) {
  599. u := getUserSession(app, r)
  600. return u, nil
  601. }
  602. func newDisplayCollection(c *Collection, cr *collectionReq, page int) *DisplayCollection {
  603. coll := &DisplayCollection{
  604. CollectionObj: &CollectionObj{Collection: *c},
  605. CurrentPage: page,
  606. Prefix: cr.prefix,
  607. IsTopLevel: isSingleUser,
  608. Format: c.NewFormat(),
  609. }
  610. c.db.GetPostsCount(coll.CollectionObj, cr.isCollOwner)
  611. return coll
  612. }
  613. func getCollectionPage(vars map[string]string) int {
  614. page := 1
  615. var p int
  616. p, _ = strconv.Atoi(vars["page"])
  617. if p > 0 {
  618. page = p
  619. }
  620. return page
  621. }
  622. // handleViewCollection displays the requested Collection
  623. func handleViewCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  624. vars := mux.Vars(r)
  625. cr := &collectionReq{}
  626. err := processCollectionRequest(cr, vars, w, r)
  627. if err != nil {
  628. return err
  629. }
  630. u, err := checkUserForCollection(app, cr, r, false)
  631. if err != nil {
  632. return err
  633. }
  634. page := getCollectionPage(vars)
  635. c, err := processCollectionPermissions(app, cr, u, w, r)
  636. if c == nil || err != nil {
  637. return err
  638. }
  639. c.hostName = app.cfg.App.Host
  640. // Serve ActivityStreams data now, if requested
  641. if strings.Contains(r.Header.Get("Accept"), "application/activity+json") {
  642. ac := c.PersonObject()
  643. ac.Context = []interface{}{activitystreams.Namespace}
  644. return impart.RenderActivityJSON(w, ac, http.StatusOK)
  645. }
  646. // Fetch extra data about the Collection
  647. // TODO: refactor out this logic, shared in collection.go:fetchCollection()
  648. coll := newDisplayCollection(c, cr, page)
  649. coll.TotalPages = int(math.Ceil(float64(coll.TotalPosts) / float64(coll.Format.PostsPerPage())))
  650. if coll.TotalPages > 0 && page > coll.TotalPages {
  651. redirURL := fmt.Sprintf("/page/%d", coll.TotalPages)
  652. if !app.cfg.App.SingleUser {
  653. redirURL = fmt.Sprintf("/%s%s%s", cr.prefix, coll.Alias, redirURL)
  654. }
  655. return impart.HTTPError{http.StatusFound, redirURL}
  656. }
  657. coll.Posts, _ = app.db.GetPosts(app.cfg, c, page, cr.isCollOwner, false, false)
  658. // Serve collection
  659. displayPage := CollectionPage{
  660. DisplayCollection: coll,
  661. StaticPage: pageForReq(app, r),
  662. IsCustomDomain: cr.isCustomDomain,
  663. IsWelcome: r.FormValue("greeting") != "",
  664. }
  665. displayPage.IsAdmin = u != nil && u.IsAdmin()
  666. displayPage.CanInvite = canUserInvite(app.cfg, displayPage.IsAdmin)
  667. var owner *User
  668. if u != nil {
  669. displayPage.Username = u.Username
  670. displayPage.IsOwner = u.ID == coll.OwnerID
  671. if displayPage.IsOwner {
  672. // Add in needed information for users viewing their own collection
  673. owner = u
  674. displayPage.CanPin = true
  675. pubColls, err := app.db.GetPublishableCollections(owner, app.cfg.App.Host)
  676. if err != nil {
  677. log.Error("unable to fetch collections: %v", err)
  678. }
  679. displayPage.Collections = pubColls
  680. }
  681. }
  682. isOwner := owner != nil
  683. if !isOwner {
  684. // Current user doesn't own collection; retrieve owner information
  685. owner, err = app.db.GetUserByID(coll.OwnerID)
  686. if err != nil {
  687. // Log the error and just continue
  688. log.Error("Error getting user for collection: %v", err)
  689. }
  690. }
  691. displayPage.Owner = owner
  692. coll.Owner = displayPage.Owner
  693. // Add more data
  694. // TODO: fix this mess of collections inside collections
  695. displayPage.PinnedPosts, _ = app.db.GetPinnedPosts(coll.CollectionObj, isOwner)
  696. collTmpl := "collection"
  697. if app.cfg.App.Chorus {
  698. collTmpl = "chorus-collection"
  699. }
  700. err = templates[collTmpl].ExecuteTemplate(w, "collection", displayPage)
  701. if err != nil {
  702. log.Error("Unable to render collection index: %v", err)
  703. }
  704. // Update collection view count
  705. go func() {
  706. // Don't update if owner is viewing the collection.
  707. if u != nil && u.ID == coll.OwnerID {
  708. return
  709. }
  710. // Only update for human views
  711. if r.Method == "HEAD" || bots.IsBot(r.UserAgent()) {
  712. return
  713. }
  714. _, err := app.db.Exec("UPDATE collections SET view_count = view_count + 1 WHERE id = ?", coll.ID)
  715. if err != nil {
  716. log.Error("Unable to update collections count: %v", err)
  717. }
  718. }()
  719. return err
  720. }
  721. func handleViewCollectionTag(app *App, w http.ResponseWriter, r *http.Request) error {
  722. vars := mux.Vars(r)
  723. tag := vars["tag"]
  724. cr := &collectionReq{}
  725. err := processCollectionRequest(cr, vars, w, r)
  726. if err != nil {
  727. return err
  728. }
  729. u, err := checkUserForCollection(app, cr, r, false)
  730. if err != nil {
  731. return err
  732. }
  733. page := getCollectionPage(vars)
  734. c, err := processCollectionPermissions(app, cr, u, w, r)
  735. if c == nil || err != nil {
  736. return err
  737. }
  738. coll := newDisplayCollection(c, cr, page)
  739. coll.Posts, _ = app.db.GetPostsTagged(app.cfg, c, tag, page, cr.isCollOwner)
  740. if coll.Posts != nil && len(*coll.Posts) == 0 {
  741. return ErrCollectionPageNotFound
  742. }
  743. // Serve collection
  744. displayPage := struct {
  745. CollectionPage
  746. Tag string
  747. }{
  748. CollectionPage: CollectionPage{
  749. DisplayCollection: coll,
  750. StaticPage: pageForReq(app, r),
  751. IsCustomDomain: cr.isCustomDomain,
  752. },
  753. Tag: tag,
  754. }
  755. var owner *User
  756. if u != nil {
  757. displayPage.Username = u.Username
  758. displayPage.IsOwner = u.ID == coll.OwnerID
  759. if displayPage.IsOwner {
  760. // Add in needed information for users viewing their own collection
  761. owner = u
  762. displayPage.CanPin = true
  763. pubColls, err := app.db.GetPublishableCollections(owner, app.cfg.App.Host)
  764. if err != nil {
  765. log.Error("unable to fetch collections: %v", err)
  766. }
  767. displayPage.Collections = pubColls
  768. }
  769. }
  770. isOwner := owner != nil
  771. if !isOwner {
  772. // Current user doesn't own collection; retrieve owner information
  773. owner, err = app.db.GetUserByID(coll.OwnerID)
  774. if err != nil {
  775. // Log the error and just continue
  776. log.Error("Error getting user for collection: %v", err)
  777. }
  778. }
  779. displayPage.Owner = owner
  780. coll.Owner = displayPage.Owner
  781. // Add more data
  782. // TODO: fix this mess of collections inside collections
  783. displayPage.PinnedPosts, _ = app.db.GetPinnedPosts(coll.CollectionObj, isOwner)
  784. err = templates["collection-tags"].ExecuteTemplate(w, "collection-tags", displayPage)
  785. if err != nil {
  786. log.Error("Unable to render collection tag page: %v", err)
  787. }
  788. return nil
  789. }
  790. func handleCollectionPostRedirect(app *App, w http.ResponseWriter, r *http.Request) error {
  791. vars := mux.Vars(r)
  792. slug := vars["slug"]
  793. cr := &collectionReq{}
  794. err := processCollectionRequest(cr, vars, w, r)
  795. if err != nil {
  796. return err
  797. }
  798. // Normalize the URL, redirecting user to consistent post URL
  799. loc := fmt.Sprintf("/%s", slug)
  800. if !app.cfg.App.SingleUser {
  801. loc = fmt.Sprintf("/%s/%s", cr.alias, slug)
  802. }
  803. return impart.HTTPError{http.StatusFound, loc}
  804. }
  805. func existingCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  806. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  807. vars := mux.Vars(r)
  808. collAlias := vars["alias"]
  809. isWeb := r.FormValue("web") == "1"
  810. var u *User
  811. if reqJSON && !isWeb {
  812. // Ensure an access token was given
  813. accessToken := r.Header.Get("Authorization")
  814. u = &User{}
  815. u.ID = app.db.GetUserID(accessToken)
  816. if u.ID == -1 {
  817. return ErrBadAccessToken
  818. }
  819. } else {
  820. u = getUserSession(app, r)
  821. if u == nil {
  822. return ErrNotLoggedIn
  823. }
  824. }
  825. if r.Method == "DELETE" {
  826. err := app.db.DeleteCollection(collAlias, u.ID)
  827. if err != nil {
  828. // TODO: if not HTTPError, report error to admin
  829. log.Error("Unable to delete collection: %s", err)
  830. return err
  831. }
  832. addSessionFlash(app, w, r, "Deleted your blog, "+collAlias+".", nil)
  833. return impart.HTTPError{Status: http.StatusNoContent}
  834. }
  835. c := SubmittedCollection{OwnerID: uint64(u.ID)}
  836. var err error
  837. if reqJSON {
  838. // Decode JSON request
  839. decoder := json.NewDecoder(r.Body)
  840. err = decoder.Decode(&c)
  841. if err != nil {
  842. log.Error("Couldn't parse collection update JSON request: %v\n", err)
  843. return ErrBadJSON
  844. }
  845. } else {
  846. err = r.ParseForm()
  847. if err != nil {
  848. log.Error("Couldn't parse collection update form request: %v\n", err)
  849. return ErrBadFormData
  850. }
  851. err = app.formDecoder.Decode(&c, r.PostForm)
  852. if err != nil {
  853. log.Error("Couldn't decode collection update form request: %v\n", err)
  854. return ErrBadFormData
  855. }
  856. }
  857. err = app.db.UpdateCollection(&c, collAlias)
  858. if err != nil {
  859. if err, ok := err.(impart.HTTPError); ok {
  860. if reqJSON {
  861. return err
  862. }
  863. addSessionFlash(app, w, r, err.Message, nil)
  864. return impart.HTTPError{http.StatusFound, "/me/c/" + collAlias}
  865. } else {
  866. log.Error("Couldn't update collection: %v\n", err)
  867. return err
  868. }
  869. }
  870. if reqJSON {
  871. return impart.WriteSuccess(w, struct {
  872. }{}, http.StatusOK)
  873. }
  874. addSessionFlash(app, w, r, "Blog updated!", nil)
  875. return impart.HTTPError{http.StatusFound, "/me/c/" + collAlias}
  876. }
  877. // collectionAliasFromReq takes a request and returns the collection alias
  878. // if it can be ascertained, as well as whether or not the collection uses a
  879. // custom domain.
  880. func collectionAliasFromReq(r *http.Request) string {
  881. vars := mux.Vars(r)
  882. alias := vars["subdomain"]
  883. isSubdomain := alias != ""
  884. if !isSubdomain {
  885. // Fall back to write.as/{collection} since this isn't a custom domain
  886. alias = vars["collection"]
  887. }
  888. return alias
  889. }
  890. func handleWebCollectionUnlock(app *App, w http.ResponseWriter, r *http.Request) error {
  891. var readReq struct {
  892. Alias string `schema:"alias" json:"alias"`
  893. Pass string `schema:"password" json:"password"`
  894. Next string `schema:"to" json:"to"`
  895. }
  896. // Get params
  897. if impart.ReqJSON(r) {
  898. decoder := json.NewDecoder(r.Body)
  899. err := decoder.Decode(&readReq)
  900. if err != nil {
  901. log.Error("Couldn't parse readReq JSON request: %v\n", err)
  902. return ErrBadJSON
  903. }
  904. } else {
  905. err := r.ParseForm()
  906. if err != nil {
  907. log.Error("Couldn't parse readReq form request: %v\n", err)
  908. return ErrBadFormData
  909. }
  910. err = app.formDecoder.Decode(&readReq, r.PostForm)
  911. if err != nil {
  912. log.Error("Couldn't decode readReq form request: %v\n", err)
  913. return ErrBadFormData
  914. }
  915. }
  916. if readReq.Alias == "" {
  917. return impart.HTTPError{http.StatusBadRequest, "Need a collection `alias` to read."}
  918. }
  919. if readReq.Pass == "" {
  920. return impart.HTTPError{http.StatusBadRequest, "Please supply a password."}
  921. }
  922. var collHashedPass []byte
  923. err := app.db.QueryRow("SELECT password FROM collectionpasswords INNER JOIN collections ON id = collection_id WHERE alias = ?", readReq.Alias).Scan(&collHashedPass)
  924. if err != nil {
  925. if err == sql.ErrNoRows {
  926. log.Error("No collectionpassword found when trying to read collection %s", readReq.Alias)
  927. return impart.HTTPError{http.StatusInternalServerError, "Something went very wrong. The humans have been alerted."}
  928. }
  929. return err
  930. }
  931. if !auth.Authenticated(collHashedPass, []byte(readReq.Pass)) {
  932. return impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  933. }
  934. // Success; set cookie
  935. session, err := app.sessionStore.Get(r, blogPassCookieName)
  936. if err == nil {
  937. session.Values[readReq.Alias] = true
  938. err = session.Save(r, w)
  939. if err != nil {
  940. log.Error("Didn't save unlocked blog '%s': %v", readReq.Alias, err)
  941. }
  942. }
  943. next := "/" + readReq.Next
  944. if !app.cfg.App.SingleUser {
  945. next = "/" + readReq.Alias + next
  946. }
  947. return impart.HTTPError{http.StatusFound, next}
  948. }
  949. func isAuthorizedForCollection(app *App, alias string, r *http.Request) bool {
  950. authd := false
  951. session, err := app.sessionStore.Get(r, blogPassCookieName)
  952. if err == nil {
  953. _, authd = session.Values[alias]
  954. }
  955. return authd
  956. }