From cfec7879e3b3fc38956f2dce0acbbeb8a578f4c1 Mon Sep 17 00:00:00 2001 From: r Date: Sun, 9 Feb 2020 13:42:16 +0000 Subject: Add poll support Currenlty only voting is possible. --- mastodon/poll.go | 38 ++++++++++++++++++++ mastodon/status.go | 11 +++--- renderer/renderer.go | 14 ++++++-- service/auth.go | 13 +++++++ service/logging.go | 12 +++++-- service/service.go | 10 ++++++ service/transport.go | 19 ++++++++++ static/style.css | 8 +++++ templates/status.tmpl | 96 +++++++++++++++++++++++++++++++++++---------------- 9 files changed, 182 insertions(+), 39 deletions(-) create mode 100644 mastodon/poll.go diff --git a/mastodon/poll.go b/mastodon/poll.go new file mode 100644 index 0000000..274b95e --- /dev/null +++ b/mastodon/poll.go @@ -0,0 +1,38 @@ +package mastodon + +import ( + "context" + "fmt" + "net/http" + "net/url" + "time" +) + +type Poll struct { + ID string `json:"id"` + ExpiresAt time.Time `json:"expires_at"` + Expired bool `json:"expired"` + Multiple bool `json:"multiple"` + VotesCount int64 `json:"votes_count"` + Voted bool `json:"voted"` + Emojis []Emoji `json:"emojis"` + Options []PollOption `json:"options"` +} + +// Poll hold information for a mastodon poll option. +type PollOption struct { + Title string `json:"title"` + VotesCount int64 `json:"votes_count"` +} + +// Vote submits a vote with given choices to the poll specified by id. +func (c *Client) Vote(ctx context.Context, id string, choices []string) (*Poll, error) { + var poll Poll + params := make(url.Values) + params["choices[]"] = choices + err := c.doAPI(ctx, http.MethodPost, fmt.Sprintf("/api/v1/polls/%s/votes", id), params, &poll, nil) + if err != nil { + return nil, err + } + return &poll, nil +} diff --git a/mastodon/status.go b/mastodon/status.go index 63de3cf..b4f57ae 100644 --- a/mastodon/status.go +++ b/mastodon/status.go @@ -47,13 +47,14 @@ type Status struct { Application Application `json:"application"` Language string `json:"language"` Pinned interface{} `json:"pinned"` + Poll *Poll `json:"poll"` // Custom fields - Pleroma StatusPleroma `json:"pleroma"` - ShowReplies bool `json:"show_replies"` - ReplyMap map[string][]ReplyInfo `json:"reply_map"` - ReplyNumber int `json:"reply_number"` - RetweetedByID string `json:"retweeted_by_id"` + Pleroma StatusPleroma `json:"pleroma"` + ShowReplies bool `json:"show_replies"` + ReplyMap map[string][]ReplyInfo `json:"reply_map"` + ReplyNumber int `json:"reply_number"` + RetweetedByID string `json:"retweeted_by_id"` } // Context hold information for mastodon context. diff --git a/renderer/renderer.go b/renderer/renderer.go index 0eb229c..bd9ccd8 100644 --- a/renderer/renderer.go +++ b/renderer/renderer.go @@ -43,6 +43,7 @@ func NewRenderer(templateGlobPattern string) (r *renderer, err error) { "StatusContentFilter": StatusContentFilter, "DisplayInteractionCount": DisplayInteractionCount, "TimeSince": TimeSince, + "TimeUntil": TimeUntil, "FormatTimeRFC3339": FormatTimeRFC3339, "FormatTimeRFC822": FormatTimeRFC822, "WithContext": WithContext, @@ -86,7 +87,7 @@ func (r *renderer) RenderUserPage(ctx *Context, writer io.Writer, return r.template.ExecuteTemplate(writer, "user.tmpl", WithContext(data, ctx)) } -func (r *renderer) RenderUserSearchPage(ctx *Context, writer io.Writer, +func (r *renderer) RenderUserSearchPage(ctx *Context, writer io.Writer, data *UserSearchData) (err error) { return r.template.ExecuteTemplate(writer, "usersearch.tmpl", WithContext(data, ctx)) } @@ -158,8 +159,7 @@ func DisplayInteractionCount(c int64) string { return "" } -func TimeSince(t time.Time) string { - dur := time.Since(t) +func DurToStr(dur time.Duration) string { s := dur.Seconds() if s < 60 { return strconv.Itoa(int(s)) + "s" @@ -184,6 +184,14 @@ func TimeSince(t time.Time) string { return strconv.Itoa(int(y)) + "y" } +func TimeSince(t time.Time) string { + return DurToStr(time.Since(t)) +} + +func TimeUntil(t time.Time) string { + return DurToStr(time.Until(t)) +} + func FormatTimeRFC3339(t time.Time) string { return t.Format(time.RFC3339) } diff --git a/service/auth.go b/service/auth.go index 6c71439..4c5b38b 100644 --- a/service/auth.go +++ b/service/auth.go @@ -250,6 +250,19 @@ func (s *as) UnRetweet(ctx context.Context, c *model.Client, id string) (count i return s.Service.UnRetweet(ctx, c, id) } +func (s *as) Vote(ctx context.Context, c *model.Client, id string, + choices []string) (err error) { + err = s.authenticateClient(ctx, c) + if err != nil { + return + } + err = checkCSRF(ctx, c) + if err != nil { + return + } + return s.Service.Vote(ctx, c, id, choices) +} + func (s *as) Follow(ctx context.Context, c *model.Client, id string) (err error) { err = s.authenticateClient(ctx, c) if err != nil { diff --git a/service/logging.go b/service/logging.go index e429fac..055dadd 100644 --- a/service/logging.go +++ b/service/logging.go @@ -77,7 +77,7 @@ func (s *ls) ServeNotificationPage(ctx context.Context, c *model.Client, return s.Service.ServeNotificationPage(ctx, c, maxID, minID) } -func (s *ls) ServeUserPage(ctx context.Context, c *model.Client, id string, +func (s *ls) ServeUserPage(ctx context.Context, c *model.Client, id string, pageType string, maxID string, minID string) (err error) { defer func(begin time.Time) { s.logger.Printf("method=%v, id=%v, type=%v, took=%v, err=%v\n", @@ -111,7 +111,7 @@ func (s *ls) ServeSearchPage(ctx context.Context, c *model.Client, q string, return s.Service.ServeSearchPage(ctx, c, q, qType, offset) } -func (s *ls) ServeUserSearchPage(ctx context.Context, c *model.Client, +func (s *ls) ServeUserSearchPage(ctx context.Context, c *model.Client, id string, q string, offset int) (err error) { defer func(begin time.Time) { s.logger.Printf("method=%v, took=%v, err=%v\n", @@ -189,6 +189,14 @@ func (s *ls) UnRetweet(ctx context.Context, c *model.Client, id string) (count i return s.Service.UnRetweet(ctx, c, id) } +func (s *ls) Vote(ctx context.Context, c *model.Client, id string, choices []string) (err error) { + defer func(begin time.Time) { + s.logger.Printf("method=%v, id=%v, took=%v, err=%v\n", + "Vote", id, time.Since(begin), err) + }(time.Now()) + return s.Service.Vote(ctx, c, id, choices) +} + func (s *ls) Follow(ctx context.Context, c *model.Client, id string) (err error) { defer func(begin time.Time) { s.logger.Printf("method=%v, id=%v, took=%v, err=%v\n", diff --git a/service/service.go b/service/service.go index d762842..ecd0d3f 100644 --- a/service/service.go +++ b/service/service.go @@ -42,6 +42,7 @@ type Service interface { UnLike(ctx context.Context, c *model.Client, id string) (count int64, err error) Retweet(ctx context.Context, c *model.Client, id string) (count int64, err error) UnRetweet(ctx context.Context, c *model.Client, id string) (count int64, err error) + Vote(ctx context.Context, c *model.Client, id string, choices []string) (err error) Follow(ctx context.Context, c *model.Client, id string) (err error) UnFollow(ctx context.Context, c *model.Client, id string) (err error) Mute(ctx context.Context, c *model.Client, id string) (err error) @@ -843,6 +844,15 @@ func (svc *service) UnRetweet(ctx context.Context, c *model.Client, id string) ( return } +func (svc *service) Vote(ctx context.Context, c *model.Client, id string, + choices []string) (err error) { + _, err = c.Vote(ctx, id, choices) + if err != nil { + return + } + return +} + func (svc *service) Follow(ctx context.Context, c *model.Client, id string) (err error) { _, err = c.AccountFollow(ctx, id) return diff --git a/service/transport.go b/service/transport.go index 81af4fa..5ce0e56 100644 --- a/service/transport.go +++ b/service/transport.go @@ -419,6 +419,24 @@ func NewHandler(s Service, staticDir string) http.Handler { w.WriteHeader(http.StatusFound) } + vote := func(w http.ResponseWriter, req *http.Request) { + c := newClient(w) + ctx := newCtxWithSesionCSRF(req, req.FormValue("csrf_token")) + id, _ := mux.Vars(req)["id"] + statusID := req.FormValue("status_id") + choices, _ := req.PostForm["choices"] + + err := s.Vote(ctx, c, id, choices) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + s.ServeErrorPage(ctx, c, err) + return + } + + w.Header().Add("Location", req.Header.Get("Referer")+"#status-"+statusID) + w.WriteHeader(http.StatusFound) + } + follow := func(w http.ResponseWriter, req *http.Request) { c := newClient(w) ctx := newCtxWithSesionCSRF(req, req.FormValue("csrf_token")) @@ -697,6 +715,7 @@ func NewHandler(s Service, staticDir string) http.Handler { r.HandleFunc("/unlike/{id}", unlike).Methods(http.MethodPost) r.HandleFunc("/retweet/{id}", retweet).Methods(http.MethodPost) r.HandleFunc("/unretweet/{id}", unretweet).Methods(http.MethodPost) + r.HandleFunc("/vote/{id}", vote).Methods(http.MethodPost) r.HandleFunc("/follow/{id}", follow).Methods(http.MethodPost) r.HandleFunc("/unfollow/{id}", unfollow).Methods(http.MethodPost) r.HandleFunc("/mute/{id}", mute).Methods(http.MethodPost) diff --git a/static/style.css b/static/style.css index dc3f285..2f80af9 100644 --- a/static/style.css +++ b/static/style.css @@ -452,6 +452,14 @@ a:hover, margin: 2px; } +.poll-form button[type=submit] { + margin-top: 6px; +} + +.poll-info { + margin-top: 6px; +} + .dark { background-color: #222222; background-image: none; diff --git a/templates/status.tmpl b/templates/status.tmpl index 75b399b..95dee20 100644 --- a/templates/status.tmpl +++ b/templates/status.tmpl @@ -25,11 +25,11 @@ {{.Account.Acct}}
-