A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 

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