counter: add a web interface

This commit is contained in:
Chris Sexton 2019-05-27 14:27:34 -04:00
parent ee05a3364d
commit 55b2b707c1
2 changed files with 209 additions and 0 deletions

View File

@ -4,8 +4,10 @@ package counter
import ( import (
"database/sql" "database/sql"
"encoding/json"
"fmt" "fmt"
"math/rand" "math/rand"
"net/http"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@ -43,6 +45,20 @@ type alias struct {
PointsTo string `db:"points_to"` PointsTo string `db:"points_to"`
} }
// GetItems returns all counters
func GetAllItems(db *sqlx.DB) ([]Item, error) {
var items []Item
err := db.Select(&items, `select * from counter`)
if err != nil {
return nil, err
}
// Don't forget to embed the DB into all of that shiz
for i := range items {
items[i].DB = db
}
return items, nil
}
// GetItems returns all counters for a subject // GetItems returns all counters for a subject
func GetItems(db *sqlx.DB, nick string) ([]Item, error) { func GetItems(db *sqlx.DB, nick string) ([]Item, error) {
var items []Item var items []Item
@ -201,6 +217,7 @@ func New(b bot.Bot) *CounterPlugin {
} }
b.Register(cp, bot.Message, cp.message) b.Register(cp, bot.Message, cp.message)
b.Register(cp, bot.Help, cp.help) b.Register(cp, bot.Help, cp.help)
cp.registerWeb()
return cp return cp
} }
@ -534,3 +551,67 @@ func everyDayImShuffling(vals []string) []string {
} }
return ret return ret
} }
func (p *CounterPlugin) registerWeb() {
http.HandleFunc("/counter/api", p.handleCounterAPI)
http.HandleFunc("/counter", p.handleCounter)
p.Bot.RegisterWeb("/counter", "Counter")
}
func (p *CounterPlugin) handleCounter(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, html)
}
func (p *CounterPlugin) handleCounterAPI(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
info := struct {
User string
Thing string
Action string
}{}
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&info)
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
log.Debug().
Interface("postbody", info).
Msg("Got a POST")
item, err := GetItem(p.DB, info.User, info.Thing)
if err != nil {
log.Error().
Err(err).
Str("subject", info.User).
Str("itemName", info.Thing).
Msg("error finding item")
w.WriteHeader(404)
fmt.Fprint(w, err)
return
}
if info.Action == "++" {
item.UpdateDelta(1)
} else if info.Action == "--" {
item.UpdateDelta(-1)
} else {
w.WriteHeader(400)
fmt.Fprint(w, "Invalid increment")
return
}
}
all, err := GetAllItems(p.DB)
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
data, err := json.Marshal(all)
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
fmt.Fprint(w, string(data))
}

128
plugins/counter/html.go Normal file
View File

@ -0,0 +1,128 @@
package counter
var html = `
<html>
<head>
<!-- Load required Bootstrap and BootstrapVue CSS -->
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<!-- Load polyfills to support older browsers -->
<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CMutationObserver"></script>
<!-- Load Vue followed by BootstrapVue -->
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<h1>Counters</h1>
<b-alert
dismissable
variant="error"
v-if="err"
@dismissed="err = ''">
{{ err }}
</b-alert>
<b-container>
<b-row>
<b-col cols="5">Human test: What is {{ equation }}?</b-col>
<b-col><b-input v-model="answer"></b-col>
</b-row>
<b-row v-for="(counter, user) in counters">
{{ user }}:
<b-container>
<b-row v-for="(count, thing) in counter">
<b-col offset="1">
{{ thing }}:
</b-col>
<b-col>
{{ count }}
</b-col>
<b-col cols="2">
<button :disabled="!authenticated" @click="subtract(user,thing,count)">-</button>
<button :disabled="!authenticated" @click="add(user,thing,count)">+</button>
</b-col>
</b-row>
</b-container>
</b-row>
</b-container>
</div>
<script>
function convertData(data) {
var newData = {};
for (let i = 0; i < data.length; i++) {
let entry = data[i]
if (newData[entry.Nick] === undefined) {
newData[entry.Nick] = {}
}
newData[entry.Nick][entry.Item] = entry.Count;
}
return newData;
}
var app = new Vue({
el: '#app',
data: {
answer: '',
correct: 0,
err: '',
counters: {
stk5: {
beer: 12,
tea: 84,
coffee: 127
},
flyngpngn: {
beer: 123,
mead: 1,
tea: 130
}
}
},
mounted() {
axios.get('/counter/api')
.then(resp => (this.counters = convertData(resp.data)))
.catch(err => (this.err = err));
},
computed: {
authenticated: function() {
if (Number(this.answer) === this.correct)
return true;
return false;
},
equation: function() {
const x = Math.floor(Math.random() * 100);
const y = Math.floor(Math.random() * 100);
const z = Math.floor(Math.random() * 100);
const ops = ['+', '-', '*'];
const op1 = ops[Math.floor(Math.random()*3)];
const op2 = ops[Math.floor(Math.random()*3)];
const eq = ""+x+op1+y+op2+z;
this.correct = eval(eq);
return eq
}
},
methods: {
add(user, thing, count) {
this.counters[user][thing]++;
axios.post('/counter/api',
{user: user, thing: thing, action: '++'})
.then(resp => (this.counters = convertData(resp.data)))
.catch(err => (this.err = err));
},
subtract(user, thing, count) {
this.counters[user][thing]--;
axios.post('/counter/api',
{user: user, thing: thing, action: '--'})
.then(resp => (this.counters = convertData(resp.data)))
.catch(err => (this.err = err));
}
}
})
</script>
</body>
</html>
`