Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for images #1

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions quiz/sheets.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package quiz

import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
"image/png"
"io"
"math"
"net/http"
Expand Down Expand Up @@ -114,7 +119,7 @@ func getQuestionFromRow(row *sheets.RowData) (qq *Question, err error) {
continue
}
cellContent := getContentFromCell(cell)
if cellContent == (DisplayableContent{}) {
if cellContent.Text == "" {
continue
}

Expand All @@ -138,7 +143,7 @@ func getQuestionFromRow(row *sheets.RowData) (qq *Question, err error) {
}

// validation
if qq.Question == (DisplayableContent{}) {
if qq.Question.Text == "" {
if len(qq.Correct) == 0 && len(qq.Wrong) == 0 {
return nil, nil
}
Expand Down Expand Up @@ -224,16 +229,26 @@ func parseCellFormula(formula, parameter string) (content DisplayableContent) {
log.Printf("Error: get image from url '%s': %v", url, err)
return
}
data, err := io.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
data, _ := io.ReadAll(resp.Body)
log.Printf("Error: could not get image from url: got '%s': %s", resp.Status, string(data))
return
}

img, imgFormat, err := image.Decode(resp.Body)
if err != nil {
log.Printf("Error: reading image response: %v", err)
log.Printf("Error: decoding image from '%s': %v", url, err)
return
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
log.Printf("Error: could not get image from url: got '%s': %s", resp.Status, string(data))
hash := sha256.New()
imgData := &bytes.Buffer{}
err = png.Encode(io.MultiWriter(hash, imgData), img)
if err != nil {
log.Printf("Error: encoding image (%s to png): %v", imgFormat, err)
return
}
content.Text = string(data)
content.Text = fmt.Sprintf("%x", hash.Sum(nil))
content.Media = imgData.Bytes()
}
return
}
21 changes: 10 additions & 11 deletions quiz/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ type Question struct {
}

type DisplayableContent struct {
Type ContentType
Text string
Type ContentType `json:"type"`
Text string `json:"text"`
Media []byte `json:"-"`
}

type ContentType uint8
Expand All @@ -85,8 +86,8 @@ const (
)

type Round struct {
Question string `json:"question"`
Answers []string `json:"answers"`
Question DisplayableContent `json:"question"`
Answers []DisplayableContent `json:"answers"`
Correct int `json:"correct,omitempty"`
Current int `json:"current_round"`
Max int `json:"max_round"`
Expand Down Expand Up @@ -277,16 +278,16 @@ func (c Category) GetRounds(n int) []*Round {
}

func (q Question) ToRound() Round {
var answers []string
var answers []DisplayableContent

// select one correct answer
if len(q.Correct) > 1 {
rand.Shuffle(len(q.Correct), func(i, j int) {
q.Correct[i], q.Correct[j] = q.Correct[j], q.Correct[i]
})
answers = append(answers, q.Correct[rand.Intn(len(q.Correct)-1)].Text)
answers = append(answers, q.Correct[rand.Intn(len(q.Correct)-1)])
} else {
answers = append(answers, q.Correct[0].Text)
answers = append(answers, q.Correct[0])
}

// select up to 3 wrong answers
Expand All @@ -296,9 +297,7 @@ func (q Question) ToRound() Round {
})
}
num_wrong := int(math.Min(float64(cap(q.Wrong)), 3))
for _, a := range q.Wrong[:num_wrong] {
answers = append(answers, a.Text)
}
answers = append(answers, q.Wrong[:num_wrong]...)

var correct int
rand.Shuffle(len(answers), func(i, j int) {
Expand All @@ -309,7 +308,7 @@ func (q Question) ToRound() Round {
})

return Round{
Question: q.Question.Text,
Question: q.Question,
Answers: answers,
Correct: correct + 1,
}
Expand Down
33 changes: 33 additions & 0 deletions webserver/handle.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"strings"

"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/kesuaheli/twitchgo"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -300,6 +301,38 @@ func getRound(w http.ResponseWriter, r *http.Request) {

w.Write(b)
}
func getRoundMedia(w http.ResponseWriter, r *http.Request) {
c, ok := isAuthorized(r)
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}

if c.Game == nil {
w.WriteHeader(http.StatusBadRequest)
return
}

if c.Game.Current == 0 {
http.Error(w, "no active round", http.StatusNotFound)
return
}

media := mux.Vars(r)["media"]
round := *c.Game.Rounds[c.Game.Current-1]
for _, answer := range round.Answers {
if answer.Type == quiz.CONTENTTEXT || answer.Text != media {
continue
}
w.Write(answer.Media)
return
}
if round.Question.Type != quiz.CONTENTTEXT && round.Question.Text == media {
w.Write(round.Question.Media)
return
}
http.Error(w, "media not found", http.StatusNotFound)
}

func nextRound(w http.ResponseWriter, r *http.Request) {
c, ok := isAuthorized(r)
Expand Down
1 change: 1 addition & 0 deletions webserver/webserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func initHandler() http.Handler {
r.HandleFunc("/game", handleGame)
r.HandleFunc("/vote/streamer", handleStreamerVote).Methods(http.MethodPost)
r.HandleFunc("/round", getRound).Methods(http.MethodGet)
r.HandleFunc("/round/media/{media}", getRoundMedia).Methods(http.MethodGet)
r.HandleFunc("/round/next", nextRound).Methods(http.MethodPost)

return r
Expand Down