github.com/Azareal/Gosora@v0.0.0-20210729070923-553e66b59003/routes/poll.go (about) 1 package routes 2 3 import ( 4 "bytes" 5 "database/sql" 6 "errors" 7 "net/http" 8 "strconv" 9 10 c "github.com/Azareal/Gosora/common" 11 ) 12 13 func PollVote(w http.ResponseWriter, r *http.Request, u *c.User, sPollID string) c.RouteError { 14 pollID, err := strconv.Atoi(sPollID) 15 if err != nil { 16 return c.PreError("The provided PollID is not a valid number.", w, r) 17 } 18 poll, err := c.Polls.Get(pollID) 19 if err == sql.ErrNoRows { 20 return c.PreError("The poll you tried to vote for doesn't exist.", w, r) 21 } else if err != nil { 22 return c.InternalError(err, w, r) 23 } 24 25 var topic *c.Topic 26 if poll.ParentTable == "replies" { 27 reply, err := c.Rstore.Get(poll.ParentID) 28 if err == sql.ErrNoRows { 29 return c.PreError("The parent post doesn't exist.", w, r) 30 } else if err != nil { 31 return c.InternalError(err, w, r) 32 } 33 topic, err = c.Topics.Get(reply.ParentID) 34 } else if poll.ParentTable == "topics" { 35 topic, err = c.Topics.Get(poll.ParentID) 36 } else { 37 return c.InternalError(errors.New("Unknown parentTable for poll"), w, r) 38 } 39 40 if err == sql.ErrNoRows { 41 return c.PreError("The parent topic doesn't exist.", w, r) 42 } else if err != nil { 43 return c.InternalError(err, w, r) 44 } 45 46 // TODO: Add hooks to make use of headerLite 47 _, ferr := c.SimpleForumUserCheck(w, r, u, topic.ParentID) 48 if ferr != nil { 49 return ferr 50 } 51 if !u.Perms.ViewTopic { 52 return c.NoPermissions(w, r, u) 53 } 54 55 optIndex, err := strconv.Atoi(r.PostFormValue("poll_option_input")) 56 if err != nil { 57 return c.LocalError("Malformed input", w, r, u) 58 } 59 err = poll.CastVote(optIndex, u.ID, u.GetIP()) 60 if err != nil { 61 return c.InternalError(err, w, r) 62 } 63 64 http.Redirect(w, r, "/topic/"+strconv.Itoa(topic.ID), http.StatusSeeOther) 65 return nil 66 } 67 68 func PollResults(w http.ResponseWriter, r *http.Request, u *c.User, sPollID string) c.RouteError { 69 //log.Print("in PollResults") 70 pollID, err := strconv.Atoi(sPollID) 71 if err != nil { 72 return c.PreError("The provided PollID is not a valid number.", w, r) 73 } 74 poll, err := c.Polls.Get(pollID) 75 if err == sql.ErrNoRows { 76 return c.PreError("The poll you tried to vote for doesn't exist.", w, r) 77 } else if err != nil { 78 return c.InternalError(err, w, r) 79 } 80 81 // TODO: Implement a version of this which doesn't rely so much on sequential order 82 var ob bytes.Buffer 83 ob.WriteRune('[') 84 var i int 85 e := poll.Resultsf(func(votes int) error { 86 if i != 0 { 87 ob.WriteRune(',') 88 } 89 ob.WriteString(strconv.Itoa(votes)) 90 i++ 91 return nil 92 }) 93 if e != nil && e != sql.ErrNoRows { 94 return c.InternalError(e, w, r) 95 } 96 ob.WriteRune(']') 97 w.Write(ob.Bytes()) 98 99 return nil 100 }