A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 

1087 rader
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. // Serve ActivityStreams data now, if requested
  640. if strings.Contains(r.Header.Get("Accept"), "application/activity+json") {
  641. ac := c.PersonObject()
  642. ac.Context = []interface{}{activitystreams.Namespace}
  643. return impart.RenderActivityJSON(w, ac, http.StatusOK)
  644. }
  645. // Fetch extra data about the Collection
  646. // TODO: refactor out this logic, shared in collection.go:fetchCollection()
  647. coll := newDisplayCollection(c, cr, page)
  648. coll.TotalPages = int(math.Ceil(float64(coll.TotalPosts) / float64(coll.Format.PostsPerPage())))
  649. if coll.TotalPages > 0 && page > coll.TotalPages {
  650. redirURL := fmt.Sprintf("/page/%d", coll.TotalPages)
  651. if !app.cfg.App.SingleUser {
  652. redirURL = fmt.Sprintf("/%s%s%s", cr.prefix, coll.Alias, redirURL)
  653. }
  654. return impart.HTTPError{http.StatusFound, redirURL}
  655. }
  656. coll.Posts, _ = app.db.GetPosts(app.cfg, c, page, cr.isCollOwner, false, false)
  657. // Serve collection
  658. displayPage := CollectionPage{
  659. DisplayCollection: coll,
  660. StaticPage: pageForReq(app, r),
  661. IsCustomDomain: cr.isCustomDomain,
  662. IsWelcome: r.FormValue("greeting") != "",
  663. }
  664. displayPage.IsAdmin = u != nil && u.IsAdmin()
  665. displayPage.CanInvite = canUserInvite(app.cfg, displayPage.IsAdmin)
  666. var owner *User
  667. if u != nil {
  668. displayPage.Username = u.Username
  669. displayPage.IsOwner = u.ID == coll.OwnerID
  670. if displayPage.IsOwner {
  671. // Add in needed information for users viewing their own collection
  672. owner = u
  673. displayPage.CanPin = true
  674. pubColls, err := app.db.GetPublishableCollections(owner)
  675. if err != nil {
  676. log.Error("unable to fetch collections: %v", err)
  677. }
  678. displayPage.Collections = pubColls
  679. }
  680. }
  681. if owner == nil {
  682. // Current user doesn't own collection; retrieve owner information
  683. owner, err = app.db.GetUserByID(coll.OwnerID)
  684. if err != nil {
  685. // Log the error and just continue
  686. log.Error("Error getting user for collection: %v", err)
  687. }
  688. }
  689. displayPage.Owner = owner
  690. coll.Owner = displayPage.Owner
  691. // Add more data
  692. // TODO: fix this mess of collections inside collections
  693. displayPage.PinnedPosts, _ = app.db.GetPinnedPosts(coll.CollectionObj)
  694. collTmpl := "collection"
  695. if app.cfg.App.Chorus {
  696. collTmpl = "chorus-collection"
  697. }
  698. err = templates[collTmpl].ExecuteTemplate(w, "collection", displayPage)
  699. if err != nil {
  700. log.Error("Unable to render collection index: %v", err)
  701. }
  702. // Update collection view count
  703. go func() {
  704. // Don't update if owner is viewing the collection.
  705. if u != nil && u.ID == coll.OwnerID {
  706. return
  707. }
  708. // Only update for human views
  709. if r.Method == "HEAD" || bots.IsBot(r.UserAgent()) {
  710. return
  711. }
  712. _, err := app.db.Exec("UPDATE collections SET view_count = view_count + 1 WHERE id = ?", coll.ID)
  713. if err != nil {
  714. log.Error("Unable to update collections count: %v", err)
  715. }
  716. }()
  717. return err
  718. }
  719. func handleViewCollectionTag(app *App, w http.ResponseWriter, r *http.Request) error {
  720. vars := mux.Vars(r)
  721. tag := vars["tag"]
  722. cr := &collectionReq{}
  723. err := processCollectionRequest(cr, vars, w, r)
  724. if err != nil {
  725. return err
  726. }
  727. u, err := checkUserForCollection(app, cr, r, false)
  728. if err != nil {
  729. return err
  730. }
  731. page := getCollectionPage(vars)
  732. c, err := processCollectionPermissions(app, cr, u, w, r)
  733. if c == nil || err != nil {
  734. return err
  735. }
  736. coll := newDisplayCollection(c, cr, page)
  737. coll.Posts, _ = app.db.GetPostsTagged(app.cfg, c, tag, page, cr.isCollOwner)
  738. if coll.Posts != nil && len(*coll.Posts) == 0 {
  739. return ErrCollectionPageNotFound
  740. }
  741. // Serve collection
  742. displayPage := struct {
  743. CollectionPage
  744. Tag string
  745. }{
  746. CollectionPage: CollectionPage{
  747. DisplayCollection: coll,
  748. StaticPage: pageForReq(app, r),
  749. IsCustomDomain: cr.isCustomDomain,
  750. },
  751. Tag: tag,
  752. }
  753. var owner *User
  754. if u != nil {
  755. displayPage.Username = u.Username
  756. displayPage.IsOwner = u.ID == coll.OwnerID
  757. if displayPage.IsOwner {
  758. // Add in needed information for users viewing their own collection
  759. owner = u
  760. displayPage.CanPin = true
  761. pubColls, err := app.db.GetPublishableCollections(owner)
  762. if err != nil {
  763. log.Error("unable to fetch collections: %v", err)
  764. }
  765. displayPage.Collections = pubColls
  766. }
  767. }
  768. if owner == nil {
  769. // Current user doesn't own collection; retrieve owner information
  770. owner, err = app.db.GetUserByID(coll.OwnerID)
  771. if err != nil {
  772. // Log the error and just continue
  773. log.Error("Error getting user for collection: %v", err)
  774. }
  775. }
  776. displayPage.Owner = owner
  777. coll.Owner = displayPage.Owner
  778. // Add more data
  779. // TODO: fix this mess of collections inside collections
  780. displayPage.PinnedPosts, _ = app.db.GetPinnedPosts(coll.CollectionObj)
  781. err = templates["collection-tags"].ExecuteTemplate(w, "collection-tags", displayPage)
  782. if err != nil {
  783. log.Error("Unable to render collection tag page: %v", err)
  784. }
  785. return nil
  786. }
  787. func handleCollectionPostRedirect(app *App, w http.ResponseWriter, r *http.Request) error {
  788. vars := mux.Vars(r)
  789. slug := vars["slug"]
  790. cr := &collectionReq{}
  791. err := processCollectionRequest(cr, vars, w, r)
  792. if err != nil {
  793. return err
  794. }
  795. // Normalize the URL, redirecting user to consistent post URL
  796. loc := fmt.Sprintf("/%s", slug)
  797. if !app.cfg.App.SingleUser {
  798. loc = fmt.Sprintf("/%s/%s", cr.alias, slug)
  799. }
  800. return impart.HTTPError{http.StatusFound, loc}
  801. }
  802. func existingCollection(app *App, w http.ResponseWriter, r *http.Request) error {
  803. reqJSON := IsJSON(r.Header.Get("Content-Type"))
  804. vars := mux.Vars(r)
  805. collAlias := vars["alias"]
  806. isWeb := r.FormValue("web") == "1"
  807. var u *User
  808. if reqJSON && !isWeb {
  809. // Ensure an access token was given
  810. accessToken := r.Header.Get("Authorization")
  811. u = &User{}
  812. u.ID = app.db.GetUserID(accessToken)
  813. if u.ID == -1 {
  814. return ErrBadAccessToken
  815. }
  816. } else {
  817. u = getUserSession(app, r)
  818. if u == nil {
  819. return ErrNotLoggedIn
  820. }
  821. }
  822. if r.Method == "DELETE" {
  823. err := app.db.DeleteCollection(collAlias, u.ID)
  824. if err != nil {
  825. // TODO: if not HTTPError, report error to admin
  826. log.Error("Unable to delete collection: %s", err)
  827. return err
  828. }
  829. addSessionFlash(app, w, r, "Deleted your blog, "+collAlias+".", nil)
  830. return impart.HTTPError{Status: http.StatusNoContent}
  831. }
  832. c := SubmittedCollection{OwnerID: uint64(u.ID)}
  833. var err error
  834. if reqJSON {
  835. // Decode JSON request
  836. decoder := json.NewDecoder(r.Body)
  837. err = decoder.Decode(&c)
  838. if err != nil {
  839. log.Error("Couldn't parse collection update JSON request: %v\n", err)
  840. return ErrBadJSON
  841. }
  842. } else {
  843. err = r.ParseForm()
  844. if err != nil {
  845. log.Error("Couldn't parse collection update form request: %v\n", err)
  846. return ErrBadFormData
  847. }
  848. err = app.formDecoder.Decode(&c, r.PostForm)
  849. if err != nil {
  850. log.Error("Couldn't decode collection update form request: %v\n", err)
  851. return ErrBadFormData
  852. }
  853. }
  854. err = app.db.UpdateCollection(&c, collAlias)
  855. if err != nil {
  856. if err, ok := err.(impart.HTTPError); ok {
  857. if reqJSON {
  858. return err
  859. }
  860. addSessionFlash(app, w, r, err.Message, nil)
  861. return impart.HTTPError{http.StatusFound, "/me/c/" + collAlias}
  862. } else {
  863. log.Error("Couldn't update collection: %v\n", err)
  864. return err
  865. }
  866. }
  867. if reqJSON {
  868. return impart.WriteSuccess(w, struct {
  869. }{}, http.StatusOK)
  870. }
  871. addSessionFlash(app, w, r, "Blog updated!", nil)
  872. return impart.HTTPError{http.StatusFound, "/me/c/" + collAlias}
  873. }
  874. // collectionAliasFromReq takes a request and returns the collection alias
  875. // if it can be ascertained, as well as whether or not the collection uses a
  876. // custom domain.
  877. func collectionAliasFromReq(r *http.Request) string {
  878. vars := mux.Vars(r)
  879. alias := vars["subdomain"]
  880. isSubdomain := alias != ""
  881. if !isSubdomain {
  882. // Fall back to write.as/{collection} since this isn't a custom domain
  883. alias = vars["collection"]
  884. }
  885. return alias
  886. }
  887. func handleWebCollectionUnlock(app *App, w http.ResponseWriter, r *http.Request) error {
  888. var readReq struct {
  889. Alias string `schema:"alias" json:"alias"`
  890. Pass string `schema:"password" json:"password"`
  891. Next string `schema:"to" json:"to"`
  892. }
  893. // Get params
  894. if impart.ReqJSON(r) {
  895. decoder := json.NewDecoder(r.Body)
  896. err := decoder.Decode(&readReq)
  897. if err != nil {
  898. log.Error("Couldn't parse readReq JSON request: %v\n", err)
  899. return ErrBadJSON
  900. }
  901. } else {
  902. err := r.ParseForm()
  903. if err != nil {
  904. log.Error("Couldn't parse readReq form request: %v\n", err)
  905. return ErrBadFormData
  906. }
  907. err = app.formDecoder.Decode(&readReq, r.PostForm)
  908. if err != nil {
  909. log.Error("Couldn't decode readReq form request: %v\n", err)
  910. return ErrBadFormData
  911. }
  912. }
  913. if readReq.Alias == "" {
  914. return impart.HTTPError{http.StatusBadRequest, "Need a collection `alias` to read."}
  915. }
  916. if readReq.Pass == "" {
  917. return impart.HTTPError{http.StatusBadRequest, "Please supply a password."}
  918. }
  919. var collHashedPass []byte
  920. err := app.db.QueryRow("SELECT password FROM collectionpasswords INNER JOIN collections ON id = collection_id WHERE alias = ?", readReq.Alias).Scan(&collHashedPass)
  921. if err != nil {
  922. if err == sql.ErrNoRows {
  923. log.Error("No collectionpassword found when trying to read collection %s", readReq.Alias)
  924. return impart.HTTPError{http.StatusInternalServerError, "Something went very wrong. The humans have been alerted."}
  925. }
  926. return err
  927. }
  928. if !auth.Authenticated(collHashedPass, []byte(readReq.Pass)) {
  929. return impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  930. }
  931. // Success; set cookie
  932. session, err := app.sessionStore.Get(r, blogPassCookieName)
  933. if err == nil {
  934. session.Values[readReq.Alias] = true
  935. err = session.Save(r, w)
  936. if err != nil {
  937. log.Error("Didn't save unlocked blog '%s': %v", readReq.Alias, err)
  938. }
  939. }
  940. next := "/" + readReq.Next
  941. if !app.cfg.App.SingleUser {
  942. next = "/" + readReq.Alias + next
  943. }
  944. return impart.HTTPError{http.StatusFound, next}
  945. }
  946. func isAuthorizedForCollection(app *App, alias string, r *http.Request) bool {
  947. authd := false
  948. session, err := app.sessionStore.Get(r, blogPassCookieName)
  949. if err == nil {
  950. _, authd = session.Values[alias]
  951. }
  952. return authd
  953. }