A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 

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