Skip to content
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
2 changes: 1 addition & 1 deletion database/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func Connect() {
log.Fatalf("Could not ping database: %v", err)
}

log.Printf("Connected to database %s@%s:%d/%s", config.User, config.Host, config.Port, config.Database)
log.Println("Connected to database")
}

// Close closes the database and prevents new queries from starting.
Expand Down
2 changes: 1 addition & 1 deletion database/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func GetUserByCredentials(username, password string) *User {
sha256 := sha256.Sum256([]byte(password))
password = hex.EncodeToString(sha256[:])

if regexp.MustCompile("^\\w+$").MatchString(username) {
if regexp.MustCompile(`^\w+$`).MatchString(username) {
return getUser("username=? AND password=?", username, password)
} else {
return getUser("email=? AND password=?", username, password)
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.23.1
require (
github.com/gorilla/websocket v1.5.3
github.com/kesuaheli/twitchgo v0.2.8-0.20240720003446-e1cc409cf403
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
google.golang.org/api v0.197.0
)

Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0V
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
Expand Down
29 changes: 21 additions & 8 deletions quiz/sheets.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package quiz

import (
"crypto/sha256"
"encoding/json"
"fmt"
"image"
_ "image/jpeg"
"image/png"
"io"
"math"
"net/http"
Expand All @@ -16,7 +20,7 @@ var spreadsheetFormulaRegex *regexp.Regexp

func init() {
var err error
spreadsheetFormulaRegex, err = regexp.Compile("^=([A-Z]+)\\((.*)\\)$")
spreadsheetFormulaRegex, err = regexp.Compile(`^=([A-Z]+)\((.*)\)$`)
if err != nil {
panic("failed to compile spreadsheet formula regex: " + err.Error())
}
Expand Down Expand Up @@ -114,7 +118,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 +142,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 +228,25 @@ 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 (%s): got '%s': %s", url, 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()
err = png.Encode(hash, 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 = img
}
return
}
51 changes: 40 additions & 11 deletions quiz/types.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package quiz

import (
"bytes"
"fmt"
"image"
"image/png"
logger "log"
"math"
"math/rand"
"time"

"github.com/nfnt/resize"
)

type Game struct {
Expand Down Expand Up @@ -73,8 +79,9 @@ type Question struct {
}

type DisplayableContent struct {
Type ContentType
Text string
Type ContentType `json:"type"`
Text string `json:"text"`
Media image.Image `json:"-"`
}

type ContentType uint8
Expand All @@ -85,8 +92,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 +284,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 +303,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,8 +314,32 @@ func (q Question) ToRound() Round {
})

return Round{
Question: q.Question.Text,
Question: q.Question,
Answers: answers,
Correct: correct + 1,
}
}

func (content DisplayableContent) EndecodeImage(width, height uint) (b []byte, err error) {
if content.Type != CONTENTIMAGE {
return nil, fmt.Errorf("content is not an image")
}

original_width, original_height := uint(content.Media.Bounds().Max.X-content.Media.Bounds().Min.X), uint(content.Media.Bounds().Max.Y-content.Media.Bounds().Min.Y)
ratio := float64(original_height) / float64(original_width)

var img image.Image
if ratio > 1 {
width = uint(float64(height) / ratio)
} else {
height = uint(float64(width) * ratio)
}
img = resize.Resize(width, height, content.Media, resize.Lanczos3)

imgData := &bytes.Buffer{}
err = png.Encode(imgData, img)
if err != nil {
return nil, fmt.Errorf("error encoding image to png: %w", err)
}
return imgData.Bytes(), nil
}
69 changes: 69 additions & 0 deletions webserver/handle.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import (
"net/http"
"quiz_backend/database"
"quiz_backend/quiz"
"strconv"
"strings"

"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/kesuaheli/twitchgo"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -300,6 +302,73 @@ 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"]
urlQueryParams := r.URL.Query()
var width, height uint
if sizeStr := urlQueryParams.Get("width"); sizeStr != "" {
size, _ := strconv.ParseUint(sizeStr, 10, 32)
width = uint(size)
} else {
http.Error(w, "missing required key 'width'", http.StatusBadRequest)
return
}
if sizeStr := urlQueryParams.Get("height"); sizeStr != "" {
size, _ := strconv.ParseUint(sizeStr, 10, 32)
height = uint(size)
} else {
http.Error(w, "missing required key 'height'", http.StatusBadRequest)
return
}
if width == 0 || height == 0 {
http.Error(w, "invalid width or height", http.StatusBadRequest)
return
}

round := *c.Game.Rounds[c.Game.Current-1]
for _, answer := range round.Answers {
if answer.Type == quiz.CONTENTTEXT || answer.Text != media {
continue
}
mediaData, err := answer.EndecodeImage(width, height)
if err != nil {
log.Printf("Failed to encode image: %v", err)
http.Error(w, "failed to encode image", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/png")
w.Write(mediaData)
return
}
if round.Question.Type != quiz.CONTENTTEXT && round.Question.Text == media {
mediaData, err := round.Question.EndecodeImage(width, height)
if err != nil {
log.Printf("Failed to encode image: %v", err)
http.Error(w, "failed to encode image", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/png")
w.Write(mediaData)
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