Skip to content
Snippets Groups Projects
Commit de557b62 authored by Tóth Miklós Tibor's avatar Tóth Miklós Tibor :shrug:
Browse files

Rewrite for db stuff

parent ee057ce6
Branches
No related tags found
No related merge requests found
Pipeline #8912 passed
package calc
import (
"fmt"
"git.sch.bme.hu/blintmester/keresett-a-feri/data"
"time"
)
func CalculateNewPoints(user *data.User) {
user.Time += user.Times[user.Group.Route[user.StoryCounter].Id].Sub(user.Times[user.Group.Route[user.StoryCounter-1].Id])
groupPoints(user.Group)
fmt.Println("time: " + user.Time.String())
fmt.Println("group time: " + user.Group.Time.String())
}
func groupPoints(group *data.Group) {
var tmp time.Duration = 0
var i int64 = 0
for _, member := range group.Members {
tmp += member.Time
i++
}
group.Time += time.Duration(tmp.Nanoseconds() / i)
}
......@@ -2,11 +2,9 @@ package data
import (
"embed"
"github.com/google/uuid"
"gopkg.in/yaml.v3"
"io/ioutil"
"math/rand"
"time"
)
//go:embed storyTemplates/*
......@@ -15,25 +13,7 @@ var StoryTemplates embed.FS
type Station struct {
Id string
Name string
Description string
}
type User struct {
Id uuid.UUID
Name string
Time time.Duration
Group *Group
Times map[string]time.Time
StoryCounter int
}
type Group struct {
Id uuid.UUID
Name string
Time time.Duration
Route []*Station
Members []User
Story string
}
type File struct {
......@@ -42,7 +22,6 @@ type File struct {
}
var Stations map[string]*Station
var Stories map[int]string
func ReadFile() {
b, err := ioutil.ReadFile("stations.yaml")
......@@ -61,35 +40,25 @@ func ReadFile() {
for key, value := range Stations {
value.Id = key
}
Stories = file.Stories
}
func CreateNewRoute() []*Station {
route := make([]*Station, len(Stations))
route[0] = Stations["first"]
route[len(Stations)-1] = Stations["last"]
keys := make([]string, len(Stations)-2)
func CreateNewRoute() []string {
stationIds := make([]string, len(Stations)-2)
i := 0
for k := range Stations {
switch k {
case "first", "last":
default:
keys[i] = k
stationIds[i] = k
i++
}
}
rand.Shuffle(len(keys), func(i, j int) {
keys[i], keys[j] = keys[j], keys[i]
rand.Shuffle(len(stationIds), func(i, j int) {
stationIds[i], stationIds[j] = stationIds[j], stationIds[i]
})
i = 1
for _, k := range keys {
route[i] = Stations[k]
i++
}
stationIds = append([]string{"first"}, stationIds...)
stationIds = append(stationIds, "last")
return route
return stationIds
}
......@@ -12,9 +12,19 @@ require (
github.com/go-playground/validator/v10 v10.9.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.10.0 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.1.1 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.8.1 // indirect
github.com/jackc/pgx/v4 v4.13.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.2 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/lib/pq v1.10.3 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
......@@ -24,11 +34,14 @@ require (
github.com/vmihailenco/msgpack/v5 v5.3.4 // indirect
github.com/vmihailenco/tagparser v0.1.2 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
gitlab.com/MikeTTh/env v0.0.0-20210102155928-2e9be3823cc7 // indirect
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
golang.org/x/sys v0.0.0-20210923061019-b8560ed6a9b7 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
gorm.io/driver/postgres v1.1.2 // indirect
gorm.io/gorm v1.21.15 // indirect
mellium.im/sasl v0.2.1 // indirect
)
This diff is collapsed.
package model
import (
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func GetUser(id string) (*User, error) {
var u User
e := db.Preload("Group").Preload("Times").First(&u, "id = ?", id).Error
if e == gorm.ErrRecordNotFound {
return nil, nil
}
return &u, e
}
func SaveUser(u *User) error {
return db.Omit(clause.Associations).Save(u).Error
}
func GetGroup(id string) (*Group, error) {
var g Group
e := db.First(&g, "id = ?", id).Error
if e == gorm.ErrRecordNotFound {
return nil, nil
}
return &g, e
}
func GetAllGroups() ([]*Group, error) {
var groups []*Group
e := db.Find(&groups).Error
return groups, e
}
func SaveGroup(g *Group) error {
return db.Save(g).Error
}
func SaveTimeStamp(t *TimeStamp) error {
return db.Save(t).Error
}
package model
import (
"gitlab.com/MikeTTh/env"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"log"
"time"
)
var db *gorm.DB
func init() {
var err error
db, err = gorm.Open(postgres.Open(env.String("POSTGRES", "postgresql://postgres:postgres@localhost")))
if err != nil {
panic(err)
}
db.Logger = logger.New(log.Default(), logger.Config{
SlowThreshold: time.Second,
LogLevel: logger.Info,
Colorful: true,
})
err = db.AutoMigrate(&Group{}, &TimeStamp{}, &User{})
if err != nil {
panic(err)
}
}
package model
import (
"git.sch.bme.hu/blintmester/keresett-a-feri/data"
"github.com/google/uuid"
"github.com/lib/pq"
"time"
)
type User struct {
Id uuid.UUID `gorm:"type:uuid not null;default:gen_random_uuid()"`
Name string `gorm:"type:varchar(200) not null"`
GroupID uuid.UUID `gorm:"type:uuid"`
Group *Group
Times []*TimeStamp
}
type Group struct {
Id uuid.UUID `gorm:"type:uuid not null;default:gen_random_uuid()"`
Name string `gorm:"type:varchar(200) not null"`
Route pq.StringArray `gorm:"type:varchar(200)[]"`
Members []*User
}
type TimeStamp struct {
Id uuid.UUID `gorm:"type:uuid not null;default:gen_random_uuid()"`
UserID uuid.UUID `gorm:"type:uuid"`
StationId string `gorm:"type:varchar(200) not null"`
Time time.Time
User *User
}
func (g *Group) GetStation(i int) *data.Station {
return data.Stations[g.Route[i]]
}
func (u *User) Time() time.Duration {
firstStation := u.Group.GetStation(0)
lastStation := u.Group.GetStation(len(data.Stations))
var firstTime, lastTime time.Time
for _, t := range u.Times {
if t.StationId == firstStation.Id {
firstTime = t.Time
}
if t.StationId == lastStation.Id {
lastTime = t.Time
}
}
return lastTime.Sub(firstTime)
}
func (g *Group) Time() time.Duration {
sum := time.Duration(0)
for _, u := range g.Members {
sum += u.Time()
}
sum /= time.Duration(len(g.Members))
return sum
}
func (u *User) HasBeenAt(station string) bool {
ret := false
for _, t := range u.Times {
if t.StationId == station {
ret = true
break
}
}
return ret
}
func (u *User) LastStation() *data.Station {
var last *data.Station
for _, s := range u.Group.Route {
for _, t := range u.Times {
if t.StationId == s {
last = data.Stations[s]
}
}
}
return last
}
stations:
first:
name: egy
description: ""
story: "01.html"
9881300f-175b-4809-b8fb-d915b2c900ac:
name: rand1
description: "18-on valahol"
story: "02.html"
2ab06fbd-0606-42a9-abc7-4163221d3f1f:
name: rand2
description: "szauna"
story: "03.html"
7023030f-e22f-4c82-93ae-4c847b3ac964:
name: rand3
description: "15-en, Feri szobajanal"
story: "04.html"
12907d55-a0c0-4256-bb60-017d603ce403:
name: rand4
description: "asd"
story: "05.html"
f0495cfa-5667-4853-ba69-febfde57fdc2:
name: rand5
description: "qwerty"
story: "06.html"
last:
name: uccso
description: "ez az AK-ban van"
story: "07.html"
stories:
1: "01.html"
2: "02.html"
3: "03.html"
4: "04.html"
5: "05.html"
6: "06.html"
7: "07.html"
......@@ -2,9 +2,8 @@ package web
import (
"errors"
"fmt"
"git.sch.bme.hu/blintmester/keresett-a-feri/calc"
"git.sch.bme.hu/blintmester/keresett-a-feri/data"
"git.sch.bme.hu/blintmester/keresett-a-feri/model"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"html/template"
......@@ -37,91 +36,87 @@ func init() {
}
func mainPage(c *gin.Context) {
groups, e := model.GetAllGroups()
if e != nil {
_ = c.Error(e)
return
}
c.HTML(http.StatusOK, "index.html", gin.H{
"Groups": []data.Group{
{
Id: uuid.New(),
Name: "A legjobb csapat",
},
{
Id: uuid.New(),
Name: "Nem, mert azok mi vagyunk",
},
},
"Groups": groups,
})
}
func times(c *gin.Context) {
c.HTML(http.StatusOK, "times.template.html", gin.H{
"Groups": groups,
//"Groups": groups, TODO
})
}
func getGroup(b string) (*data.Group, bool) {
for i, a := range groups {
if a.Name == b {
return groups[i], true
}
}
return nil, false
func getGroup(b string) (*model.Group, error) {
return model.GetGroup(b)
}
func getUser(cookie string) (*data.User, bool) {
func getUser(cookie string) (*model.User, error) {
if cookie != "" {
for i, group := range groups {
for j, member := range group.Members {
if member.Id.String() == cookie {
return &groups[i].Members[j], true
}
return model.GetUser(cookie)
}
return nil, nil
}
}
return nil, false
}
var groups []*data.Group
func login(c *gin.Context) {
cookie, _ := c.Cookie("uuid")
user, ok := getUser(cookie)
if !ok {
groupName := c.PostForm("group")
group, ok := getGroup(groupName)
if !ok {
group = &data.Group{
Id: uuid.New(),
Name: groupName,
Time: 0,
Route: data.CreateNewRoute(),
user, err := getUser(cookie)
if err != nil {
_ = c.Error(err)
return
}
groups = append(groups, group)
if user == nil {
groupId := c.PostForm("group")
group, err := getGroup(groupId)
if err != nil {
_ = c.Error(err)
return
}
if group == nil {
_ = c.Error(errors.New("group not found"))
return
}
user = &data.User{
user = &model.User{
Id: uuid.New(),
Name: c.PostForm("name"),
Time: 0,
StoryCounter: 0,
Group: group,
Times: make(map[string]time.Time),
}
group.Members = append(group.Members, *user)
err = model.SaveUser(user)
if err != nil {
_ = c.Error(err)
return
}
c.SetCookie("uuid", user.Id.String(), 7200, "/", "", false, true)
}
if user.Group.Route[user.StoryCounter].Id == "" {
user.Group.Route[user.StoryCounter].Id = "first"
user.Times["first"] = time.Now()
fmt.Println(user.Name + " accessed first station at " + user.Times["first"].String())
if user.Group.Route == nil {
user.Group.Route = data.CreateNewRoute()
e := model.SaveGroup(user.Group)
if e != nil {
_ = c.Error(e)
return
}
}
c.Redirect(http.StatusMovedPermanently, "/station/"+user.Group.Route[user.StoryCounter].Id)
c.Redirect(http.StatusMovedPermanently, "/station/"+user.LastStation().Id)
}
func routeChooser(c *gin.Context) {
cookie, _ := c.Cookie("uuid")
user, ok := getUser(cookie)
if !ok {
user, err := getUser(cookie)
if err != nil {
_ = c.Error(err)
return
}
if user == nil {
c.Redirect(http.StatusMovedPermanently, "/")
return
}
......@@ -138,47 +133,42 @@ func routeChooser(c *gin.Context) {
return
}
story := ""
var next *data.Station
for i, stat := range user.Group.Route {
if user.StoryCounter < i {
i := 0
for n, s := range user.Group.Route {
if s == station.Id {
i = n
break
}
if stat == station {
story = data.Stories[i+1]
if stat.Id == data.Stations["last"].Id {
next = nil
} else {
next = user.Group.Route[i+1]
}
}
}
if story != "" {
_, ok = user.Times[stationUri.Id]
if !ok {
user.Times[stationUri.Id] = time.Now()
fmt.Println(user.Name + " accessed" + station.Name + " station at " + user.Times[stationUri.Id].String())
}
storyTempl, _ := data.StoryTemplates.ReadFile("storyTemplates/" + story)
if station.Id == "first" || user.HasBeenAt(user.Group.GetStation(i-1).Id) {
storyTempl, _ := data.StoryTemplates.ReadFile("storyTemplates/" + station.Story)
c.HTML(http.StatusOK, "station.html", gin.H{
"Name": station.Name,
"Story": template.HTML(storyTempl),
"Next": next,
})
} else {
_ = c.Error(errors.New("ez nem az az állomás pajti"))
if !user.HasBeenAt(station.Id) {
ts := &model.TimeStamp{
StationId: stationUri.Id,
Time: time.Now(),
User: user,
}
e := model.SaveTimeStamp(ts)
if e != nil {
_ = c.Error(e)
return
}
if station.Id != "first" {
calc.CalculateNewPoints(user)
e = model.SaveUser(user)
if e != nil {
_ = c.Error(e)
return
}
if user.Group.Route[user.StoryCounter] == station {
if user.StoryCounter < len(data.Stories)-1 {
user.StoryCounter++
}
} else {
_ = c.Error(errors.New("ez nem az az állomás pajti"))
}
}
......@@ -29,7 +29,7 @@
<label>Csapatnév:</label>
<select class="form-select" id="group" name="group" form="form">
{{- range .Groups }}
<option value="{{ .Name }}">{{ .Name }}</option>
<option value="{{ .Id }}">{{ .Name }}</option>
{{- end }}
</select>
<form method="post" action="/" id="form">
......
......@@ -3,9 +3,6 @@
<div class="container" style="padding-top: 2em">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-8 col-xl-8">
<p>{{ .Story }}</p>
{{- if .Next }}
<a href="/station/{{ .Next.Id }}">link debug celbol</a>
{{- end }}
</div>
</div>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment