upload map image and displaying on connect works (still need to send broadcast on the socket when upload happens)

This commit is contained in:
Iris Lightshard 2023-04-03 23:15:17 -06:00
parent 51f50d679d
commit 16d58eb281
Signed by: Iris Lightshard
GPG key ID: 3B7FBC22144E6398
5 changed files with 71 additions and 15 deletions

View file

@ -2,7 +2,7 @@ package admin
import (
"encoding/json"
_ "fmt"
"fmt"
"hacklab.nilfm.cc/felt/admin/util"
"hacklab.nilfm.cc/felt/models"
"hacklab.nilfm.cc/felt/mongodb"
@ -152,12 +152,19 @@ func apiDestroyTable(next http.Handler, udb auth.UserStore, dbAdapter mongodb.Db
func apiUploadMapImg(next http.Handler, udb auth.UserStore, dbAdapter mongodb.DbAdapter, uploads, uploadType string, uploadMax int) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
// get table from request body
tableKey := models.TableKey{}
err := json.NewDecoder(req.Body).Decode(&tableKey)
r, err := req.MultipartReader()
if err != nil {
w.WriteHeader(400)
next.ServeHTTP(w, req)
return
fmt.Println(err.Error())
}
f, err := r.ReadForm(int64(uploadMax << 20))
if err != nil {
fmt.Println(err.Error())
}
tableKey := models.TableKey{
Name: f.Value["name"][0],
Passcode: f.Value["passcode"][0],
}
// check if this table exists
@ -170,20 +177,25 @@ func apiUploadMapImg(next http.Handler, udb auth.UserStore, dbAdapter mongodb.Db
// ensure data storage dir exists
info, err := os.Stat(uploads)
if !info.IsDir() {
fmt.Println("uploads dir aint no dir")
w.WriteHeader(500)
next.ServeHTTP(w, req)
return
} else if err != nil {
err = os.MkdirAll(filepath.Join(uploads, tableKey.Name, uploadType), 0755)
err = os.MkdirAll(uploads, 0755)
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(500)
next.ServeHTTP(w, req)
}
}
err = os.MkdirAll(filepath.Join(uploads, tableKey.Name, uploadType), 0755)
// check for filename; call create to overwrite regardless
// get file data from multipart form
req.ParseMultipartForm(int64(uploadMax << 20))
file, header, err := req.FormFile("file")
header := f.File["file"][0]
file, err := header.Open()
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(500)
next.ServeHTTP(w, req)
}
@ -194,15 +206,21 @@ func apiUploadMapImg(next http.Handler, udb auth.UserStore, dbAdapter mongodb.Db
}
// write to file
destPath := filepath.Join(uploads, tableKey.Name, uploadType, header.Filename)
fmt.Println(destPath)
dest, err := os.Create(destPath)
if err != nil {
fmt.Println(err.Error())
w.WriteHeader(500)
next.ServeHTTP(w, req)
}
dest.Write(fileData)
dest.Close()
err = dbAdapter.SetMapImageUrl(tableKey, "/uploads/"+tableKey.Name+"/"+uploadType+"/"+header.Filename)
if err != nil {
fmt.Println(err.Error())
}
// respond with URL so UI can update
w.WriteHeader(201)
w.Header().Set("Content-Type", "application/json")
AddContextValue(req, "location", "/uploads/"+tableKey.Name+"/"+uploadType+"/"+header.Filename)
next.ServeHTTP(w, req)

View file

@ -45,6 +45,7 @@ func New(adapter mongodb.DbAdapter, udb auth.UserStore, uploads string, uploadMa
dbAdapter: adapter,
}
srvr.serveMux.Handle("/table/", http.StripPrefix("/table/", renderer.Subtree("./static")))
srvr.serveMux.Handle("/uploads/", http.StripPrefix("/uploads/", renderer.Subtree(uploads)))
srvr.serveMux.Handle("/admin/", http.StripPrefix("/admin", admin.CreateAdminInterface(udb, adapter, uploads, uploadMaxMB)))
srvr.serveMux.HandleFunc("/subscribe", srvr.subscribeHandler)
srvr.serveMux.HandleFunc("/publish", srvr.publishHandler)

View file

@ -213,7 +213,7 @@ func (self *DbEngine) SetMapImageUrl(table models.TableKey, url string) error {
{"passcode", table.Passcode},
},
bson.D{
{"mapImageUrl", url},
{"$set", bson.D{{"mapImageUrl", url}}},
},
).Decode(&result)
@ -254,7 +254,7 @@ func (self *DbEngine) SetAuxMessage(table models.TableKey, message string) error
{"passcode", table.Passcode},
},
bson.D{
{"auxMessage", message},
{"$set", bson.D{{"auxMessage", message}}},
},
).Decode(&result)

View file

@ -21,7 +21,8 @@ async function getTable(name, pass) {
infoHtml = "<a href='#' onclick='getTables()'>&larr; table list</a><br><pre>";
infoHtml += await res.text();
infoHtml += "</pre>"
infoHtml += `<button onclick='destroyTable()'>Destroy</button>`
infoHtml += "<input id='map_img_upload' type='file'>Map Image</input><button onclick='uploadMapImg()'>Upload</button>"
infoHtml += "<button onclick='destroyTable()'>Destroy</button>"
adminZone.innerHTML = infoHtml;
}
else {
@ -32,6 +33,30 @@ async function getTable(name, pass) {
}
}
async function uploadMapImg() {
try {
var input = document.getElementById("map_img_upload");
var data = new FormData();
data.append('file', input.files[0]);
data.append('name', tableKey.name);
data.append('passcode', tableKey.passcode);
const headers = new Headers();
headers.set('Authorization', 'Bearer ' + adminToken.access_token);
res = await fetch(`/admin/api/upload/${tableKey.name}/map/`, {
headers: headers,
method: "POST",
body: data,
});
if (res.ok) {
getTable(tableKey.name, tableKey.passcode);
} else {
throw new Error("Something went wrong uploading the map BG...");
}
} catch (err) {
setErr(`${err.name}: ${err.message}`);
}
}
async function destroyTable() {
try {
const headers = new Headers();

View file

@ -40,11 +40,20 @@ function logDice(dice, many) {
}
function makeUpToDate(table) {
if (table && table.diceRolls) {
logDice(table.diceRolls, true);
if (table) {
if (table.diceRolls) {
logDice(table.diceRolls, true);
}
if (table.mapImageUrl) {
setMapImg(table.mapImageUrl);
}
}
}
function setMapImg(url) {
document.getElementById("map").innerHTML = `<img src="${url}"/>`
}
function dial() {
// get tableKey from UI
const tblNameInput = document.getElementById("input_table_name");
@ -95,6 +104,9 @@ function dial() {
if (data.diceRoll) {
logDice(data.diceRoll);
}
if (data.mapImageUrl) {
setMapImg(data.mapImageUrl);
}
}
console.log(data);
});