A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 

1042 linhas
27 KiB

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