feat(admin): admin page

This commit is contained in:
catvayor 2024-06-10 09:43:35 +02:00
parent 6e0e9ae4a5
commit a00df617c5
6 changed files with 346 additions and 197 deletions

View file

@ -4,7 +4,7 @@ use rand::Rng;
use rocket::{
fs::{relative, FileServer},
response::stream::{Event, EventStream},
serde::Serialize,
serde::{json::Json, Deserialize, Serialize},
tokio::{
self, select,
time::{self, Duration, Instant},
@ -17,7 +17,7 @@ use std::{
sync::{Arc, RwLock},
};
#[derive(Serialize, Clone)]
#[derive(Serialize, Deserialize, Clone)]
#[serde(crate = "rocket::serde")]
enum TrackedState {
Conscrit {
@ -161,6 +161,8 @@ impl From<QueuedEvent> for Event {
type Tracking = Arc<RwLock<HashMap<String, RwLock<Tracked>>>>;
type TrackingEventQueue = Arc<RwLock<HashMap<String, RwLock<VecDeque<QueuedEvent>>>>>;
type AdminEventQueue = Arc<RwLock<VecDeque<QueuedEvent>>>;
type AdminKey = String;
#[derive(Serialize)]
#[serde(crate = "rocket::serde")]
@ -268,47 +270,33 @@ fn tracked_view(
}
}
fn evts_to_send(id: &str, evt_queue: &TrackingEventQueue) -> Vec<Event> {
let mut evts = Vec::new();
for qevt in evt_queue
.read()
.unwrap()
.get(&id.to_string())
.unwrap()
fn evts_to_send(evt_queue: &RwLock<VecDeque<QueuedEvent>>) -> Vec<Event> {
evt_queue
.read()
.unwrap()
.iter()
.filter(|qevt| !qevt.expired())
{
evts.push(qevt.evt.clone());
}
evts
.map(|qevt| qevt.evt.clone())
.collect()
}
fn evts_for(id: &str, evt_queues: &TrackingEventQueue) -> Vec<Event> {
evts_to_send(evt_queues.read().unwrap().get(&id.to_string()).unwrap())
}
#[get("/track/<id>/events")]
fn tracked_events<'a>(
id: &'a str,
tracking: &State<Tracking>,
evt_queue: &'a State<TrackingEventQueue>,
mut shutdown: Shutdown,
) -> Option<EventStream![Event + 'a]> {
if evt_queue.read().unwrap().contains_key(&id.to_string()) {
state_update(
&tracking
.read()
.unwrap()
.get(&id.to_string())
.unwrap()
.read()
.unwrap(),
&evt_queue,
);
Some(EventStream! {
let mut interval = time::interval(Duration::from_millis(100));
loop {
select!{
_ = interval.tick() =>{
for evt in evts_to_send(id, evt_queue){
for evt in evts_for(id, evt_queue){
//println!("{:?}", evt);
yield evt;
}
@ -322,7 +310,79 @@ fn tracked_events<'a>(
}
}
fn state_update(tracked: &Tracked, evt_queues: &TrackingEventQueue) {
#[get("/admin?<tok>&<dbg>")]
fn admin_page(
tok: Option<AdminKey>,
dbg: Option<bool>,
admin_key: &State<AdminKey>,
) -> Option<Template> {
if tok == Some(admin_key.to_string()) {
Some(Template::render(
"admin",
context! { tok: tok.unwrap(), dbg: dbg.unwrap_or(false) },
))
} else {
None
}
}
#[patch("/admin/<id>?<tok>", data = "<nstate>")]
fn admin_set_state(
tok: Option<AdminKey>,
id: &str,
admin_key: &State<AdminKey>,
nstate: Json<TrackedState>,
tracking: &State<Tracking>,
evt_queue: &State<TrackingEventQueue>,
admin_queue: &State<AdminEventQueue>,
) -> Option<()> {
if tok == Some(admin_key.to_string()) {
let tracking_lock = tracking.read().unwrap();
let tracked = tracking_lock.get(&id.to_string()).unwrap();
tracked.write().unwrap().state = nstate.into_inner();
state_update(&tracked.read().unwrap(), &evt_queue, &admin_queue);
Some(())
} else {
None
}
}
#[get("/admin/events?<tok>")]
fn admin_events<'a>(
tok: Option<AdminKey>,
admin_key: &State<AdminKey>,
admin_queue: &'a State<AdminEventQueue>,
tracking: &State<Tracking>,
mut shutdown: Shutdown,
) -> Option<EventStream![Event + 'a]> {
if tok == Some(admin_key.to_string()) {
let full_info: Vec<AdminTrackedInfo> = tracking
.read()
.unwrap()
.iter()
.map(|(_, tracked)| admin_view(&tracked.read().unwrap()))
.collect();
Some(EventStream! {
yield Event::json(&full_info).event("full_update");
let mut interval = time::interval(Duration::from_millis(100));
loop {
select!{
_ = interval.tick() =>{
for evt in evts_to_send(admin_queue){
//println!("{:?}", evt);
yield evt;
}
},
_ = &mut shutdown => break
}
}
})
} else {
None
}
}
fn state_update(tracked: &Tracked, evt_queues: &TrackingEventQueue, admin_queue: &AdminEventQueue) {
evt_queues
.read()
.unwrap()
@ -331,6 +391,10 @@ fn state_update(tracked: &Tracked, evt_queues: &TrackingEventQueue) {
.write()
.unwrap()
.push_back(Event::json(&admin_view(tracked)).event("self_info").into());
admin_queue
.write()
.unwrap()
.push_back(Event::json(&admin_view(tracked)).event("update").into());
}
#[put("/track/<id>/pos?<lat>&<long>")]
@ -340,10 +404,11 @@ fn store_pos(
long: f32,
tracking: &State<Tracking>,
evt_queues: &State<TrackingEventQueue>,
admin_queue: &State<AdminEventQueue>,
) {
if let Some(tracked) = tracking.read().unwrap().get(&id.to_string()) {
tracked.write().unwrap().pos = (lat, long);
state_update(&tracked.read().unwrap(), &evt_queues);
state_update(&tracked.read().unwrap(), &evt_queues, &admin_queue);
}
}
@ -354,6 +419,7 @@ fn set_state(
col: u8,
tracking: &State<Tracking>,
evt_queues: &State<TrackingEventQueue>,
admin_queue: &State<AdminEventQueue>,
) -> Option<()> {
let tracking_lock = tracking.read().unwrap();
let tracked = &mut tracking_lock.get(&id.to_string()).unwrap().write().unwrap();
@ -364,7 +430,7 @@ fn set_state(
{
*invisible = inv;
*color = col;
state_update(&tracked, &evt_queues);
state_update(&tracked, &evt_queues, &admin_queue);
Some(())
} else {
None
@ -393,7 +459,7 @@ fn send_coords(tracking: &Tracking, evt_queue: &TrackingEventQueue) {
}
}
fn clean_expired_evt(evt_queues: &TrackingEventQueue) {
fn clean_expired_evt(evt_queues: &TrackingEventQueue, admin_queue: &AdminEventQueue) {
for (_, queue) in evt_queues.read().unwrap().iter() {
let queue = &mut queue.write().unwrap();
while let Some(queued_evt) = queue.front() {
@ -404,10 +470,19 @@ fn clean_expired_evt(evt_queues: &TrackingEventQueue) {
}
}
}
let queue = &mut admin_queue.write().unwrap();
while let Some(queued_evt) = queue.front() {
if queued_evt.expired() {
queue.pop_front();
} else {
break;
}
}
}
#[launch]
async fn rocket() -> _ {
//TODO: read a config file on release
let tracking: Tracking = Arc::new(RwLock::new(HashMap::from([
(
"team00".to_string(),
@ -434,13 +509,27 @@ async fn rocket() -> _ {
.map(|(id, _)| (id.clone(), RwLock::new(VecDeque::new())))
.collect(),
));
let admin_evt_queue: AdminEventQueue = Arc::new(RwLock::new(VecDeque::new()));
let key: AdminKey = "root".to_string(); //TODO : random on release
println!("Admin token: {}", key);
let rocket = rocket::build()
.attach(Template::fairing())
.manage(tracking.clone())
.manage(evt_queue.clone())
.manage(admin_evt_queue.clone())
.manage(key)
.mount(
"/",
routes![index, store_pos, tracked_view, tracked_events, set_state],
routes![
index,
store_pos,
tracked_view,
tracked_events,
set_state,
admin_page,
admin_events,
admin_set_state,
],
)
.mount("/", FileServer::from(relative!("static")));
tokio::spawn(async move {
@ -449,7 +538,7 @@ async fn rocket() -> _ {
loop {
select! {
_ = coord_interval.tick() => send_coords(&tracking, &evt_queue),
_ = clean_interval.tick() => clean_expired_evt(&evt_queue),
_ = clean_interval.tick() => clean_expired_evt(&evt_queue, &admin_evt_queue),
}
}
});

View file

@ -77,6 +77,9 @@ function setup_map(){
}).addTo(map);
L.polyline(map_border, {color: 'red'}).addTo(map);
}
function setup_map_self(){
self_marker = L.marker([0,0], {"icon": icons[0] }).addTo(map);
self_marker.setZIndexOffset(1000);
self_marker.bindPopup(name);

View file

@ -1,166 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Traque | Client admin</title>
<!-- LEAFLET INCLUDE -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"
integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
crossorigin=""></script>
<!-- SOCKET.IO INCLUDE -->
<script src="/socket.io/socket.io.js"></script>
<style type="text/css">
#map {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 50%;
}
#right {
position: fixed;
width: 49%;
height: 98%;
top: 1%;
right: 0.5%;
}
.vieux { color: DarkOrchid; }
.tableFixHead { overflow: auto; height: 60%; }
.tableFixHead thead th { position: sticky; top: 0; z-index: 1; }
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th { background: Grey; }
tr:nth-child(even) { background-color: Silver; }
</style>
<script type="text/javascript" src="utils.js"></script>
</head>
<body>
<div id="map"></div>
<div id="right">
<div class="tableFixHead">
<table>
<thead><tr>
<th>ID</th>
<th>Mallette</th>
<th>Invisible</th>
<th>Brouillé</th>
<th>Tracker</th>
<th>Code Invisibilité</th>
<th>Code Brouillage</th>
<th>Npc</th>
<th>Last Update</th>
</tr></thead>
<tbody id="teamInfos">
</tbody>
</table>
</div>
<input id="popup"/><button id="sendPopup">Send popup to all clients</button><br/>
<br/>
<a href="https://dgnum.eu"><img src="/dgnum-logo.png" height=50px /></a><br/>
<span style="font-size: 0.8em">Merci à la <a href="https://dgnum.eu">Délégation Générale NUMérique de l'ENS</a>, qui héberge ce site.</span>
</div>
<script type="text/javascript">
//////////////////////////////////////////////////////////////////////////////
// SETUP MAP
setup_map();
map.on("dblclick", function(data){
socket.emit("newTracker", {"position": [data.latlng.lat, data.latlng.lng]});
});
//////////////////////////////////////////////////////////////////////////////
// UPDATE MAP
socket = io({rejectUnauthorized: false, auth: {type:"Admin"}});
setup_socket_common();
//////////////////////////////////////////////////////////////////////////////
// INTERACTION
var equipes = {};
var info_table = document.getElementById("teamInfos");
function sendUpdate(id){
var state = {};
state.mallette = document.getElementById(`${id}.mallette`).checked;
state.invisibility = document.getElementById(`${id}.invisibility`).checked;
state.blurred = document.getElementById(`${id}.blurred`).checked;
state.tracker = document.getElementById(`${id}.tracker`).checked;
state.npc = document.getElementById(`${id}.npc`).value;
socket.emit('setState', { id: id, state: state });
}
socket.on('update', function(data){
var id = data.id;
if(!(id in equipes)){
var row = `<td class="${data.vieux?"vieux":"conscrit"}">${id}</td>`;
row += `<td><input type="checkbox"
id="${id}.mallette"
onchange="sendUpdate('${id}')" /></td>`
row += `<td><input type="checkbox"
id="${id}.invisibility"
onchange="sendUpdate('${id}')" /></td>`
row += `<td><input type="checkbox"
id="${id}.blurred"
onchange="sendUpdate('${id}')" /></td>`
row += `<td><input type="checkbox"
id="${id}.tracker"
onchange="sendUpdate('${id}')" /></td>`
row += `<td><span id="${id}.code.invisi"></span>
<button onclick="socket.emit('newCode', {id:'${id}', code:'invisibility'})">
Add
</button>
</td>`;
row += `<td><span id="${id}.code.blurred"></span>
<button onclick="socket.emit('newCode', {id:'${id}', code:'blurred'})">
Add
</button>
</td>`;
row += `<td><input type="number" min=0 max=9 style="width: 40px"
id="${id}.npc"
onchange="sendUpdate('${id}')" /></td>`
row += `<td><span id="${id}.time"></span></td>`
info_table.innerHTML += `<tr>${row}</tr>`
for(i in equipes){
var equipe = equipes[i];
document.getElementById(`${i}.mallette`).checked = equipe.state.mallette;
document.getElementById(`${i}.invisibility`).checked = equipe.state.invisibility;
document.getElementById(`${i}.blurred`).checked = equipe.state.blurred;
document.getElementById(`${i}.tracker`).checked = equipe.state.tracker;
document.getElementById(`${i}.npc`).value = equipe.state.npc;
}
}
equipes[id] = data;
document.getElementById(`${id}.mallette`).checked = data.state.mallette;
document.getElementById(`${id}.invisibility`).checked = data.state.invisibility;
document.getElementById(`${id}.blurred`).checked = data.state.blurred;
document.getElementById(`${id}.tracker`).checked = data.state.tracker;
document.getElementById(`${id}.code.invisi`).innerHTML = data.codes.invisibility;
document.getElementById(`${id}.code.blurred`).innerHTML = data.codes.blurred;
document.getElementById(`${id}.npc`).value = data.state.npc;
var now = new Date();
document.getElementById(`${id}.time`).innerHTML =
`${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
});
document.querySelector('#sendPopup').addEventListener('click', function(){
const input = document.querySelector('#popup');
socket.emit("popup", {"content": input.value});
});
</script>
</body>
</html>

221
templates/admin.html.hbs Normal file
View file

@ -0,0 +1,221 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Traque | Client admin</title>
<!-- LEAFLET INCLUDE -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.8.0/dist/leaflet.css"
integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.8.0/dist/leaflet.js"
integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ=="
crossorigin=""></script>
<style type="text/css">
#map {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 50%;
}
#right {
position: fixed;
width: 49%;
height: 98%;
top: 1%;
right: 0.5%;
}
.vieux { color: DarkOrchid; }
.code_count { width: 90%; }
.tableFixHead { overflow: auto; height: 60%; }
.tableFixHead thead th { position: sticky; top: 0; z-index: 1; }
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th { background: Grey; }
tr:nth-child(even) { background-color: Silver; }
</style>
<script type="text/javascript" src="utils.js"></script>
</head>
<body>
<div id="map"></div>
<div id="right">
<div class="tableFixHead">
<table>
<thead><tr>
<th>Nom</th>
<th>Mallette</th>
<th>Tracker</th>
<th>Invisible</th>
<th>Brouillé</th>
<th>Code Invisibilité</th>
<th>Code Brouillage</th>
<th>Couleur</th>
<!-- <th>Last Update</th> -->
</tr></thead>
<tbody id="teamInfos">
</tbody>
</table>
</div>
<input id="popup"/><button id="sendPopup">Send popup to all clients</button><br/>
<br/>
<a href="https://dgnum.eu"><img src="/dgnum-logo.png" height=50px /></a><br/>
<span style="font-size: 0.8em">Merci à la <a href="https://dgnum.eu">Délégation Générale NUMérique de l'ENS</a>, qui héberge ce site.</span>
</div>
<script type="text/javascript">
setup_map();
// map.on("dblclick", function(data){
// socket.emit("newTracker", {"position": [data.latlng.lat, data.latlng.lng]});
// });
var equipes = {};
var equipes_markers = {};
var info_table = document.getElementById("teamInfos");
function show_update(id){
var equipe = equipes[id];
var state = equipe.state;
if("Vieux" in state){
state = state.Vieux;
document.getElementById(`${id}.invisibility`).checked = state.invisible;
document.getElementById(`${id}.color`).value = state.color;
} else {
state = state.Conscrit;
document.getElementById(`${id}.mallette`).checked = state.mallette;
document.getElementById(`${id}.invisibility`).checked = state.invisible;
document.getElementById(`${id}.blurred`).checked = state.blurred;
document.getElementById(`${id}.tracker`).checked = state.captured;
document.getElementById(`${id}.bonus.invisi`).value = state.invisibility_codes;
document.getElementById(`${id}.bonus.blurred`).value = state.blur_codes;
}
equipes_markers[id].setLatLng(equipe.pos);
equipes_markers[id].setIcon(icons[equipe.color]);
}
evtSource = new EventSource("/admin/events?tok={{tok}}");
function update(data) {
{{#if dbg}}console.log(data);{{/if}}
var id = data.id;
if(!(id in equipes)){
var row = "";
if("Vieux" in data.state){
row = `<td class="vieux">${data.name}</td>`;
row += `<td></td>`;
row += `<td></td>`;
row += `<td><input type="checkbox"
id="${id}.invisibility"
onchange="modifyVieux('${id}')" /></td>`;
row += `<td></td>`;
row += `<td></td>`;
row += `<td></td>`;
row += `<td><select id="${id}.color"
onchange="modifyVieux('${id}')" >
<option value=1>1- Tracker</option>
<option value=3>3- <img src="/icons/3.png" height=15px></option>
<option value=4>4- <img src="/icons/4.png" height=15px></option>
<option value=5>5- <img src="/icons/5.png" height=15px></option>
<option value=6>6- <img src="/icons/6.png" height=15px></option>
<option value=7>7- <img src="/icons/7.png" height=15px></option>
<option value=8>8- <img src="/icons/8.png" height=15px></option>
<option value=9>9- <img src="/icons/9.png" height=15px></option>
<option value=10>10- <img src="/icons/10.png" height=15px></option>
<option value=11>11- <img src="/icons/11.png" height=15px></option>
</select></td>`;
} else {
row = `<td class="conscrit">${data.name}</td>`;
row += `<td><input type="checkbox"
id="${id}.mallette"
onchange="modifyConscrit('${id}')" /></td>`
row += `<td><input type="checkbox"
id="${id}.tracker"
onchange="modifyConscrit('${id}')" /></td>`
row += `<td><input type="checkbox"
id="${id}.invisibility"
onchange="modifyConscrit('${id}')" /></td>`;
row += `<td><input type="checkbox"
id="${id}.blurred"
onchange="modifyConscrit('${id}')" /></td>`
row += `<td><input type="number" min="0"
id="${id}.bonus.invisi"
class="code_count"
onchange="modifyConscrit('${id}')" />
</td>`;
row += `<td><input type="number" min="0"
id="${id}.bonus.blurred"
class="code_count"
onchange="modifyConscrit('${id}')" />
</td>`;
row += `<td></td>`;
}
info_table.innerHTML += `<tr>${row}</tr>`
equipes[id] = data;
equipes_markers[id] = L.marker([0,0], {"icon": icons[0] }).addTo(map);
equipes_markers[id].bindPopup(data.name);
setTimeout(function (){
for(i in equipes){
show_update(i);
}
}, 10);
} else {
equipes[id] = data;
show_update(id);
}
};
evtSource.addEventListener("update", (event) => {
data = JSON.parse(event.data);
update(data);
});
evtSource.addEventListener("full_update", (event) => {
data = JSON.parse(event.data);
info_table.innerHTML = "";
equipes = {};
for(i in equipes_markers){
equipes_markers[i].remove();
}
equipes_markers = {};
for (tracked of data) {
update(tracked);
}
});
function modifyVieux(id){
state = {
Vieux: {
invisible: document.getElementById(`${id}.invisibility`).checked,
color: document.getElementById(`${id}.color`).value - 0,
}
};
fetch(`/admin/${id}?tok={{tok}}`, {
method: "PATCH",
body: JSON.stringify(state)
});
}
function modifyConscrit(id){
state = {
Conscrit: {
mallette: document.getElementById(`${id}.mallette`).checked,
invisible: document.getElementById(`${id}.invisibility`).checked,
blurred: document.getElementById(`${id}.blurred`).checked,
captured: document.getElementById(`${id}.tracker`).checked,
invisibility_codes: document.getElementById(`${id}.bonus.invisi`).value - 0,
blur_codes: document.getElementById(`${id}.bonus.blurred`).value - 0,
}
};
fetch(`/admin/${id}?tok={{tok}}`, {
method: "PATCH",
body: JSON.stringify(state)
});
}
</script>
</body>
</html>

View file

@ -41,6 +41,7 @@
dbg = {{dbg}};
setup_map();
setup_map_self();
// {{#if gpslog}}setup_geoLoc();{{/if}}
//////////////////////////////////////////////////////////////////////////////

View file

@ -67,6 +67,7 @@
dbg = {{dbg}};
setup_map();
setup_map_self();
// {{#if gpslog}}setup_geoLoc();{{/if}}
//////////////////////////////////////////////////////////////////////////////