39 Commits

Author SHA1 Message Date
LinlyBoi
7615b24e8f Obama 2022-12-26 23:40:52 +02:00
LinlyBoi
dd4685d8ae yes 2022-12-26 23:05:40 +02:00
LinlyBoi
1e195f12e2 YESS? 2022-12-26 23:01:23 +02:00
LinlyBoi
7a1e385802 obama 2022-12-26 22:56:57 +02:00
LinlyBoi
b766ef2ee4 learning food (I burnty my food for htis) 2022-12-26 21:51:22 +02:00
LinlyBoi
f41ea8e67c mum 2022-12-26 21:42:00 +02:00
LinlyBoi
8acd2e701d YESS 2022-12-26 09:32:46 +02:00
LinlyBoi
6002cfb866 Yes 2022-12-26 09:23:07 +02:00
LinlyBoi
94686d5815 FINAL BEFORE SUBMITION :( 2022-12-26 01:03:42 +02:00
LinlyBoi
c93bb7ad17 pog 2022-12-26 00:04:10 +02:00
LinlyBoi
598718f9d8 WILL 100% WORK THIS TIME 2022-12-25 23:37:07 +02:00
LinlyBoi
6adfa1429e obama pls 2022-12-25 23:30:34 +02:00
LinlyBoi
c054995509 INSHALLAH SUI 2022-12-25 23:22:37 +02:00
LinlyBoi
f6ff2f1212 AAAA 2022-12-25 23:14:40 +02:00
LinlyBoi
bb2d30e890 BOOM 2022-12-25 22:35:16 +02:00
LinlyBoi
3e9a85a2a7 I have no idea what I'm dong 2022-12-25 21:42:46 +02:00
LinlyBoi
cd2092a7c9 es 2022-12-25 13:46:06 +02:00
LinlyBoi
12b79ed17c yes 2022-12-25 13:24:35 +02:00
LinlyBoi
63e1ae6f0d Consistency added 2022-12-25 13:18:28 +02:00
LinlyBoi
f9dfb4bf64 radars and vehicles 2022-12-25 13:10:38 +02:00
LinlyBoi
298b35af4c shorter content 2022-12-25 12:11:02 +02:00
LinlyBoi
e4e8b1a79d FIRE 2022-12-25 10:59:51 +02:00
LinlyBoi
9ae78e01cc no 2022-12-25 10:54:14 +02:00
LinlyBoi
33e816e820 yes 2022-12-25 10:48:53 +02:00
LinlyBoi
af3714bcfa testing headers 2022-12-25 10:46:24 +02:00
LinlyBoi
71f261da52 plaint text type plas 2022-12-25 10:42:31 +02:00
LinlyBoi
b09d9e7c54 neater strings 2022-12-25 10:21:36 +02:00
LinlyBoi
d7a93d5a3f tactical nuke..no json :( 2022-12-25 10:19:11 +02:00
LinlyBoi
523bae94f2 snapped async fn 2022-12-25 10:10:50 +02:00
LinlyBoi
f1aeeed085 Thanos did a thing 2022-12-25 10:09:06 +02:00
LinlyBoi
f456749a66 ??idkfrontend things? 2022-12-25 00:13:06 +02:00
LinlyBoi
87d96d938f added test api function that just returns a string thank you obama 2022-12-24 21:29:20 +02:00
LinlyBoi
d012926261 a state of no errors 2022-12-24 21:06:13 +02:00
LinlyBoi
77002200a3 Before I nuke my life 2022-12-24 20:16:36 +02:00
LinlyBoi
367d778ec1 ?? 2022-12-24 15:03:04 +02:00
LinlyBoi
d466c1199d Its friday and the drivers are happy 2022-12-23 21:54:20 +02:00
LinlyBoi
bcf3ec0d8c TyPe MiSmAtCh pGdAtE eXpEcTeD StRiNg 2022-12-23 19:35:08 +00:00
LinlyBoi
99ec37991e third time's a charm 2022-12-23 19:10:33 +02:00
LinlyBoi
f99e1504f6 bum 2022-12-23 17:07:10 +00:00
21 changed files with 1614 additions and 125 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
/target
.env

154
Cargo.lock generated
View File

@@ -222,6 +222,15 @@ dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]]
name = "anymap2"
version = "0.13.0"
@@ -239,7 +248,7 @@ name = "backend"
version = "0.1.0"
dependencies = [
"actix-web",
"chrono",
"chrono 0.2.25",
"common",
"diesel",
"dotenv",
@@ -356,6 +365,28 @@ dependencies = [
"time 0.1.45",
]
[[package]]
name = "chrono"
version = "0.4.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f"
dependencies = [
"iana-time-zone",
"num-integer",
"num-traits",
"winapi",
]
[[package]]
name = "codespan-reporting"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e"
dependencies = [
"termcolor",
"unicode-width",
]
[[package]]
name = "common"
version = "0.1.0"
@@ -391,6 +422,12 @@ dependencies = [
"version_check",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"
[[package]]
name = "cpufeatures"
version = "0.2.5"
@@ -419,11 +456,62 @@ dependencies = [
"typenum",
]
[[package]]
name = "cxx"
version = "1.0.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5add3fc1717409d029b20c5b6903fc0c0b02fa6741d820054f4a2efa5e5816fd"
dependencies = [
"cc",
"cxxbridge-flags",
"cxxbridge-macro",
"link-cplusplus",
]
[[package]]
name = "cxx-build"
version = "1.0.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c87959ba14bc6fbc61df77c3fcfe180fc32b93538c4f1031dd802ccb5f2ff0"
dependencies = [
"cc",
"codespan-reporting",
"once_cell",
"proc-macro2",
"quote",
"scratch",
"syn",
]
[[package]]
name = "cxxbridge-flags"
version = "1.0.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69a3e162fde4e594ed2b07d0f83c6c67b745e7f28ce58c6df5e6b6bef99dfb59"
[[package]]
name = "cxxbridge-macro"
version = "1.0.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e7e2adeb6a0d4a282e581096b06e1791532b7d576dcde5ccd9382acf55db8e6"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "db-frontend"
version = "0.1.0"
dependencies = [
"common",
"gloo",
"gloo-net",
"serde",
"serde_json",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"yew",
]
@@ -457,6 +545,7 @@ checksum = "68c186a7418a2aac330bb76cde82f16c36b03a66fb91db32d20214311f9f6545"
dependencies = [
"bitflags",
"byteorder",
"chrono 0.4.23",
"diesel_derives",
"itoa",
"pq-sys",
@@ -845,6 +934,30 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"
[[package]]
name = "iana-time-zone"
version = "0.1.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"winapi",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca"
dependencies = [
"cxx",
"cxx-build",
]
[[package]]
name = "idna"
version = "0.3.0"
@@ -910,6 +1023,15 @@ version = "0.2.138"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db6d7e329c562c5dfab7a46a2afabc8b987ab9a4834c9d1ca04dc54c1546cef8"
[[package]]
name = "link-cplusplus"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5"
dependencies = [
"cc",
]
[[package]]
name = "local-channel"
version = "0.1.3"
@@ -1302,6 +1424,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "scratch"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddccb15bcce173023b3fedd9436f882a0739b8dfb45e4f6b6002bee5929f61b2"
[[package]]
name = "semver"
version = "1.0.14"
@@ -1419,6 +1547,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "termcolor"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
dependencies = [
"winapi-util",
]
[[package]]
name = "thiserror"
version = "1.0.37"
@@ -1608,6 +1745,12 @@ dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-width"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b"
[[package]]
name = "url"
version = "2.3.1"
@@ -1735,6 +1878,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"

View File

@@ -6,7 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
diesel = { version = "2.0.0",features = ["postgres","r2d2"] }
diesel = { version = "2.0.0",features = ["postgres","r2d2","chrono"] }
dotenv = "0.15"
chrono = "0.2.25"
common = { path = "../common"}

View File

@@ -1,4 +1,5 @@
use crate::models::{Admin, AdminEmail, NewAdmin, NewAdminEmail};
use common::CommonAdmin;
use diesel::prelude::*;
pub fn listadmins(connection: &mut PgConnection) -> String {
@@ -38,3 +39,17 @@ pub fn listadminmails(connection: &mut PgConnection) {
println!("{} {}", addmail.email, addmail.admin_id);
}
}
pub fn get_admin(connection: &mut PgConnection, admin_id: i32) -> CommonAdmin {
use crate::schema::admins::dsl::*;
let admin = &mut admins
.filter(id.eq(admin_id))
.limit(1)
.load::<Admin>(connection)
.expect("no admins :(")[0];
return CommonAdmin {
id: admin.id,
name: String::from(&admin.name),
address: String::from(&admin.address),
};
}

View File

@@ -1,21 +1,38 @@
use diesel::prelude::*;
use crate::models::{Driver, NewDriver};
use common::CommonDriver;
use diesel::{prelude::*, query_builder::SqlQuery, sql_query};
pub fn listdrivers(connection: &mut PgConnection)
{
use crate::schema::drivers::dsl::*;
let queury = drivers.load::<Driver>(connection).expect("KANKER");
for driver in queury
{
println!("{} {}",driver.name ,driver.address);
pub fn listdrivers(connection: &mut PgConnection) -> Vec<CommonDriver> {
let query = sql_query("SELECT * FROM drivers WHERE id = 10").load::<Driver>(connection);
let mut drivers: Vec<CommonDriver> = Vec::new();
for driver in query.unwrap() {
drivers.push(CommonDriver {
id: driver.id,
name: driver.name,
address: driver.address,
});
}
return drivers;
}
pub fn addriver(connection: &mut PgConnection, new_driver: NewDriver) {
use crate::schema::drivers::dsl::*;
diesel::insert_into(drivers)
.values(&new_driver)
.execute(connection)
.expect("Couldn't insert new driver :)");
}
pub fn get_driver(connection: &mut PgConnection, driver_id: i32) -> CommonDriver {
use crate::schema::drivers::dsl::*;
let driver = &mut drivers
.filter(id.eq(driver_id))
.limit(1)
.load::<Driver>(connection)
.expect("no drivers :(")[0];
return CommonDriver {
id: driver.id,
name: String::from(&driver.name),
address: String::from(&driver.address),
};
}

View File

@@ -1,24 +1,20 @@
use diesel::{prelude::*, data_types::PgDate};
use crate::schema::*;
use diesel::{data_types::PgDate, prelude::*};
//Admins
#[derive(Queryable, Debug, AsChangeset, Identifiable)]
pub
struct Admin {
pub struct Admin {
pub id: i32,
pub name: String,
pub address: String
pub address: String,
}
#[derive(Insertable)]
#[diesel(table_name = admins)]
pub
struct NewAdmin<'a> {
pub struct NewAdmin<'a> {
pub id: i32,
pub name: &'a str,
pub address: &'a str
pub address: &'a str,
}
#[derive(Queryable, AsChangeset, Associations)]
@@ -36,19 +32,19 @@ pub struct NewAdminEmail<'a> {
pub email: &'a str,
}
//Ticket things
#[derive(Queryable)]
pub struct Ticket {
pub id: i32,
pub category: String,
pub description: String,
pub issue_date: PgDate
pub issue_date: PgDate,
}
#[derive(Insertable)]
#[diesel(table_name = tickets)]
pub struct NewTicket<'a> {
pub id: i32,
pub category: &'a str,
pub description: &'a str,
}
@@ -72,7 +68,8 @@ pub struct AutoIssuedTicket<'a> {
}
//Drivers
#[derive(Queryable,AsChangeset,Identifiable)]
#[derive(Queryable, AsChangeset, Identifiable, QueryableByName)]
#[table_name = "drivers"]
pub struct Driver {
pub id: i32,
pub name: String,
@@ -83,8 +80,7 @@ pub struct Driver {
#[derive(Insertable)]
#[diesel(table_name = drivers)]
pub
struct NewDriver<'a> {
pub struct NewDriver<'a> {
pub id: i32,
pub name: &'a str,
pub address: &'a str,
@@ -93,14 +89,21 @@ struct NewDriver<'a> {
}
//Vehicles
#[derive(Queryable,AsChangeset)]
#[diesel(belongs_to(Driver))]
#[derive(Queryable, QueryableByName)]
#[diesel(belongs_to(Driver), table_name = vehicles)]
pub struct Vehicle {
pub model: Option<String>,
pub color: Option<String>,
pub chasse_num: i32,
pub chasse_num: Option<i32>,
pub plate_num: String,
pub vehicle_type: String,
pub owner: i32
pub category: String,
pub owner: Option<i32>,
}
#[derive(Queryable)]
pub struct Radar {
pub id: i32,
pub category: Option<String>,
pub address: Option<String>,
}

View File

@@ -0,0 +1,19 @@
use common::CommonRadar;
use diesel::prelude::*;
use diesel::PgConnection;
use crate::models::Radar;
pub fn get_radar(connection: &mut PgConnection, radar_id: i32) -> CommonRadar {
use crate::schema::radars::dsl::*;
let radar = &mut radars
.filter(id.eq(radar_id))
.limit(1)
.load::<Radar>(connection)
.expect("no radars :(")[0];
return CommonRadar {
id: radar.id,
category: radar.category.clone(),
address: radar.address.clone(),
};
}

View File

@@ -73,10 +73,9 @@ diesel::table! {
}
diesel::table! {
radars (serialnumber) {
serialnumber -> Int4,
#[sql_name = "type"]
type_ -> Nullable<Text>,
radars (id) {
id -> Int4,
category -> Nullable<Text>,
address -> Nullable<Text>,
}
}

View File

@@ -1,4 +1,7 @@
use crate::models::{AutoIssuedTicket, IssuedTicket, NewTicket, Ticket};
use crate::{
models::{AutoIssuedTicket, IssuedTicket, NewTicket, Ticket},
schema::{drivers, issued_tickets, tickets},
};
use common::CommonTicket;
use diesel::prelude::*;
@@ -10,20 +13,27 @@ pub fn create_ticket(connection: &mut PgConnection, ticket: NewTicket) {
.expect("Didn't save ticket AAAAAA");
}
pub fn get_tickets(connection: &mut PgConnection, amount: i64) -> Vec<CommonTicket> {
use crate::schema::tickets::dsl::*;
let results = tickets
.limit(amount)
.load::<Ticket>(connection)
.expect("KANKER TIKET");
return results
pub fn get_tickets(connection: &mut PgConnection, driver_id: i32) -> Vec<CommonTicket> {
//Chonky join function for the sake of my life :))
let join = tickets::table
.left_join(issued_tickets::table)
.select((
tickets::id,
tickets::category,
tickets::description,
tickets::issue_date,
))
.filter(issued_tickets::driver.eq(driver_id));
let tickets_by_driver = join.load::<Ticket>(connection).expect("oh no!");
let common_ticket_output = tickets_by_driver
.iter()
.map(|ticket| CommonTicket {
id: ticket.id,
category: String::from(&ticket.category),
description: String::from(&ticket.description),
})
.collect(); //Shoves everything to a vector
.collect();
return common_ticket_output;
}
pub fn get_ticket(connection: &mut PgConnection, tickid: i32) -> CommonTicket {

View File

@@ -0,0 +1,41 @@
use common::CommonVehicle;
use diesel::prelude::*;
use diesel::PgConnection;
use crate::models::Vehicle;
pub fn get_vehicle(connection: &mut PgConnection, vehicle_id: String) -> CommonVehicle {
use crate::schema::vehicles::dsl::*;
let vehicle = &mut vehicles
.filter(plate_num.eq(vehicle_id))
.limit(1)
.load::<Vehicle>(connection)
.expect("no vehicles :(")[0];
return CommonVehicle {
model: vehicle.model.clone(),
color: vehicle.color.clone(),
chasse_num: vehicle.chasse_num,
plate_num: vehicle.plate_num.clone(),
vehicle_type: vehicle.vehicle_type.clone(),
category: vehicle.category.clone(),
owner: vehicle.owner,
};
}
// pub fn insert_vehicle(connection: &mut PgConnection, vehicle: CommonVehicle) -> bool {
// use crate::schema::vehicles::dsl::*;
// //convert CommonVehicle to Vehicle
// let vehicle = Vehicle {
// model: vehicle.model,
// color: vehicle.color,
// chasse_num: vehicle.chasse_num,
// plate_num: vehicle.plate_num,
// vehicle_type: vehicle.vehicle_type,
// category: vehicle.category,
// owner: vehicle.owner,
// };
// diesel::insert_into(vehicles)
// .values(&vehicle)
// .execute(connection)
// .is_ok()
// }

View File

@@ -15,3 +15,32 @@ pub struct CommonAdmin {
pub name: String,
pub address: String,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CommonDriver {
pub id: i32,
pub name: String,
pub address: String,
}
//generate common radar struct
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CommonRadar {
pub id: i32,
pub category: Option<String>,
pub address: Option<String>,
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CommonVehicle {
pub model: Option<String>,
pub category: String,
pub color: Option<String>,
pub chasse_num: Option<i32>,
pub plate_num: String,
pub vehicle_type: String,
pub owner: Option<i32>,
}

View File

@@ -8,3 +8,20 @@ edition = "2021"
[dependencies]
yew = { version = "0.20.0", features = ["csr"] }
common = { path = "../common"}
gloo-net = {version = "0.2"}
gloo = "0.8"
serde = { version = "1.0.126", features = ["derive"] }
serde_json = "1.0.64"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
[dependencies.web-sys]
version = "0.3"
features = [
"Headers",
"Request",
"RequestInit",
"RequestMode",
"Response",
"Window",
]

View File

@@ -0,0 +1,678 @@
let wasm;
const heap = new Array(32).fill(undefined);
heap.push(undefined, null, true, false);
function getObject(idx) { return heap[idx]; }
let WASM_VECTOR_LEN = 0;
let cachedUint8Memory0 = new Uint8Array();
function getUint8Memory0() {
if (cachedUint8Memory0.byteLength === 0) {
cachedUint8Memory0 = new Uint8Array(wasm.memory.buffer);
}
return cachedUint8Memory0;
}
const cachedTextEncoder = new TextEncoder('utf-8');
const encodeString = (typeof cachedTextEncoder.encodeInto === 'function'
? function (arg, view) {
return cachedTextEncoder.encodeInto(arg, view);
}
: function (arg, view) {
const buf = cachedTextEncoder.encode(arg);
view.set(buf);
return {
read: arg.length,
written: buf.length
};
});
function passStringToWasm0(arg, malloc, realloc) {
if (realloc === undefined) {
const buf = cachedTextEncoder.encode(arg);
const ptr = malloc(buf.length);
getUint8Memory0().subarray(ptr, ptr + buf.length).set(buf);
WASM_VECTOR_LEN = buf.length;
return ptr;
}
let len = arg.length;
let ptr = malloc(len);
const mem = getUint8Memory0();
let offset = 0;
for (; offset < len; offset++) {
const code = arg.charCodeAt(offset);
if (code > 0x7F) break;
mem[ptr + offset] = code;
}
if (offset !== len) {
if (offset !== 0) {
arg = arg.slice(offset);
}
ptr = realloc(ptr, len, len = offset + arg.length * 3);
const view = getUint8Memory0().subarray(ptr + offset, ptr + len);
const ret = encodeString(arg, view);
offset += ret.written;
}
WASM_VECTOR_LEN = offset;
return ptr;
}
function isLikeNone(x) {
return x === undefined || x === null;
}
let cachedInt32Memory0 = new Int32Array();
function getInt32Memory0() {
if (cachedInt32Memory0.byteLength === 0) {
cachedInt32Memory0 = new Int32Array(wasm.memory.buffer);
}
return cachedInt32Memory0;
}
const cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
cachedTextDecoder.decode();
function getStringFromWasm0(ptr, len) {
return cachedTextDecoder.decode(getUint8Memory0().subarray(ptr, ptr + len));
}
let heap_next = heap.length;
function addHeapObject(obj) {
if (heap_next === heap.length) heap.push(heap.length + 1);
const idx = heap_next;
heap_next = heap[idx];
heap[idx] = obj;
return idx;
}
function dropObject(idx) {
if (idx < 36) return;
heap[idx] = heap_next;
heap_next = idx;
}
function takeObject(idx) {
const ret = getObject(idx);
dropObject(idx);
return ret;
}
function debugString(val) {
// primitive types
const type = typeof val;
if (type == 'number' || type == 'boolean' || val == null) {
return `${val}`;
}
if (type == 'string') {
return `"${val}"`;
}
if (type == 'symbol') {
const description = val.description;
if (description == null) {
return 'Symbol';
} else {
return `Symbol(${description})`;
}
}
if (type == 'function') {
const name = val.name;
if (typeof name == 'string' && name.length > 0) {
return `Function(${name})`;
} else {
return 'Function';
}
}
// objects
if (Array.isArray(val)) {
const length = val.length;
let debug = '[';
if (length > 0) {
debug += debugString(val[0]);
}
for(let i = 1; i < length; i++) {
debug += ', ' + debugString(val[i]);
}
debug += ']';
return debug;
}
// Test for built-in
const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val));
let className;
if (builtInMatches.length > 1) {
className = builtInMatches[1];
} else {
// Failed to match the standard '[object ClassName]'
return toString.call(val);
}
if (className == 'Object') {
// we're a user defined class or Object
// JSON.stringify avoids problems with cycles, and is generally much
// easier than looping through ownProperties of `val`.
try {
return 'Object(' + JSON.stringify(val) + ')';
} catch (_) {
return 'Object';
}
}
// errors
if (val instanceof Error) {
return `${val.name}: ${val.message}\n${val.stack}`;
}
// TODO we could test for more things here, like `Set`s and `Map`s.
return className;
}
function makeMutClosure(arg0, arg1, dtor, f) {
const state = { a: arg0, b: arg1, cnt: 1, dtor };
const real = (...args) => {
// First up with a closure we increment the internal reference
// count. This ensures that the Rust closure environment won't
// be deallocated while we're invoking it.
state.cnt++;
const a = state.a;
state.a = 0;
try {
return f(a, state.b, ...args);
} finally {
if (--state.cnt === 0) {
wasm.__wbindgen_export_2.get(state.dtor)(a, state.b);
} else {
state.a = a;
}
}
};
real.original = state;
return real;
}
let stack_pointer = 32;
function addBorrowedObject(obj) {
if (stack_pointer == 1) throw new Error('out of js stack');
heap[--stack_pointer] = obj;
return stack_pointer;
}
function __wbg_adapter_18(arg0, arg1, arg2) {
try {
wasm._dyn_core__ops__function__FnMut___A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h9380123c3ed0eddb(arg0, arg1, addBorrowedObject(arg2));
} finally {
heap[stack_pointer++] = undefined;
}
}
function __wbg_adapter_21(arg0, arg1, arg2) {
wasm._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__h414630ac9216cad4(arg0, arg1, addHeapObject(arg2));
}
let cachedUint32Memory0 = new Uint32Array();
function getUint32Memory0() {
if (cachedUint32Memory0.byteLength === 0) {
cachedUint32Memory0 = new Uint32Array(wasm.memory.buffer);
}
return cachedUint32Memory0;
}
function getArrayJsValueFromWasm0(ptr, len) {
const mem = getUint32Memory0();
const slice = mem.subarray(ptr / 4, ptr / 4 + len);
const result = [];
for (let i = 0; i < slice.length; i++) {
result.push(takeObject(slice[i]));
}
return result;
}
function handleError(f, args) {
try {
return f.apply(this, args);
} catch (e) {
wasm.__wbindgen_exn_store(addHeapObject(e));
}
}
async function load(module, imports) {
if (typeof Response === 'function' && module instanceof Response) {
if (typeof WebAssembly.instantiateStreaming === 'function') {
try {
return await WebAssembly.instantiateStreaming(module, imports);
} catch (e) {
if (module.headers.get('Content-Type') != 'application/wasm') {
console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
} else {
throw e;
}
}
}
const bytes = await module.arrayBuffer();
return await WebAssembly.instantiate(bytes, imports);
} else {
const instance = await WebAssembly.instantiate(module, imports);
if (instance instanceof WebAssembly.Instance) {
return { instance, module };
} else {
return instance;
}
}
}
function getImports() {
const imports = {};
imports.wbg = {};
imports.wbg.__wbindgen_string_get = function(arg0, arg1) {
const obj = getObject(arg1);
const ret = typeof(obj) === 'string' ? obj : undefined;
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbindgen_string_new = function(arg0, arg1) {
const ret = getStringFromWasm0(arg0, arg1);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
};
imports.wbg.__wbg_listenerid_12315eee21527820 = function(arg0, arg1) {
const ret = getObject(arg1).__yew_listener_id;
getInt32Memory0()[arg0 / 4 + 1] = isLikeNone(ret) ? 0 : ret;
getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret);
};
imports.wbg.__wbg_setlistenerid_3183aae8fa5840fb = function(arg0, arg1) {
getObject(arg0).__yew_listener_id = arg1 >>> 0;
};
imports.wbg.__wbg_subtreeid_e348577f7ef777e3 = function(arg0, arg1) {
const ret = getObject(arg1).__yew_subtree_id;
getInt32Memory0()[arg0 / 4 + 1] = isLikeNone(ret) ? 0 : ret;
getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret);
};
imports.wbg.__wbg_setsubtreeid_d32e6327eef1f7fc = function(arg0, arg1) {
getObject(arg0).__yew_subtree_id = arg1 >>> 0;
};
imports.wbg.__wbg_cachekey_b61393159c57fd7b = function(arg0, arg1) {
const ret = getObject(arg1).__yew_subtree_cache_key;
getInt32Memory0()[arg0 / 4 + 1] = isLikeNone(ret) ? 0 : ret;
getInt32Memory0()[arg0 / 4 + 0] = !isLikeNone(ret);
};
imports.wbg.__wbg_setcachekey_80183b7cfc421143 = function(arg0, arg1) {
getObject(arg0).__yew_subtree_cache_key = arg1 >>> 0;
};
imports.wbg.__wbg_error_f851667af71bcfc6 = function(arg0, arg1) {
try {
console.error(getStringFromWasm0(arg0, arg1));
} finally {
wasm.__wbindgen_free(arg0, arg1);
}
};
imports.wbg.__wbg_new_abda76e883ba8a5f = function() {
const ret = new Error();
return addHeapObject(ret);
};
imports.wbg.__wbg_stack_658279fe44541cf6 = function(arg0, arg1) {
const ret = getObject(arg1).stack;
const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbindgen_object_drop_ref = function(arg0) {
takeObject(arg0);
};
imports.wbg.__wbindgen_cb_drop = function(arg0) {
const obj = takeObject(arg0).original;
if (obj.cnt-- == 1) {
obj.a = 0;
return true;
}
const ret = false;
return ret;
};
imports.wbg.__wbindgen_is_undefined = function(arg0) {
const ret = getObject(arg0) === undefined;
return ret;
};
imports.wbg.__wbg_error_71d6845bf00a930f = function(arg0, arg1) {
var v0 = getArrayJsValueFromWasm0(arg0, arg1).slice();
wasm.__wbindgen_free(arg0, arg1 * 4);
console.error(...v0);
};
imports.wbg.__wbg_instanceof_Window_acc97ff9f5d2c7b4 = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof Window;
} catch {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_document_3ead31dbcad65886 = function(arg0) {
const ret = getObject(arg0).document;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_fetch_0fe04905cccfc2aa = function(arg0, arg1) {
const ret = getObject(arg0).fetch(getObject(arg1));
return addHeapObject(ret);
};
imports.wbg.__wbg_body_3cb4b4042b9a632b = function(arg0) {
const ret = getObject(arg0).body;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_createElement_976dbb84fe1661b5 = function() { return handleError(function (arg0, arg1, arg2) {
const ret = getObject(arg0).createElement(getStringFromWasm0(arg1, arg2));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_createElementNS_1561aca8ee3693c0 = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
const ret = getObject(arg0).createElementNS(arg1 === 0 ? undefined : getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_createTextNode_300f845fab76642f = function(arg0, arg1, arg2) {
const ret = getObject(arg0).createTextNode(getStringFromWasm0(arg1, arg2));
return addHeapObject(ret);
};
imports.wbg.__wbg_instanceof_Response_eaa426220848a39e = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof Response;
} catch {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_text_1169d752cc697903 = function() { return handleError(function (arg0) {
const ret = getObject(arg0).text();
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_newwithstrandinit_05d7180788420c40 = function() { return handleError(function (arg0, arg1, arg2) {
const ret = new Request(getStringFromWasm0(arg0, arg1), getObject(arg2));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_instanceof_ShadowRoot_76b32ccdae10a710 = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof ShadowRoot;
} catch {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_host_57eec05a2624bc1b = function(arg0) {
const ret = getObject(arg0).host;
return addHeapObject(ret);
};
imports.wbg.__wbg_value_ccb32485ee1b3928 = function(arg0, arg1) {
const ret = getObject(arg1).value;
const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbg_setvalue_df64bc6794c098f2 = function(arg0, arg1, arg2) {
getObject(arg0).value = getStringFromWasm0(arg1, arg2);
};
imports.wbg.__wbg_setchecked_f1e1f3e62cdca8e7 = function(arg0, arg1) {
getObject(arg0).checked = arg1 !== 0;
};
imports.wbg.__wbg_value_b2a620d34c663701 = function(arg0, arg1) {
const ret = getObject(arg1).value;
const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbg_setvalue_e5b519cca37d82a7 = function(arg0, arg1, arg2) {
getObject(arg0).value = getStringFromWasm0(arg1, arg2);
};
imports.wbg.__wbg_instanceof_Element_33bd126d58f2021b = function(arg0) {
let result;
try {
result = getObject(arg0) instanceof Element;
} catch {
result = false;
}
const ret = result;
return ret;
};
imports.wbg.__wbg_namespaceURI_e19c7be2c60e5b5c = function(arg0, arg1) {
const ret = getObject(arg1).namespaceURI;
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbg_setinnerHTML_32081d8a164e6dc4 = function(arg0, arg1, arg2) {
getObject(arg0).innerHTML = getStringFromWasm0(arg1, arg2);
};
imports.wbg.__wbg_outerHTML_bf662bdff92e5910 = function(arg0, arg1) {
const ret = getObject(arg1).outerHTML;
const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbg_children_67776b4810f38b6a = function(arg0) {
const ret = getObject(arg0).children;
return addHeapObject(ret);
};
imports.wbg.__wbg_removeAttribute_beaed7727852af78 = function() { return handleError(function (arg0, arg1, arg2) {
getObject(arg0).removeAttribute(getStringFromWasm0(arg1, arg2));
}, arguments) };
imports.wbg.__wbg_setAttribute_d8436c14a59ab1af = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).setAttribute(getStringFromWasm0(arg1, arg2), getStringFromWasm0(arg3, arg4));
}, arguments) };
imports.wbg.__wbg_bubbles_03eed164b4feeaf1 = function(arg0) {
const ret = getObject(arg0).bubbles;
return ret;
};
imports.wbg.__wbg_cancelBubble_8c0bdf21c08f1717 = function(arg0) {
const ret = getObject(arg0).cancelBubble;
return ret;
};
imports.wbg.__wbg_composedPath_160ed014dc4d787f = function(arg0) {
const ret = getObject(arg0).composedPath();
return addHeapObject(ret);
};
imports.wbg.__wbg_addEventListener_1fc744729ac6dc27 = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).addEventListener(getStringFromWasm0(arg1, arg2), getObject(arg3), getObject(arg4));
}, arguments) };
imports.wbg.__wbg_removeEventListener_b10f1a66647f3aa0 = function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) {
getObject(arg0).removeEventListener(getStringFromWasm0(arg1, arg2), getObject(arg3), arg4 !== 0);
}, arguments) };
imports.wbg.__wbg_parentNode_e397bbbe28be7b28 = function(arg0) {
const ret = getObject(arg0).parentNode;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_parentElement_0cffb3ceb0f107bd = function(arg0) {
const ret = getObject(arg0).parentElement;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_lastChild_a2f5ed739809bb31 = function(arg0) {
const ret = getObject(arg0).lastChild;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_nextSibling_62338ec2a05607b4 = function(arg0) {
const ret = getObject(arg0).nextSibling;
return isLikeNone(ret) ? 0 : addHeapObject(ret);
};
imports.wbg.__wbg_setnodeValue_4077cafeefd0725e = function(arg0, arg1, arg2) {
getObject(arg0).nodeValue = arg1 === 0 ? undefined : getStringFromWasm0(arg1, arg2);
};
imports.wbg.__wbg_textContent_77bd294928962f93 = function(arg0, arg1) {
const ret = getObject(arg1).textContent;
var ptr0 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
var len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbg_appendChild_e513ef0e5098dfdd = function() { return handleError(function (arg0, arg1) {
const ret = getObject(arg0).appendChild(getObject(arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_insertBefore_9f2d2defb9471006 = function() { return handleError(function (arg0, arg1, arg2) {
const ret = getObject(arg0).insertBefore(getObject(arg1), getObject(arg2));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_removeChild_6751e9ca5d9aaf00 = function() { return handleError(function (arg0, arg1) {
const ret = getObject(arg0).removeChild(getObject(arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_get_57245cc7d7c7619d = function(arg0, arg1) {
const ret = getObject(arg0)[arg1 >>> 0];
return addHeapObject(ret);
};
imports.wbg.__wbg_from_7ce3cb27cb258569 = function(arg0) {
const ret = Array.from(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_length_6e3bbe7c8bd4dbd8 = function(arg0) {
const ret = getObject(arg0).length;
return ret;
};
imports.wbg.__wbg_newnoargs_b5b063fc6c2f0376 = function(arg0, arg1) {
const ret = new Function(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
};
imports.wbg.__wbg_call_97ae9d8645dc388b = function() { return handleError(function (arg0, arg1) {
const ret = getObject(arg0).call(getObject(arg1));
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_is_40a66842732708e7 = function(arg0, arg1) {
const ret = Object.is(getObject(arg0), getObject(arg1));
return ret;
};
imports.wbg.__wbg_new_0b9bfdd97583284e = function() {
const ret = new Object();
return addHeapObject(ret);
};
imports.wbg.__wbg_resolve_99fe17964f31ffc0 = function(arg0) {
const ret = Promise.resolve(getObject(arg0));
return addHeapObject(ret);
};
imports.wbg.__wbg_then_11f7a54d67b4bfad = function(arg0, arg1) {
const ret = getObject(arg0).then(getObject(arg1));
return addHeapObject(ret);
};
imports.wbg.__wbg_then_cedad20fbbd9418a = function(arg0, arg1, arg2) {
const ret = getObject(arg0).then(getObject(arg1), getObject(arg2));
return addHeapObject(ret);
};
imports.wbg.__wbg_globalThis_7f206bda628d5286 = function() { return handleError(function () {
const ret = globalThis.globalThis;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_self_6d479506f72c6a71 = function() { return handleError(function () {
const ret = self.self;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_window_f2557cc78490aceb = function() { return handleError(function () {
const ret = window.window;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_global_ba75c50d1cf384f4 = function() { return handleError(function () {
const ret = global.global;
return addHeapObject(ret);
}, arguments) };
imports.wbg.__wbg_set_bf3f89b92d5a34bf = function() { return handleError(function (arg0, arg1, arg2) {
const ret = Reflect.set(getObject(arg0), getObject(arg1), getObject(arg2));
return ret;
}, arguments) };
imports.wbg.__wbindgen_debug_string = function(arg0, arg1) {
const ret = debugString(getObject(arg1));
const ptr0 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
const len0 = WASM_VECTOR_LEN;
getInt32Memory0()[arg0 / 4 + 1] = len0;
getInt32Memory0()[arg0 / 4 + 0] = ptr0;
};
imports.wbg.__wbindgen_throw = function(arg0, arg1) {
throw new Error(getStringFromWasm0(arg0, arg1));
};
imports.wbg.__wbindgen_closure_wrapper3975 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 302, __wbg_adapter_18);
return addHeapObject(ret);
};
imports.wbg.__wbindgen_closure_wrapper6639 = function(arg0, arg1, arg2) {
const ret = makeMutClosure(arg0, arg1, 329, __wbg_adapter_21);
return addHeapObject(ret);
};
return imports;
}
function initMemory(imports, maybe_memory) {
}
function finalizeInit(instance, module) {
wasm = instance.exports;
init.__wbindgen_wasm_module = module;
cachedInt32Memory0 = new Int32Array();
cachedUint32Memory0 = new Uint32Array();
cachedUint8Memory0 = new Uint8Array();
wasm.__wbindgen_start();
return wasm;
}
function initSync(module) {
const imports = getImports();
initMemory(imports);
if (!(module instanceof WebAssembly.Module)) {
module = new WebAssembly.Module(module);
}
const instance = new WebAssembly.Instance(module, imports);
return finalizeInit(instance, module);
}
async function init(input) {
if (typeof input === 'undefined') {
input = new URL('db-frontend-12bfbd74b2a545ed_bg.wasm', import.meta.url);
}
const imports = getImports();
if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {
input = fetch(input);
}
initMemory(imports);
const { instance, module } = await load(await input, imports);
return finalizeInit(instance, module);
}
export { initSync }
export default init;

Binary file not shown.

35
frontend/dist/index.html vendored Normal file
View File

@@ -0,0 +1,35 @@
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<title>Ze greatest</title>
<link rel="preload" href="/db-frontend-12bfbd74b2a545ed_bg.wasm" as="fetch" type="application/wasm" crossorigin="">
<link rel="modulepreload" href="/db-frontend-12bfbd74b2a545ed.js"></head>
<body>
<script type="module">import init from '/db-frontend-12bfbd74b2a545ed.js';init('/db-frontend-12bfbd74b2a545ed_bg.wasm');</script><script>(function () {
var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
var url = protocol + '//' + window.location.host + '/_trunk/ws';
var poll_interval = 5000;
var reload_upon_connect = () => {
window.setTimeout(
() => {
// when we successfully reconnect, we'll force a
// reload (since we presumably lost connection to
// trunk due to it being killed, so it will have
// rebuilt on restart)
var ws = new WebSocket(url);
ws.onopen = () => window.location.reload();
ws.onclose = reload_upon_connect;
},
poll_interval);
};
var ws = new WebSocket(url);
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.reload) {
window.location.reload();
}
};
ws.onclose = reload_upon_connect;
})()
</script></body></html>

251
frontend/src/fetching.rs Normal file
View File

@@ -0,0 +1,251 @@
use common::{CommonAdmin, CommonDriver};
use std::{
error::Error,
fmt::{self, Debug, Display, Formatter},
};
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
use yew::props;
use yew::{html, Component, Context, Html, Properties};
//Trait to handle Future yew HTMLS
pub trait UseAble {
//Return HTML if didn't fail return error if not
fn use_it(self) -> Result<Html, String>;
}
impl UseAble for CommonDriver {
fn use_it(self) -> Result<Html, String> {
let name = self.name;
let address = self.address;
let id = self.id;
let html = html! {
<div>
<h2> { "Driver:" } </h2>
<p> { format!("Name: {}", name) } </p>
<p> { format!("Address: {}", address) } </p>
<p> { format!("ID: {}", id) } </p>
</div>
};
Ok(html)
}
}
impl UseAble for CommonAdmin {
fn use_it(self) -> Result<Html, String> {
let name = self.name;
let address = self.address;
let id = self.id;
let html = html! {
<div>
<h2> { "Admin:" } </h2>
<p> { format!("Name: {}", name) } </p>
<p> { format!("Address: {}", address) } </p>
<p> { format!("ID: {}", id) } </p>
</div>
};
Ok(html)
}
}
//Wwasm bingdengen code
const DRIVER_URL: &str = "http://db.sewelam.tech/api/driver/50";
const ADMIN_URL: &str = "http://db.sewelam.tech/api/admin/69422";
const TICKET_URL: &str = "http://db.sewelam.tech/api/ticket/32";
const FUNNY_TXT_URL: &str = "https://whatthecommit.com/index.txt";
const INCORRECT_URL: &str = "http://libkyy.cf";
//Generic Msg for our states
pub enum Msg<T> {
SetDataFetchState(FetchState<T>),
GetData,
GetError,
}
pub struct TextRequestComponent {
text_request: FetchState<String>,
}
//This trait is for all yew components
impl Component for TextRequestComponent {
type Message = Msg<String>;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
text_request: FetchState::NotFetching, //Default state is not fetching anything
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::SetDataFetchState(fetch_state) => {
self.text_request = fetch_state;
true
}
Msg::GetData => {
ctx.link().send_future(async {
match fetch_url_text(TICKET_URL).await {
Ok(text_request) => {
Msg::SetDataFetchState(FetchState::Success(text_request))
}
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
Msg::GetError => {
ctx.link().send_future(async {
match fetch_url_text(ADMIN_URL).await {
Ok(text_request) => {
Msg::SetDataFetchState(FetchState::Success(text_request))
}
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
match &self.text_request {
FetchState::NotFetching => html! {
<>
<button onclick={ctx.link().callback(|_| Msg::GetData)}>
{ "Get Example Ticket" }
</button>
<button onclick={ctx.link().callback(|_| Msg::GetError)}>
{ "Get Example Admin " }
</button>
</>
},
FetchState::Fetching => html! { "Fetching" },
FetchState::Success(data) => {
html! { <> {data}</> }
}
FetchState::Failed(err) => html! { err },
}
}
}
//Generate Struct and implement component for driver using CommonDriver
pub struct DriverComponent {
driver: FetchState<String>,
}
#[derive(Default, Properties, PartialEq)]
pub struct ApiParams {
pub entered_id: i32,
}
impl ApiParams {
pub fn new_api_thingy_with_id(id: i32) -> Self {
props! { ApiParams {
entered_id: id
}}
}
}
//implement the component for Driver using a string
impl Component for DriverComponent {
type Message = Msg<String>;
type Properties = ApiParams;
fn create(_ctx: &Context<Self>) -> Self {
Self {
driver: FetchState::NotFetching,
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::SetDataFetchState(fetch_state) => {
self.driver = fetch_state;
true
}
Msg::GetData => {
ctx.link().send_future(async {
match fetch_url_text(DRIVER_URL).await {
Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
Msg::GetError => {
ctx.link().send_future(async {
match fetch_url_text(INCORRECT_URL).await {
Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
match &self.driver {
FetchState::NotFetching => html! {
<>
<label for="id"> {"ID:"} </label>
<input type="text" id="name" name="name"/>
<br/>
<button onclick={ctx.link().callback(|_| Msg::GetData)}>
{ "Get driver" }
</button>
</>
},
FetchState::Fetching => html! { "Fetching" },
FetchState::Success(data) => html! { <> {data} <br/>
<button onclick={ctx.link().callback(|_| Msg::GetData)}>
{ "Get new driver (assuming input works :D)" }
</button>
</> },
FetchState::Failed(err) => html! { err },
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FetchError {
err: JsValue,
}
impl Display for FetchError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Debug::fmt(&self.err, f)
}
}
impl Error for FetchError {}
impl From<JsValue> for FetchError {
fn from(value: JsValue) -> Self {
Self { err: value }
}
}
//Enum for Fetchstates that takes a generic type --> String/Driver etc.
pub enum FetchState<T> {
NotFetching,
Fetching,
Success(T),
Failed(FetchError),
}
async fn fetch_url_text(url: &'static str) -> Result<String, FetchError> {
let mut opts = RequestInit::new();
opts.method("GET");
opts.mode(RequestMode::Cors); //Cors is required for fetch to work
//initialise request
let request = Request::new_with_str_and_init(url, &opts)?;
let window = gloo::utils::window();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
let resp: Response = resp_value.dyn_into().unwrap();
let text = JsFuture::from(resp.text()?).await?;
Ok(text.as_string().unwrap())
}
//Admin component

View File

@@ -1,60 +1,21 @@
mod fetching;
use yew::prelude::*;
use common::CommonTicket;
use crate::fetching::{DriverComponent, TextRequestComponent};
#[function_component]
fn App() -> Html {
let counter = use_state(|| 0);
let onclick = {
let counter = counter.clone();
move |_| {
let value = *counter + 1;
counter.set(value);
}
};
let stdnts = vec! [
Stdnt {
id: 1,
name: "Hamada".to_string(),
email: "Hamada@Gmail.com".to_string(),
gpa: 3.4
},
Stdnt {
id: 2,
name: "Gamal".to_string(),
email: "Gamal@Gmail.com".to_string(),
gpa: 4.0
},
Stdnt {
id: 3,
name: "Joe".to_string(),
email: "joe@proton.mail".to_string(),
gpa: 3.8
}
];
let stdnts_comp = stdnts.iter().map(|stdnt| html! {
<>
<p key={stdnt.id}>{format!("Name: {}", stdnt.name)} </p>
<p key={stdnt.id}>{format!("Email: {}", stdnt.email)} </p>
<p key={stdnt.id}>{format!("GPA: {}",stdnt.gpa)} </p>
<br/>
</>
}).collect::<Html>();
let entered_id = 50;
html! {
<div>
<button {onclick}>{ "+1" }</button>
<p>{ *counter }</p>
<h2> { "Students:" } </h2>
<p> { stdnts_comp } </p>
<h1> {"API response examples"} </h1>
<h2> {"Drivers"} </h2>
<DriverComponent {entered_id}/>
<h2> {"Admins and Tickets" } </h2>
<TextRequestComponent/>
</div>
}
}
struct Stdnt {
id: usize,
name: String,
gpa: f32,
email: String,
}
fn main() {
yew::Renderer::<App>::new().render();

View File

@@ -0,0 +1,85 @@
// impl Component for Driver {
// type Message = Msg<CommonDriver>;
// type Properties = ();
// fn create(_ctx: &Context<Self>) -> Self {
// Self {
// driver: FetchState::NotFetching, //Default state is not fetching anything
// }
// }
//
// fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
// match msg {
// Msg::SetDataFetchState(fetch_state) => {
// self.driver = fetch_state;
// true
// }
// Msg::GetData => {
// ctx.link().send_future(async {
// match fetch_driver(DRIVER_URL).await {
// Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
// Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
// }
// });
// ctx.link()
// .send_message(Msg::SetDataFetchState(FetchState::Fetching));
// false
// }
// Msg::GetError => {
// ctx.link().send_future(async {
// match fetch_driver(INCORRECT_URL).await {
// Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
// Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
// }
// });
// ctx.link()
// .send_message(Msg::SetDataFetchState(FetchState::Fetching));
// false
// }
// }
// }
//
// fn view(&self, ctx: &Context<Self>) -> Html {
// //render the component into HTML
// match &self.driver {
// FetchState::NotFetching => html! {
// <>
// <button onclick={ctx.link().callback(|_| Msg::GetData)}>
// { "Get driver info" }
// </button>
// <button onclick={ctx.link().callback(|_| Msg::GetError)}>
// { "Get using incorrect URL" }
// </button>
// </>
// },
// FetchState::Fetching => html! { "Fetching" },
// FetchState::Success(data) => match data.clone().use_it() {
// Ok(html) => html,
// Err(err) => html! { err },
// },
// FetchState::Failed(err) => html! { err },
// }
// }
// }
// async fn fetch_driver(url: &'static str) -> Result<CommonDriver, FetchError> {
// let mut opts = RequestInit::new();
// opts.method("GET");
// //Available request modes: Cors, NoCors, SameOrigin
// opts.mode(RequestMode::NoCors); //NoCors because cors simply doesn't work here
//
// let request = Request::new_with_str_and_init(url, &opts)?;
// //api header for json
// request.headers().set("Accept", "application/json")?;
//
// let window = web_sys::window().unwrap();
// let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
// assert!(resp_value.is_instance_of::<Response>());
// let resp: Response = resp_value.dyn_into().unwrap();
//
// //parsing Json response
// let fetched_json = JsFuture::from(resp.json()?).await?;
// log!(fetched_json.clone());
// let fetched_json: JsValue = fetched_json.into();
// //parsing into CommonDriver struct
// let fetched_json: CommonDriver = fetched_json.into_serde().unwrap();
// Ok(fetched_json)
// }

103
src/api.rs Normal file
View File

@@ -0,0 +1,103 @@
use actix_web::{
get,
http::header::ContentType,
web::{self, Json},
HttpResponse, Responder,
};
use backend::{
admin_data::get_admin, driver_data::get_driver, establish_connection, ticket_data::get_ticket,
vehicle_data::get_vehicle,
};
// use common::{CommonAdmin, CommonDriver, CommonTicket};
#[get("api/ticket/{id}")]
async fn api_ticket(id: web::Path<i32>) -> impl Responder {
let fetched_ticket_data = get_ticket(&mut establish_connection(), *id);
//return struct values as string
HttpResponse::Ok()
.content_type(ContentType::plaintext())
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("content-type", "text/plain"))
.insert_header(("content-encoded", "gzip"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.body(format!(
"Ticket ID: {}, Ticket Price: {}, Ticket Status: {}",
fetched_ticket_data.id, fetched_ticket_data.category, fetched_ticket_data.description
))
}
// Getting admin data or smth idk
#[get("api/admin/{id}")]
async fn api_admin(id: web::Path<i32>) -> impl Responder {
let fetched_admin_data = get_admin(&mut establish_connection(), *id);
//return struct values as string
HttpResponse::Ok()
.content_type(ContentType::plaintext())
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("content-type", "text/plain"))
.insert_header(("content-encoded", "gzip"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.body(format!(
"Admin ID: {}, Admin Name: {}, Admin Address: {}",
fetched_admin_data.id, fetched_admin_data.name, fetched_admin_data.address
))
}
#[get("api/driver/{id}")]
async fn api_driver(id: web::Path<i32>) -> impl Responder {
let fetched_driver_data = get_driver(&mut establish_connection(), *id);
HttpResponse::Ok()
.content_type(ContentType::plaintext())
//headers for plain text
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("content-type", "text/plain"))
.insert_header(("content-encoded", "gzip"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.body(format!(
"Driver ID: {}, Driver Name: {}, Driver Address: {}",
fetched_driver_data.id, fetched_driver_data.name, fetched_driver_data.address
))
}
#[get("api/test")]
async fn api_test() -> impl Responder {
HttpResponse::Ok()
.content_type(ContentType::plaintext())
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("Access-Control-Allow-Methods", "GET"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.insert_header(("content-type", "text/plain"))
.insert_header(("content-encoded", "gzip"))
.body("Alles gut")
}
#[get("api/vehicle/{id}")]
async fn api_vehicle(id: web::Path<String>) -> impl Responder {
let id = id.into_inner();
let fetched_vehicle_data = get_vehicle(&mut establish_connection(), String::from(id));
HttpResponse::Ok()
.content_type(ContentType::plaintext())
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("content-type", "text/plain"))
.insert_header(("content-encoded", "gzip"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.body(format!(
"Vehicle ID: {}, Vehicle Category: {}",
fetched_vehicle_data.plate_num, fetched_vehicle_data.category
))
}

View File

@@ -1,32 +1,26 @@
use actix_web::{
get,
web::{self, Json},
App, HttpServer,
};
use backend::{establish_connection, ticket_data::get_ticket};
use common::CommonTicket;
// //Admin Services
// #[get("/api/admin/{id}")]
// async fn admin(id: web::Path<i32>) -> Json<CommonAdmin> {
// Json(get_admin(&mut establish_connection(), *id))
// }
// #[get("/api/admins{amount}")]
// async fn admins(amount: web::Path<i64>) -> Json<Vec<CommonAdmin>> {
// Json(get_admins(&mut establish_connection(), *amount))
// }
//Ticket Table Services
#[get("api/ticket/{id}")]
async fn ticket(id: web::Path<i32>) -> Json<CommonTicket> {
let fetched_ticket = get_ticket(&mut establish_connection(), *id);
Json(fetched_ticket)
}
pub mod api;
pub mod shadowrealmapi;
use crate::api::*;
use crate::shadowrealmapi::*;
pub(crate) use actix_web::{App, HttpServer};
//Main function where all the api calls are
//attached as services to backend
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(ticket))
.bind(("127.0.0.1", 8081))?
HttpServer::new(|| {
App::new()
.service(api_ticket)
.service(api_admin)
.service(api_driver)
.service(api_json_ticket)
.service(api_json_admin)
.service(api_json_driver)
.service(api_test)
.service(api_json_driver_tickets)
.service(api_json_ticket_new)
})
.bind(("0.0.0.0", 48590))?
.run()
.await
}

79
src/shadowrealmapi.rs Normal file
View File

@@ -0,0 +1,79 @@
use actix_web::{
get,
http::header::ContentType,
post,
web::{self, Json},
HttpResponse, Responder,
};
use backend::{
admin_data::get_admin,
driver_data::get_driver,
establish_connection,
models::NewTicket,
ticket_data::{create_ticket, get_ticket, get_tickets},
};
use common::{CommonAdmin, CommonDriver, CommonTicket};
// Json goodies? NAHH
// Ticket Table Services
#[get("api/json/ticket/{id}")]
async fn api_json_ticket(id: web::Path<i32>) -> impl Responder {
let fetched_ticket_data = get_ticket(&mut establish_connection(), *id);
HttpResponse::Ok()
.content_type(ContentType::json())
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("content-encoded", "gzip"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.json(fetched_ticket_data)
}
#[post("api/json/ticket/new")]
async fn api_json_ticket_new(ticket: web::Json<CommonTicket>) -> impl Responder {
let input = ticket.into_inner();
let input_result = NewTicket {
id: input.id,
description: &input.description,
category: &input.category,
};
create_ticket(&mut establish_connection(), input_result);
HttpResponse::Ok()
.content_type(ContentType::plaintext())
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("Access-Control-Allow-Methods", "GET"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.insert_header(("content-type", "text/plain"))
.insert_header(("content-encoded", "gzip"))
.body("Alles gut")
}
// Getting admin data or smth idk
#[get("api/json/admin/{id}")]
async fn api_json_admin(id: web::Path<i32>) -> Json<CommonAdmin> {
let fetched_admin_data = get_admin(&mut establish_connection(), *id);
Json(fetched_admin_data)
}
#[get("api/json/driver/{id}")]
async fn api_json_driver(id: web::Path<i32>) -> Json<CommonDriver> {
let fetched_driver_data = get_driver(&mut establish_connection(), *id);
Json(fetched_driver_data)
}
#[get("api/json/tickets/{driver}")]
async fn api_json_driver_tickets(id: web::Path<i32>) -> impl Responder {
let fetched_tickets = get_tickets(&mut establish_connection(), *id);
HttpResponse::Ok()
.content_type(ContentType::json())
.insert_header(("Access-Control-Allow-Origin", "*"))
.insert_header(("content-encoded", "gzip"))
.insert_header((
"Access-Control-Allow-Headers",
"Content-Type, Content-Length, User-Agent, X-Requested-With, Range, DNT ",
))
.json(fetched_tickets)
}