static/admin.js (raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
let adminToken = null; async function loadAdmin(name, pass) { try { const headers = new Headers(); headers.set('Authorization', 'Bearer ' + adminToken.access_token); const tableData = await fetch(`/admin/api/table/${name}?passcode=${pass}`, { method: 'GET', headers: headers, }); const mapImgs = await fetch (`/admin/api/upload/${name}/map/?passcode=${pass}`, { method: 'GET', headers: headers, }); const tokenImgs = await fetch(`/admin/api/upload/${name}/token/?passcode=${pass}`, { method: 'GET', headers: headers, }); let mgmtHTML = "" if (tableData.ok) { $("input_table_name").value = name; $("input_table_pass").value = pass; dial(); const table = await tableData.json() mgmtHTML = `<a href='#' onclick='getTables();return false;'>← table list</a><br>\n` + `<button id='q_toggle' onclick='toggleQ()'>Enqueue Updates</button>` + `<textarea id='aux_msg_input'>${table.auxMsg}</textarea><br><button onclick='publishAuxMsg()'>Set Status</button>\n` + `<button onclick='destroyTable()'>Destroy Table</button><br/>\n` + `<input id='map_img_upload' type='file'/><button onclick='uploadImg("map")'>Upload Map</button><br/>\n` if (mapImgs.ok) { const imgs = (await mapImgs.json()).sort(); mgmtHTML = imgs.reduce((s, i) => { const parts = i.split("/"); return s + `<li><a href="${i}" target="_blank">${parts[parts.length - 1]}</a> <button onclick="sendMapImg('${i}');">Set</button> <button onclick="deleteImg('${i}')">Delete</button></li>\n`; }, mgmtHTML + "<label>Available Maps</label><ul class='two_btn_list'>") + "</ul>"; } else { mgmtHTML += "<label>Maps couldn't be retrieved</label>"; } $("table_management").innerHTML = mgmtHTML; q = false; let spriteListHTML = `<input id='token_img_upload' type='file'/><button onclick='uploadImg("token")'>Upload Sprite</button><br/>`; if (tokenImgs.ok) { const sprites = (await tokenImgs.json()).sort(); spriteListHTML = sprites.reduce((s, t) => { const parts = t.split("/"); return s + `<li><a href="${t}" target="_blank">${parts[parts.length - 1]}</a> <button onclick="deleteImg('${t}')">Delete</button></li>\n`; }, spriteListHTML + "<ul class='single_btn_list'>") + "</ul>"; fillSpriteDropdown(sprites); } else { spriteListHTML += "<label>Sprites couldn't be retrieved</label>" } $("sprite_zone").innerHTML = spriteListHTML; $("token_management").style.display = "inline"; } else { console.log(res.status); } } catch (err) { setErr(`${err.name}: ${err.message}`); } } function toggleQ() { const toggleBtn = $('q_toggle'); q = !q; if (!q) { emptyMsgQ(); toggleBtn.innerText = "Enqueue Updates" } else { toggleBtn.innerText = "Send Updates" } } function fillSpriteDropdown(sprites) { const dropdown = $("sprite_dropdown"); let options = "<option value=''>select</option>"; dropdown.innerHTML = sprites.reduce((s, t) => { const parts = t.split("/"); return s + `<option value="${t}">${parts[parts.length - 1]}</option>\n`; }, "<option value=''>select</option>"); } function previewSprite(source) { if (source) { switch (source.id) { case "sprite_dropdown": reinitializeSpritePreview(); break; case "token_cx": case "token_cy": drawTokenOrigin(); break; default: scaleSpritePreview(source); } } } function toggleAspectLock() { try { const locked = $("token_aspect_lock").checked; $("aspect_lock_label").innerHTML = locked ? "w:h locked" : "w:h free" } catch {} } function scaleSpritePreview(source) { const tokenHeight = $("token_height"); const tokenWidth = $("token_width"); const tokenCX = $("token_cx"); const tokenCY = $("token_cy"); const tokenAspect = $("token_aspect_lock"); const preview = $("token_admin_preview"); if (mapImg && mapImg._image && tokenHeight && tokenWidth && tokenCX && tokenCY && tokenAspect && preview) { const scaleFactor = mapImg._image.clientWidth / mapImg._image.naturalWidth; const keepAspect = tokenAspect.checked; const img = preview.children[0]; tokenHeight.value = Math.floor(Number(tokenHeight.value)) tokenWidth.value = Math.floor(Number(tokenWidth.value)) if (img) { if (!keepAspect || !source) { img.width = Number(tokenWidth.value) * scaleFactor; img.height = Number(tokenHeight.value) * scaleFactor; } else { const currentAspect = img.width/img.height; switch (source.id) { case "token_width": img.width = Number(tokenWidth.value) * scaleFactor; img.height = (img.clientWidth / img.naturalWidth) * img.naturalHeight; tokenHeight.value = Math.floor(Number(tokenWidth.value)/currentAspect); break; case "token_height": img.height = Number(tokenHeight.value) * scaleFactor; img.width = (img.clientHeight / img.naturalHeight) * img.naturalWidth; tokenWidth.value = Math.floor(currentAspect * Number(tokenHeight.value)); break; } } if (!tokenCX.value || source) { tokenCX.value = Number(tokenWidth.value)/2; } if (!tokenCY.value || source) { tokenCY.value = Number(tokenHeight.value)/2; } drawTokenOrigin(); } } } function drawTokenOrigin() { const dropdown = $("sprite_dropdown"); const tokenWidth = $("token_width"); const tokenHeight = $("token_height"); const tokenCX = $("token_cx"); const tokenCY = $("token_cy"); const preview = $("token_admin_preview"); if (dropdown && tokenWidth && tokenHeight && tokenCX && tokenCY && preview && dropdown.selectedIndex >= 0) { tokenCX.value = Math.floor(Number(tokenCX.value)) tokenCY.value = Math.floor(Number(tokenCY.value)) const img = preview.children[0]; const x = Number(tokenWidth.value) / Number(tokenCX.value); const y = Number(tokenHeight.value) / Number(tokenCY.value); const origin = {x: img.width/x, y: img.height/y}; const originImg = document.createElement("img"); originImg.src="/table/origin.png"; originImg.style.position = "absolute"; originImg.style.left = (origin.x - 2) + "px"; originImg.style.top = (origin.y - 2) + "px"; if (preview.children.length > 1) { preview.replaceChild(originImg, preview.children[1]); } else { preview.appendChild(originImg); } } } function reinitializeSpritePreview(existing = false) { const dropdown = $("sprite_dropdown"); const tokenName = $("token_name"); const tokenWidth = $("token_width"); const tokenHeight = $("token_height"); const tokenCX = $("token_cx"); const tokenCY = $("token_cy"); const preview = $("token_admin_preview"); if (dropdown && tokenName && tokenWidth && tokenHeight && tokenCX && tokenCY && preview) { const img = document.createElement("img"); img.src = dropdown[dropdown.selectedIndex].value; if (!existing) { const tokenNameParts = dropdown[dropdown.selectedIndex].text.split("."); tokenNameParts.pop(); tokenName.value = tokenNameParts.join("."); } img.onload = () => { const w = img.naturalWidth; const h = img.naturalHeight; if (!existing) { tokenWidth.value = w; tokenHeight.value = h; tokenCX.value = ""; tokenCY.value = ""; } scaleSpritePreview(); } preview.innerHTML = ""; preview.appendChild(img); } } function createToken() { const dropdown = $("sprite_dropdown"); try { const w = Number($("token_width").value); const h = Number($("token_height").value); const oX = Number($("token_cx").value); const oY = Number($("token_cy").value); const img = dropdown[dropdown.selectedIndex].value; const name = $("token_name").value; if (!isNaN(w) && !isNaN(h) && !isNaN(oX) && !isNaN(oY) && img && name) { // send it on the websocket and wait for it to come back const [x, y] = [0, 0]; sendToken({ w: w, h: h, ox:oX, oy:oY, x: x, y: y, sprite: img, name: name, active: false }); setTokenCreateFormVisible(false); return; } setErr("All token fields are required"); } catch (err) { setErr(`${err.name}: ${err.message}`); } } function destroyToken(id) { const existing = tokens.find(t=>t.t.id == id); if (existing) { const self = Object.assign({}, existing.t); self.active = false; self.x = null; self.y = null; sendToken(self); } } function previewExistingToken(id) { try { const existing = tokens.find(t=>t.t.id == id); const dropdown = $("sprite_dropdown"); if (existing && dropdown) { $("token_width").value = existing.t.w; $("token_height").value = existing.t.h; $("token_cx").value = existing.t.oX; $("token_cy").value = existing.t.oY; $("token_name").value = existing.t.name; for (let i = 0; i < dropdown.options.length; i++ ) { if (dropdown.options[i].value === existing.t.sprite) { dropdown.selectedIndex = i; break; } } reinitializeSpritePreview(true); } } catch (err) { setErr(`${err.name}: ${err.message}`); } } function copyToken(id) { setTokenCreateFormVisible(true); previewExistingToken(id); } function renderTokenMasterList() { const tokenList = $("token_list"); if (tokenList) { const scroll = tokenList.scrollTop; tokenList.innerHTML = tokens.reduce((s, t) => { return s + `<li><a href="#" onclick="previewExistingToken('${t.t.id}');return false">${t.t.name}</a><button onclick="copyToken('${t.t.id}')">Copy</button><button onclick="destroyToken('${t.t.id}')">Destroy</button></li>\n`; }, ""); tokenList.scrollTop = scroll; } } function publishAuxMsg() { const txtArea = $("aux_msg_input"); if (txtArea) { publish({auxMsg: txtArea.value || " ", auth: adminToken.access_token}); } } function sendMapImg(url) { publish({mapImg: url, auth: adminToken.access_token}); } function sendToken(t) { publish({token: t, auth: adminToken.access_token}); } async function uploadImg(imgType) { try { var input = $(`${imgType}_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}/${imgType}/`, { headers: headers, method: "POST", body: data, }); if (res.ok) { loadAdmin(tableKey.name, tableKey.passcode); } else { throw new Error(`Something went wrong uploading the ${imgType} image...`); } } catch (err) { setErr(`${err.name}: ${err.message}`); } } async function deleteImg(url) { try { if (url.startsWith("/uploads/")) { const parts = url.split("/"); parts.shift(); const table = parts[1]; const imgType = parts[2] const file = parts[3]; const headers = new Headers(); headers.set('Authorization', 'Bearer ' + adminToken.access_token); const res = await fetch(`/admin/api/upload/${table}/${imgType}/${file}?passcode=${tableKey.passcode}`, { headers: headers, method: "DELETE", }); if (res.ok) { loadAdmin(tableKey.name, tableKey.passcode); } else { throw new Error ("Something went wrong deleting the image..."); } } } catch (err) { setErr(`${err.name}: ${err.message}`); } } async function destroyTable() { try { if (confirm("You really want to destroy this table?")) { const headers = new Headers(); headers.set('Authorization', 'Bearer ' + adminToken.access_token); const res = await fetch(`/admin/api/table/${tableKey.name}`, { method: 'DELETE', headers: headers, body: JSON.stringify(tableKey) }); if (res.ok) { leave(); getTables(); } else { setErr("Error destroying table"); } } } catch (err) { setErr(`${err.name}: ${err.message}`); } } function sortByName(a, b) { return (a.name < b.name) ? -1 : ((a.name > b.name) ? 1 : 0) } async function getTables() { try { const headers = new Headers(); headers.set('Authorization', 'Bearer ' + adminToken.access_token); const res = await fetch('/admin/api/table/', { method: 'GET', headers: headers }); if (res.ok) { const tblMgmt = $("table_management"); const tableList = (await res.json()).sort(sortByName); tblMgmt.innerHTML = tableList.reduce((s, t)=>{ return s + `<li><a href="#" onclick="loadAdmin('${t.name}','${t.passcode}');return false;">${t.name}</a></li>\n` }, "<ul>\n" ) + "</ul>"; tableListHTML += "</ul>" tblMgmt.style.display = "none"; } else { // fail silently } } catch { // fail silently } } async function doLogin() { const adminUsrInput = $("name_entry"); const adminPassInput = $("input_admin_pass"); const adminUI = $("admin_ui"); const tblMgmt = $("table_management"); const tokenMgmt = $("token_management"); if (adminUsrInput && adminPassInput && adminUI && tblMgmt && tokenMgmt) { adminToken = await getAdminToken(adminUsrInput.value, adminPassInput.value); if (adminToken) { getTables(); tblMgmt.style.display = "block"; tokenMgmt.style.display = "none"; adminUI.style.display="inline"; closeErr(); replaceAdminModal(); } else { setErr("Incorrect credentials"); } } } function replaceAdminModal() { const adminModal = $("admin_modal"); if (adminModal) { adminModal.innerHTML = "<a href='./'>Logout</a>"; } } async function getAdminToken(user, pass) { const headers = new Headers(); headers.set('Authorization', 'Basic ' + btoa(user + ":" + pass)); try { const res = await fetch('/admin/api/auth/', { method: 'POST', headers: headers }); if (res.ok) { return await res.json(); } return null; } catch (err) { return null; } } function setTableCreateFormVisible(v) { try { $("table_creation_form").style.display = v ? "block" : "none"; if (!v) { $("new_table_name").value = ""; $("new_table_pass").value = ""; } } catch (err) { setErr(`${err.name}: ${err.message}`); } } function setTokenCreateFormVisible(v) { try { if (v) { $("token_width").value = ""; $("token_height").value = ""; $("token_cx").value = ""; $("token_cy").value = ""; $("token_name").value = ""; $("sprite_dropdown").selectedIndex = 0; } $("token_creation_form").style.display = v ? "block" : "none"; $("token_list").style.display = v ? "none" : "block"; $("token_admin_preview").innerHTML = ""; } catch (err) { setErr(`${err.name}: ${err.message}`); } } async function createTable() { const newTableName = $("new_table_name"); const newTablePass = $("new_table_pass"); if (newTableName && newTablePass) { const headers = new Headers(); headers.set('Authorization', 'Bearer ' + adminToken.access_token); const formData = new FormData(); formData.set("name", newTableName.value); formData.set("passcode", newTablePass.value); let bodyStr = "{"; for (const pair of formData.entries()) { bodyStr += `"${pair[0]}": "${pair[1]}",`; } bodyStr = bodyStr.slice(0, -1); bodyStr += "}"; try { const res = await fetch('/admin/api/table/', { method: 'POST', headers: headers, body: bodyStr, }); if (res.ok) { getTables(); setTableCreateFormVisible(false); } else if (res.status === 422) { setErr("Table name and passcode must be only alphanumeric and underscores"); } else { setErr("Error creating table"); } } catch (err) { setErr(`${err.name}: ${err.message}`); } } } |