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

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