Compare commits

..

3 Commits

Author SHA1 Message Date
Chris Sexton 22658949a8 emojy: update web UI a bit
- cards on list
- add text name to stats
2022-07-22 10:18:52 -04:00
Chris Sexton cf19a2bc15 cowboy: anchor emojy pages to URLs
This also refactored a bunch of junk and eliminated about 4k calls to
the config/database on emojy listing.
2022-07-22 10:18:52 -04:00
Chris Sexton 79cdd0f828 cowboy: stop scaling the base image so much 2022-07-22 09:16:54 -04:00
9 changed files with 276 additions and 71 deletions

View File

@ -118,7 +118,11 @@ func New(config *config.Config, connector Connector) Bot {
log.Debug().Msgf("created web router") log.Debug().Msgf("created web router")
bot.router.Use(middleware.Logger) // Make the http logger optional
// It has never served a purpose in production and with the emojy page, can make a rather noisy log
if bot.Config().GetInt("bot.useLogger", 0) == 1 {
bot.router.Use(middleware.Logger)
}
bot.router.Use(middleware.StripSlashes) bot.router.Use(middleware.StripSlashes)
bot.router.HandleFunc("/", bot.serveRoot) bot.router.HandleFunc("/", bot.serveRoot)

View File

@ -12,12 +12,19 @@ import (
type Cowboy struct { type Cowboy struct {
b bot.Bot b bot.Bot
c *config.Config c *config.Config
emojyPath string
baseEmojyURL string
} }
func New(b bot.Bot) *Cowboy { func New(b bot.Bot) *Cowboy {
emojyPath := b.Config().Get("emojy.path", "emojy")
baseURL := b.Config().Get("emojy.baseURL", "/emojy/file")
c := Cowboy{ c := Cowboy{
b: b, b: b,
c: b.Config(), c: b.Config(),
emojyPath: emojyPath,
baseEmojyURL: baseURL,
} }
c.register() c.register()
c.registerWeb() c.registerWeb()

View File

@ -6,6 +6,7 @@ import (
"image" "image"
"image/draw" "image/draw"
"image/png" "image/png"
"math"
"os" "os"
"path" "path"
@ -14,8 +15,8 @@ import (
"github.com/velour/catbase/plugins/emojy" "github.com/velour/catbase/plugins/emojy"
) )
func getEmojy(c *config.Config, name string) (image.Image, error) { func getEmojy(emojyPath, baseEmojyURL, name string) (image.Image, error) {
files, _, err := emojy.AllFiles(c) files, _, err := emojy.AllFiles(emojyPath, baseEmojyURL)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -34,8 +35,7 @@ func getEmojy(c *config.Config, name string) (image.Image, error) {
return img, nil return img, nil
} }
func getCowboyHat(c *config.Config) (image.Image, error) { func getCowboyHat(c *config.Config, emojyPath string) (image.Image, error) {
emojyPath := c.Get("emojy.path", "emojy")
p := path.Join(emojyPath, c.Get("cowboy.hatname", "hat.png")) p := path.Join(emojyPath, c.Get("cowboy.hatname", "hat.png"))
p = path.Clean(p) p = path.Clean(p)
f, err := os.Open(p) f, err := os.Open(p)
@ -49,28 +49,28 @@ func getCowboyHat(c *config.Config) (image.Image, error) {
return img, nil return img, nil
} }
func cowboyifyImage(c *config.Config, input image.Image) (image.Image, error) { func cowboyifyImage(c *config.Config, emojyPath string, input image.Image) (image.Image, error) {
hat, err := getCowboyHat(c) hat, err := getCowboyHat(c, emojyPath)
if err != nil { if err != nil {
return nil, err return nil, err
} }
targetW := uint(c.GetInt("cowboy.targetw", 64)) inputW, inputH := float64(input.Bounds().Max.X), float64(input.Bounds().Max.Y)
hatW, hatH := float64(hat.Bounds().Max.X), float64(hat.Bounds().Max.Y) hatW, hatH := float64(hat.Bounds().Max.X), float64(hat.Bounds().Max.Y)
newH := uint(float64(targetW) / hatW * hatH) targetSZ := math.Max(inputW, inputH)
hat = resize.Resize(targetW, newH, hat, resize.MitchellNetravali) dst := image.NewRGBA(image.Rect(0, 0, int(targetSZ), int(targetSZ)))
input = resize.Resize(targetW, targetW, input, resize.MitchellNetravali) newH := uint(targetSZ / hatW * hatH)
dst := image.NewRGBA(image.Rect(0, 0, 64, 64)) hat = resize.Resize(uint(targetSZ), newH, hat, resize.Lanczos3)
draw.Draw(dst, input.Bounds(), input, image.Point{}, draw.Src) draw.Draw(dst, input.Bounds(), input, image.Point{}, draw.Src)
draw.Draw(dst, hat.Bounds(), hat, image.Point{}, draw.Over) draw.Draw(dst, hat.Bounds(), hat, image.Point{}, draw.Over)
return dst, nil return dst, nil
} }
func cowboy(c *config.Config, name string) ([]byte, error) { func cowboy(c *config.Config, emojyPath, baseEmojyURL, name string) ([]byte, error) {
emojy, err := getEmojy(c, name) emojy, err := getEmojy(emojyPath, baseEmojyURL, name)
if err != nil { if err != nil {
return nil, err return nil, err
} }
img, err := cowboyifyImage(c, emojy) img, err := cowboyifyImage(c, emojyPath, emojy)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -15,7 +15,7 @@ func (p *Cowboy) registerWeb() {
func (p *Cowboy) handleImage(w http.ResponseWriter, r *http.Request) { func (p *Cowboy) handleImage(w http.ResponseWriter, r *http.Request) {
what := chi.URLParam(r, "what") what := chi.URLParam(r, "what")
img, err := cowboy(p.c, what) img, err := cowboy(p.c, p.emojyPath, p.baseEmojyURL, what)
if err != nil { if err != nil {
w.WriteHeader(500) w.WriteHeader(500)
fmt.Fprintf(w, "Error: %s", err) fmt.Fprintf(w, "Error: %s", err)

View File

@ -26,16 +26,23 @@ type EmojyPlugin struct {
b bot.Bot b bot.Bot
c *config.Config c *config.Config
db *sqlx.DB db *sqlx.DB
emojyPath string
baseURL string
} }
const maxLen = 32 const maxLen = 32
func New(b bot.Bot) *EmojyPlugin { func New(b bot.Bot) *EmojyPlugin {
log.Debug().Msgf("emojy.New") log.Debug().Msgf("emojy.New")
emojyPath := b.Config().Get("emojy.path", "emojy")
baseURL := b.Config().Get("emojy.baseURL", "/emojy/file")
p := &EmojyPlugin{ p := &EmojyPlugin{
b: b, b: b,
c: b.Config(), c: b.Config(),
db: b.DB(), db: b.DB(),
emojyPath: emojyPath,
baseURL: baseURL,
} }
p.setupDB() p.setupDB()
p.register() p.register()
@ -193,11 +200,9 @@ func (p *EmojyPlugin) allCounts() (map[string][]EmojyCount, error) {
return out, nil return out, nil
} }
func AllFiles(c *config.Config) (map[string]string, map[string]string, error) { func AllFiles(emojyPath, baseURL string) (map[string]string, map[string]string, error) {
files := map[string]string{} files := map[string]string{}
urls := map[string]string{} urls := map[string]string{}
emojyPath := c.Get("emojy.path", "emojy")
baseURL := c.Get("emojy.baseURL", "/emojy/file")
entries, err := os.ReadDir(emojyPath) entries, err := os.ReadDir(emojyPath)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@ -214,7 +219,7 @@ func AllFiles(c *config.Config) (map[string]string, map[string]string, error) {
} }
func (p *EmojyPlugin) isKnownEmojy(name string) (bool, string, string, error) { func (p *EmojyPlugin) isKnownEmojy(name string) (bool, string, string, error) {
allFiles, allURLs, err := AllFiles(p.c) allFiles, allURLs, err := AllFiles(p.emojyPath, p.baseURL)
if err != nil { if err != nil {
return false, "", "", err return false, "", "", err
} }

102
plugins/emojy/list.html Normal file
View File

@ -0,0 +1,102 @@
<!DOCTYPE html>
<html lang="en">
<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@^2/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@^2/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@^2/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<meta charset="UTF-8">
<title>Memes</title>
</head>
<body>
<div id="app">
<b-navbar>
<b-navbar-brand>Emojys</b-navbar-brand>
<b-navbar-nav>
<b-nav-item v-for="item in nav" :href="item.url" :active="item.name === 'Meme'" :key="item.key">{{ item.name
}}
</b-nav-item>
</b-navbar-nav>
</b-navbar>
<b-navbar>
<b-navbar-nav>
<b-nav-item href="/emojy/stats">Stats</b-nav-item>
<b-nav-item active href="/emojy/list">List</b-nav-item>
<b-nav-item href="/emojy/new">Upload</b-nav-item>
</b-navbar-nav>
</b-navbar>
<div
style="background-color:red;"
variant="error"
v-if="err != ''"
@click="err = ''">
{{ err }}
</div>
<div class="row row-cols-5">
<div class="card text-center" v-for="(path, name) in fileList" key="name">
<img :src="path" class="card-img-top mx-auto d-block" :alt="name" style="max-width: 100px">
<div class="card-body">
<h5 class="card-title">{{name}}</h5>
</div>
</div>
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: function () {
return {
err: '',
view: '',
nav: [],
results: [],
fileList: {},
image: null,
password: ''
}
},
watch: {
view(newView, oldView) {
this.err = '';
}
},
mounted() {
axios.get('/nav')
.then(resp => {
this.nav = resp.data;
})
.catch(err => console.log(err))
this.refresh();
},
methods: {
refresh: function () {
axios.get('/emojy/all')
.then(resp => {
this.results = resp.data
this.err = ''
})
.catch(err => (this.err = err))
axios.get('/emojy/allFiles')
.then(resp => {
this.fileList = resp.data
this.err = ''
})
.catch(err => (this.err = err))
},
}
})
</script>
</body>
</html>

112
plugins/emojy/stats.html Normal file
View File

@ -0,0 +1,112 @@
<!DOCTYPE html>
<html lang="en">
<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@^2/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@^2/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@^2/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<meta charset="UTF-8">
<title>Memes</title>
</head>
<body>
<div id="app">
<b-navbar>
<b-navbar-brand>Emojys</b-navbar-brand>
<b-navbar-nav>
<b-nav-item v-for="item in nav" :href="item.url" :active="item.name === 'Meme'" :key="item.key">{{ item.name
}}
</b-nav-item>
</b-navbar-nav>
</b-navbar>
<b-navbar>
<b-navbar-nav>
<b-nav-item active href="/emojy/stats">Stats</b-nav-item>
<b-nav-item href="/emojy/list">List</b-nav-item>
<b-nav-item href="/emojy/new">Upload</b-nav-item>
</b-navbar-nav>
</b-navbar>
<div
style="background-color:red;"
variant="error"
v-if="err != ''"
@click="err = ''">
{{ err }}
</div>
<ul>
<li v-for="(category, name) in results" key="name">
{{name}}:
<ul>
<li v-for="emojy in category" key="emojy">
{{emojy.count}} -
<span v-if="name != 'emoji'">
<span v-if="emojy.onServer"></span>
<span v-else></span>
-
</span>
<img v-if="emojy.url" :src="emojy.url" :alt="emojy.name" class="img-thumbnail"
style="max-width: 64px; max-height: 64px"/> {{emojy.name}}
<span v-else>{{emojy.emojy}}</span>
</li>
</ul>
</li>
</ul>
</div>
<script>
var app = new Vue({
el: '#app',
data: function () {
return {
err: '',
view: '',
nav: [],
results: [],
fileList: {},
image: null,
password: ''
}
},
watch: {
view(newView, oldView) {
this.err = '';
}
},
mounted() {
axios.get('/nav')
.then(resp => {
this.nav = resp.data;
})
.catch(err => console.log(err))
this.refresh();
},
methods: {
refresh: function () {
axios.get('/emojy/all')
.then(resp => {
this.results = resp.data
this.err = ''
})
.catch(err => (this.err = err))
axios.get('/emojy/allFiles')
.then(resp => {
this.fileList = resp.data
this.err = ''
})
.catch(err => (this.err = err))
},
}
})
</script>
</body>
</html>

View File

@ -11,8 +11,7 @@
<!-- Load Vue followed by BootstrapVue --> <!-- Load Vue followed by BootstrapVue -->
<script src="//unpkg.com/vue@^2/dist/vue.min.js"></script> <script src="//unpkg.com/vue@^2/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@^2/dist/bootstrap-vue.min.js"></script> <script src="//unpkg.com/bootstrap-vue@^2/dist/bootstrap-vue.min.js"></script>
<script src="https://unpkg.com/vue-router@^2"></script> <script src="//unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Memes</title> <title>Memes</title>
</head> </head>
@ -30,9 +29,9 @@
<b-navbar> <b-navbar>
<b-navbar-nav> <b-navbar-nav>
<b-nav-item :active="view == 'stats'" @click="view = 'stats'">Stats</b-nav-item> <b-nav-item href="/emojy/stats">Stats</b-nav-item>
<b-nav-item :active="view == 'list'" @click="view = 'list'">List</b-nav-item> <b-nav-item href="/emojy/list">List</b-nav-item>
<b-nav-item :active="view == 'upload'" @click="view = 'upload'">Upload</b-nav-item> <b-nav-item active href="/emojy/new">Upload</b-nav-item>
</b-navbar-nav> </b-navbar-nav>
</b-navbar> </b-navbar>
@ -44,7 +43,7 @@
{{ err }} {{ err }}
</div> </div>
<div class="container" v-if="view == 'upload'"> <div class="container">
<label>Passphrase</label> <label>Passphrase</label>
<b-input v-model="password"></b-input> <b-input v-model="password"></b-input>
<label>File <label>File
@ -53,42 +52,11 @@
<br> <br>
<button @click="submitFile()">Submit</button> <button @click="submitFile()">Submit</button>
</div> </div>
<ul v-if="view == 'stats'">
<li v-for="(category, name) in results" key="name">
{{name}}:
<ul>
<li v-for="emojy in category" key="emojy">
{{emojy.count}} -
<span v-if="name != 'emoji'">
<span v-if="emojy.onServer"></span>
<span v-else></span>
-
</span>
<img v-if="emojy.url" :src="emojy.url" :alt="emojy.name" class="img-thumbnail"
style="max-width: 64px; max-height: 64px"/>
<span v-else>{{emojy.emojy}}</span>
</li>
</ul>
</li>
</ul>
<ul v-if="view == 'list'">
<li v-for="(path, name) in fileList" key="name">
{{name}}:
<img :src="path" :alt="name" class="img-thumbnail" style="max-width: 64px; max-height: 64px"/>
</li>
</ul>
</div> </div>
<script> <script>
var router = new VueRouter({
mode: 'history',
routes: []
});
var app = new Vue({ var app = new Vue({
el: '#app', el: '#app',
router,
data: function () { data: function () {
return { return {
err: '', err: '',
@ -144,7 +112,7 @@
}) })
.then(() => { .then(() => {
console.log('SUCCESS!!'); console.log('SUCCESS!!');
this.view = 'list'; window.location.href = '/emojy/list';
}) })
.catch(e => { .catch(e => {
console.log('FAILURE!!' + e); console.log('FAILURE!!' + e);

View File

@ -25,13 +25,22 @@ func (p *EmojyPlugin) registerWeb() {
r.HandleFunc("/allFiles", p.handleAllFiles) r.HandleFunc("/allFiles", p.handleAllFiles)
r.HandleFunc("/upload", p.handleUpload) r.HandleFunc("/upload", p.handleUpload)
r.HandleFunc("/file/{name}", p.handleEmojy) r.HandleFunc("/file/{name}", p.handleEmojy)
r.HandleFunc("/stats", p.handlePage("stats.html"))
r.HandleFunc("/list", p.handlePage("list.html"))
r.HandleFunc("/new", p.handlePage("upload.html"))
r.HandleFunc("/", p.handleIndex) r.HandleFunc("/", p.handleIndex)
p.b.RegisterWebName(r, "/emojy", "Emojys") p.b.RegisterWebName(r, "/emojy", "Emojys")
} }
func (p *EmojyPlugin) handleIndex(w http.ResponseWriter, r *http.Request) { func (p *EmojyPlugin) handleIndex(w http.ResponseWriter, r *http.Request) {
index, _ := embeddedFS.ReadFile("index.html") http.Redirect(w, r, "/emojy/stats", http.StatusPermanentRedirect)
w.Write(index) }
func (p *EmojyPlugin) handlePage(file string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
index, _ := embeddedFS.ReadFile(file)
w.Write(index)
}
} }
func (p *EmojyPlugin) handleAll(w http.ResponseWriter, r *http.Request) { func (p *EmojyPlugin) handleAll(w http.ResponseWriter, r *http.Request) {
@ -47,7 +56,7 @@ func (p *EmojyPlugin) handleAll(w http.ResponseWriter, r *http.Request) {
} }
func (p *EmojyPlugin) handleAllFiles(w http.ResponseWriter, r *http.Request) { func (p *EmojyPlugin) handleAllFiles(w http.ResponseWriter, r *http.Request) {
_, urlMap, err := AllFiles(p.c) _, urlMap, err := AllFiles(p.emojyPath, p.baseURL)
if err != nil { if err != nil {
w.WriteHeader(500) w.WriteHeader(500)
out, _ := json.Marshal(struct{ err error }{err}) out, _ := json.Marshal(struct{ err error }{err})
@ -107,13 +116,12 @@ func (p *EmojyPlugin) FileSave(r *http.Request) (string, error) {
if ok, _, _, _ := p.isKnownEmojy(emojyName); ok { if ok, _, _, _ := p.isKnownEmojy(emojyName); ok {
return "", fmt.Errorf("emojy already exists") return "", fmt.Errorf("emojy already exists")
} }
emojyPath := p.c.Get("emojy.path", "emojy")
contentType := fileHeader.Header.Get("Content-Type") contentType := fileHeader.Header.Get("Content-Type")
if !strings.HasPrefix(contentType, "image") { if !strings.HasPrefix(contentType, "image") {
return "", fmt.Errorf("incorrect mime type - given: %s", contentType) return "", fmt.Errorf("incorrect mime type - given: %s", contentType)
} }
fullPath := filepath.Clean(filepath.Join(emojyPath, emojyFileName)) fullPath := filepath.Clean(filepath.Join(p.emojyPath, emojyFileName))
_ = os.MkdirAll(emojyPath, os.ModePerm) _ = os.MkdirAll(p.emojyPath, os.ModePerm)
log.Debug().Msgf("trying to create/open file: %s", fullPath) log.Debug().Msgf("trying to create/open file: %s", fullPath)
file, err := os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE, os.ModePerm) file, err := os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE, os.ModePerm)
if err != nil { if err != nil {
@ -132,8 +140,7 @@ func (p *EmojyPlugin) FileSave(r *http.Request) (string, error) {
func (p *EmojyPlugin) handleEmojy(w http.ResponseWriter, r *http.Request) { func (p *EmojyPlugin) handleEmojy(w http.ResponseWriter, r *http.Request) {
fname := chi.URLParam(r, "name") fname := chi.URLParam(r, "name")
emojyPath := p.c.Get("emojy.path", "emojy") contents, err := ioutil.ReadFile(path.Join(p.emojyPath, fname))
contents, err := ioutil.ReadFile(path.Join(emojyPath, fname))
if err != nil { if err != nil {
w.WriteHeader(404) w.WriteHeader(404)
out, _ := json.Marshal(struct{ err error }{err}) out, _ := json.Marshal(struct{ err error }{err})