aboutsummaryrefslogblamecommitdiff
path: root/controllers/topic.go
blob: 50f65e7cb852765f7c614c893e4f652e4ea36473 (plain) (tree)






































































































                                                                                                      
package controllers

import (
	"errors"
	"fmt"
	"net/http"
	"strconv"

	"gitrepo.ru/neonxp/gorum/contextlib"
	"gitrepo.ru/neonxp/gorum/models"
	"gitrepo.ru/neonxp/gorum/views"
	"go.neonxp.ru/mux"
)

func (rt *Router) Index(w http.ResponseWriter, r *http.Request) {
	topics, err := rt.topicRepo.List(0)
	if err != nil {
		mux.Render(w, r, mux.DefaultErrorHandler(err))
		return
	}

	mux.Render(w, r, views.Topics(topics))
}

func (rt *Router) Topic(w http.ResponseWriter, r *http.Request) {
	sParentID := r.PathValue("id")
	parentID, err := strconv.Atoi(sParentID)
	if err != nil {
		mux.Render(w, r, mux.DefaultErrorHandler(err))
		return
	}
	topic, err := rt.topicRepo.Get(uint64(parentID))
	if err != nil {
		mux.Render(w, r, mux.DefaultErrorHandler(err))
		return
	}

	topics, err := rt.topicRepo.List(uint64(parentID))
	if err != nil {
		mux.Render(w, r, mux.DefaultErrorHandler(err))
		return
	}
	posts, err := rt.postRepo.List(uint64(parentID))
	if err != nil {
		mux.Render(w, r, mux.DefaultErrorHandler(err))
		return
	}
	emailToUser := map[string]*models.User{}
	for _, p := range posts {
		u, ok := emailToUser[p.AuthorID]
		if !ok {
			u, err = rt.userRepo.Get(p.AuthorID)
			if err != nil {
				u = &models.User{Username: "user-not-found"}
			}
		}
		emailToUser[p.AuthorID] = u
		p.Author = u
	}

	mux.Render(w, r, views.Posts(topic, topics, posts))
}

func (rt *Router) NewTopic(w http.ResponseWriter, r *http.Request) {
	req := new(topicRequest)
	if err := mux.Bind(r, req); err != nil {
		mux.Render(w, r, mux.DefaultErrorHandler(err))
		return
	}
	user := contextlib.GetUser(r.Context())
	if user == nil {
		mux.Render(w, r, mux.DefaultErrorHandler(errors.New("403")))
		return
	}

	if r.Method == http.MethodPost {
		topic, err := rt.topicRepo.Create(req.Topic, req.Text, user.Email, uint64(req.Parent))
		if err != nil {
			mux.Render(w, r, mux.DefaultErrorHandler(err))
			return
		}
		mux.Redirect(w, 302, fmt.Sprintf("/t/%d", topic.ID))
		return
	}

	topic := &models.Topic{
		ID:    0,
		Topic: "Корень",
	}

	sTopicID := r.PathValue("topic")
	if sTopicID != "" {
		if topicID, err := strconv.Atoi(sTopicID); err == nil {
			topic, err = rt.topicRepo.Get(uint64(topicID))
			if err != nil {
				mux.Render(w, r, mux.DefaultErrorHandler(err))
				return
			}
		}
	}

	mux.Render(w, r, views.NewTopic(topic))
}