category_save.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package ui
  5. import (
  6. "net/http"
  7. "github.com/miniflux/miniflux/http/context"
  8. "github.com/miniflux/miniflux/http/response"
  9. "github.com/miniflux/miniflux/http/response/html"
  10. "github.com/miniflux/miniflux/http/route"
  11. "github.com/miniflux/miniflux/logger"
  12. "github.com/miniflux/miniflux/model"
  13. "github.com/miniflux/miniflux/ui/form"
  14. "github.com/miniflux/miniflux/ui/session"
  15. "github.com/miniflux/miniflux/ui/view"
  16. )
  17. // SaveCategory validate and save the new category into the database.
  18. func (c *Controller) SaveCategory(w http.ResponseWriter, r *http.Request) {
  19. ctx := context.New(r)
  20. user, err := c.store.UserByID(ctx.UserID())
  21. if err != nil {
  22. html.ServerError(w, err)
  23. return
  24. }
  25. categoryForm := form.NewCategoryForm(r)
  26. sess := session.New(c.store, ctx)
  27. view := view.New(c.tpl, ctx, sess)
  28. view.Set("form", categoryForm)
  29. view.Set("menu", "categories")
  30. view.Set("user", user)
  31. view.Set("countUnread", c.store.CountUnreadEntries(user.ID))
  32. if err := categoryForm.Validate(); err != nil {
  33. view.Set("errorMessage", err.Error())
  34. html.OK(w, r, view.Render("create_category"))
  35. return
  36. }
  37. duplicateCategory, err := c.store.CategoryByTitle(user.ID, categoryForm.Title)
  38. if err != nil {
  39. html.ServerError(w, err)
  40. return
  41. }
  42. if duplicateCategory != nil {
  43. view.Set("errorMessage", "This category already exists.")
  44. html.OK(w, r, view.Render("create_category"))
  45. return
  46. }
  47. category := model.Category{
  48. Title: categoryForm.Title,
  49. UserID: user.ID,
  50. }
  51. if err = c.store.CreateCategory(&category); err != nil {
  52. logger.Error("[Controller:CreateCategory] %v", err)
  53. view.Set("errorMessage", "Unable to create this category.")
  54. html.OK(w, r, view.Render("create_category"))
  55. return
  56. }
  57. response.Redirect(w, r, route.Path(c.router, "categories"))
  58. }