aboutsummaryrefslogtreecommitdiff
path: root/src-tauri/src/main.rs
blob: b555123088bde5d693f8aaf5efb3ad7252aa1f25 (plain) (blame)
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV6};
use std::sync::Mutex;
use std::time::{Duration, SystemTime};

use tauri::State;

use chrono::{DateTime, Local};
use reqwest::{Client, Response};
use reqwest::{StatusCode, Url};
use serde::{Deserialize, Serialize};

#[derive(Debug)]
struct Session {
    client: Client,
    instance: Option<Instance>,
}

#[derive(Clone, Debug)]
struct Instance {
    url: Url,
    password: String,
}

#[derive(Debug, Serialize)]
struct WanCredentials {
    username: String,
    password: String,
    status_text: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct WanCredentialFile {
    username: String,
    password: String,
}

#[derive(Debug, Serialize)]
struct ConnectionStatus {
    session: String,
    ipv4: String,
    ipv6: String,
}

#[derive(Debug, Default, Deserialize)]
struct ConnectionFile {
    v4: Option<Ipv4Connection>,
    v6: Option<Ipv6Connection>,
}

impl ConnectionFile {
    fn session_summary(&self) -> String {
        if self.v4.is_some() && self.v6.is_some() {
            String::from("Einwahlstatus: ✅ Dual Stack")
        } else if self.v6.is_some() {
            String::from(
                r#"Einwahlstatus: ✅ IPv6 | ggf. DS-Lite-Status unter "DHCPv6" überprüfen"#,
            )
        } else if self.v4.is_some() {
            String::from(
                r#"Einwahlstatus: ⚠ IPv4 | Eigene Server nicht von außen erreichbar, kleine Teile des modernen Internets nicht erreichbar. Internetanbieter um Freischaltung von IPv6 (bevorzugt "Dual Stack" bzw. mit öffentlicher IPv4-Adresse <i>und</i> IPv6, aber nicht zwingend nötig) bitten."#,
            )
        } else {
            String::from("Einwahlstatus: ❌ Keine Einwahl | Router und Modem neu starten. Bei weiterem Bestehen Diagnoseprotokolle konsultieren oder Internetanbieter kontaktieren.")
        }
    }

    fn ipv4_summary(&self) -> String {
        if let Some(v4) = &self.v4 {
            format!("IPv4: 🟢 Verbunden | Öffentliche Adresse: {}/32 | Primärer DNS-Server (nicht verwendet): {} | Sekundärer DNS-Server (nicht verwendet): {}",v4.addr,v4.dns1,v4.dns2)
        } else if self.v6.is_some() {
            String::from(
                r#"IPv4: 🟡 Nicht verfügbar (ggf. DS-Lite-Status unter "DHCPv6" überprüfen)"#,
            )
        } else {
            String::from("IPv4: 🔴 Nicht verbunden")
        }
    }

    fn ipv6_summary(&self) -> String {
        if let Some(v6) = &self.v6 {
            format!(
                "IPv6: 🟢 Verbunden | Verbindungslokale Adresse: {}/128 | Standardgateway: {}",
                v6.laddr, v6.raddr
            )
        } else if self.v4.is_some() {
            String::from("IPv6: 🟡 Nicht verfügbar | Bitte freischalten lassen (s. oben)")
        } else {
            String::from("IPv6: 🔴 Nicht verbunden")
        }
    }
}

#[derive(Debug, Deserialize)]
struct Ipv4Connection {
    addr: Ipv4Addr,
    dns1: Ipv4Addr,
    dns2: Ipv4Addr,
}

#[derive(Debug, Deserialize)]
struct Ipv6Connection {
    laddr: Ipv6Addr,
    raddr: Ipv6Addr,
}

#[derive(Debug, Serialize)]
struct Dhcpv6Status {
    timestamp: String,
    srvaddr: String,
    srvid: String,
    t1: String,
    t2: String,
    prefix: String,
    wanaddr: String,
    preflft: String,
    validlft: String,
    dns1: String,
    dns2: String,
    aftr: String,
}

impl Dhcpv6Status {
    fn no_lease() -> Self {
        Self::with_all(String::from(
            "✖ Keine Lease vorhanden (erster Systemstart oder Stromausfall?)",
        ))
    }

    fn with_all(message: String) -> Self {
        Self {
            timestamp: message.clone(),
            srvaddr: message.clone(),
            srvid: message.clone(),
            t1: message.clone(),
            t2: message.clone(),
            prefix: message.clone(),
            wanaddr: message.clone(),
            preflft: message.clone(),
            validlft: message.clone(),
            dns1: message.clone(),
            dns2: message.clone(),
            aftr: message,
        }
    }
}

impl From<Dhcpv6Lease> for Dhcpv6Status {
    fn from(lease: Dhcpv6Lease) -> Self {
        let validity = if lease.is_valid() { "✅" } else { "❌" };

        Self {
            timestamp: format!(
                "{} {}",
                validity,
                DateTime::<Local>::from(lease.timestamp).format("%d.%m.%Y %H:%M:%S UTC%Z")
            ),
            srvaddr: if lease.server
                == SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0))
            {
                String::from("ff02::1:2 (Alle DHCPv6-Server, da der Server keine spezifische Adresse angegeben hat)")
            } else {
                format!("{}", lease.server)
            },
            srvid: hex::encode(lease.server_id),
            t1: if lease.t1 == 0 {
                String::from("Sofort")
            } else if lease.t1 == u32::MAX {
                String::from("Nie")
            } else {
                let remaining_secs = std::cmp::max(
                    (Duration::from_secs(lease.t1.into())
                        - lease.timestamp.elapsed().unwrap_or(Duration::ZERO))
                    .as_secs(),
                    0,
                );
                format!(
                    "Alle {} Sekunden ({} Sekunden verbleibend)",
                    lease.t1, remaining_secs
                )
            },
            t2: if lease.t2 == 0 {
                String::from("Sofort")
            } else if lease.t2 == u32::MAX {
                String::from("Nie")
            } else {
                let remaining_secs = std::cmp::max(
                    (Duration::from_secs(lease.t2.into())
                        - lease.timestamp.elapsed().unwrap_or(Duration::ZERO))
                    .as_secs(),
                    0,
                );
                format!(
                    "Alle {} Sekunden ({} Sekunden verbleibend)",
                    lease.t2, remaining_secs
                )
            },
            prefix: format!("{}/{}", lease.prefix, lease.len),
            wanaddr: format!("{}1/64", lease.prefix),
            preflft: if lease.preflft == 0 {
                String::from("⚠ Niemals für neue Verbindungen verwenden")
            } else if lease.preflft == u32::MAX {
                String::from("Unendlich")
            } else {
                let remaining_secs = std::cmp::max(
                    (Duration::from_secs(lease.preflft.into())
                        - lease.timestamp.elapsed().unwrap_or(Duration::ZERO))
                    .as_secs(),
                    0,
                );
                format!(
                    "{} Sekunden ({} Sekunden verbleibend)",
                    lease.preflft, remaining_secs
                )
            },
            validlft: if lease.validlft == 0 {
                String::from("⚠ Internetanbieter verlangte manuell sofortigen Verfall")
            } else if lease.validlft == u32::MAX {
                String::from("Unendlich")
            } else {
                let remaining_secs = std::cmp::max(
                    (Duration::from_secs(lease.validlft.into())
                        - lease.timestamp.elapsed().unwrap_or(Duration::ZERO))
                    .as_secs(),
                    0,
                );
                format!(
                    "{} Sekunden ({} Sekunden verbleibend)",
                    lease.validlft, remaining_secs
                )
            },
            dns1: format!("{}", lease.dns1),
            dns2: format!("{}", lease.dns2),
            aftr: match lease.aftr {
                Some(aftr) => format!("🟢 Aktiviert | Tunnel-Endpunkt (AFTR): {}", aftr),
                None => String::from("⚪ Deaktiviert"),
            },
        }
    }
}

#[derive(Debug, Deserialize)]
struct Dhcpv6Lease {
    timestamp: std::time::SystemTime,
    server: SocketAddr,
    server_id: Vec<u8>,
    t1: u32,
    t2: u32,
    prefix: Ipv6Addr,
    len: u8,
    preflft: u32,
    validlft: u32,
    dns1: Ipv6Addr,
    dns2: Ipv6Addr,
    aftr: Option<String>,
}

#[derive(Debug, Serialize)]
struct Duid {
    duid: String,
    status_text: String,
}

impl Dhcpv6Lease {
    fn is_valid(&self) -> bool {
        let expiry = self.timestamp + Duration::from_secs(self.validlft.into());
        SystemTime::now() < expiry
    }
}

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
async fn connect(
    url: &str,
    password: String,
    state: State<'_, Mutex<Session>>,
) -> Result<String, ()> {
    let instance = Instance {
        url: match url.parse() {
            Ok(url) => url,
            Err(e) => return Ok(format!("Ungültige URL: {}", e)),
        },
        password: password,
    };

    let response = state
        .lock()
        .unwrap()
        .client
        .get(instance.url.join("/proc/top").unwrap())
        .basic_auth("rustkrazy", Some(&instance.password))
        .send();

    Ok(match response.await {
        Ok(response) => handle_connect_response(response, instance, state),
        Err(e) => format!("Verbindungsaufbau fehlgeschlagen: {}", e),
    })
}

fn handle_connect_response(
    response: Response,
    instance: Instance,
    state: State<Mutex<Session>>,
) -> String {
    let status = response.status();
    if status.is_success() {
        state.lock().unwrap().instance = Some(instance);
        format!("Verbindungsaufbau erfolgreich")
    } else if status == StatusCode::UNAUTHORIZED {
        format!("Ungültiges Passwort")
    } else if status.is_client_error() {
        format!("Clientseitiger Fehler: {}", status)
    } else if status.is_server_error() {
        format!("Serverseitiger Fehler: {}", status)
    } else {
        format!("Unerwarteter Statuscode: {}", status)
    }
}

#[tauri::command]
fn disconnect(state: State<Mutex<Session>>) {
    state.lock().unwrap().instance = None;
}

#[tauri::command]
async fn load_wan_credentials(state: State<'_, Mutex<Session>>) -> Result<WanCredentials, ()> {
    let (client, instance) = {
        let state = state.lock().unwrap();
        (state.client.clone(), state.instance.clone())
    };
    let instance = match instance {
        Some(instance) => instance,
        None => {
            return Ok(WanCredentials {
                username: String::new(),
                password: String::new(),
                status_text: String::from(
                    "Keine Instanz ausgewählt, bitte melden Sie sich neu an!",
                ),
            })
        }
    };

    let response = client
        .get(instance.url.join("/data/read").unwrap())
        .query(&[("path", "/data/pppoe.conf")])
        .basic_auth("rustkrazy", Some(&instance.password))
        .send();

    Ok(match response.await {
        Ok(response) => handle_load_wan_credentials_response(response).await,
        Err(e) => WanCredentials {
            username: String::new(),
            password: String::new(),
            status_text: format!("Abruf der aktuellen Zugangsdaten fehlgeschlagen: {}", e),
        },
    })
}

async fn handle_load_wan_credentials_response(response: Response) -> WanCredentials {
    let status = response.status();
    if status.is_success() {
        match response.json::<WanCredentialFile>().await {
            Ok(credentials) => WanCredentials {
                username: credentials.username,
                password: credentials.password,
                status_text: String::new(),
            },
            Err(e) => WanCredentials {
                username: String::new(),
                password: String::new(),
                status_text: format!(
                    "Fehlerhafte Konfigurationsdatei, bitte Zugangsdatenänderung vornehmen. Fehler: {}", e
                ),
            },
        }
    } else if status == StatusCode::UNAUTHORIZED {
        WanCredentials {
            username: String::new(),
            password: String::new(),
            status_text: String::from(
                "Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!",
            ),
        }
    } else if status == StatusCode::NOT_FOUND {
        WanCredentials {
            username: String::new(),
            password: String::new(),
            status_text: String::from("Keine Zugangsdaten eingestellt"),
        }
    } else if status.is_client_error() {
        WanCredentials {
            username: String::new(),
            password: String::new(),
            status_text: format!("Clientseitiger Fehler: {}", status),
        }
    } else if status.is_server_error() {
        WanCredentials {
            username: String::new(),
            password: String::new(),
            status_text: format!("Serverseitiger Fehler: {}", status),
        }
    } else {
        WanCredentials {
            username: String::new(),
            password: String::new(),
            status_text: format!("Unerwarteter Statuscode: {}", status),
        }
    }
}

#[tauri::command]
async fn change_wan_credentials(
    credentials: WanCredentialFile,
    state: State<'_, Mutex<Session>>,
) -> Result<String, ()> {
    let (client, instance) = {
        let state = state.lock().unwrap();
        (state.client.clone(), state.instance.clone())
    };
    let instance = match instance {
        Some(instance) => instance,
        None => {
            return Ok(String::from(
                "Keine Instanz ausgewählt, bitte melden Sie sich neu an!",
            ))
        }
    };

    let response = client
        .post(instance.url.join("/data/write").unwrap())
        .query(&[("path", "/data/pppoe.conf")])
        .basic_auth("rustkrazy", Some(&instance.password))
        .json(&credentials)
        .send();

    Ok(match response.await {
        Ok(response) => handle_change_wan_credentials_response(response),
        Err(e) => format!("Änderung fehlgeschlagen: {}", e),
    })
}

fn handle_change_wan_credentials_response(response: Response) -> String {
    let status = response.status();
    if status.is_success() {
        String::from("Änderung erfolgreich")
    } else if status == StatusCode::UNAUTHORIZED {
        String::from("Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!")
    } else if status.is_client_error() {
        format!("Clientseitiger Fehler: {}", status)
    } else if status.is_server_error() {
        format!("Serverseitiger Fehler: {}", status)
    } else {
        format!("Unerwarteter Statuscode: {}", status)
    }
}

#[tauri::command]
async fn kill(
    process: String,
    signal: String,
    state: State<'_, Mutex<Session>>,
) -> Result<String, ()> {
    let (client, instance) = {
        let state = state.lock().unwrap();
        (state.client.clone(), state.instance.clone())
    };
    let instance = match instance {
        Some(instance) => instance,
        None => {
            return Ok(String::from(
                "Keine Instanz ausgewählt, bitte melden Sie sich neu an!",
            ))
        }
    };

    let response = client
        .post(instance.url.join("/proc/kill").unwrap())
        .query(&[("process", process), ("signal", signal)])
        .basic_auth("rustkrazy", Some(&instance.password))
        .send();

    Ok(match response.await {
        Ok(response) => handle_kill_response(response),
        Err(e) => format!("Signalversand an Dienst fehlgeschlagen: {}", e),
    })
}

fn handle_kill_response(response: Response) -> String {
    let status = response.status();
    if status.is_success() {
        String::new()
    } else if status == StatusCode::UNAUTHORIZED {
        String::from("Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!")
    } else if status.is_client_error() {
        format!("Clientseitiger Fehler: {}", status)
    } else if status.is_server_error() {
        format!("Serverseitiger Fehler: {}", status)
    } else {
        format!("Unerwarteter Statuscode: {}", status)
    }
}

#[tauri::command]
async fn connection_status(state: State<'_, Mutex<Session>>) -> Result<ConnectionStatus, ()> {
    let (client, instance) = {
        let state = state.lock().unwrap();
        (state.client.clone(), state.instance.clone())
    };
    let instance = match instance {
        Some(instance) => instance,
        None => {
            return Ok(ConnectionStatus {
                session: String::from("❗ Keine Instanz ausgewählt, bitte melden Sie sich neu an!"),
                ipv4: String::from("❗ Keine Instanz ausgewählt, bitte melden Sie sich neu an!"),
                ipv6: String::from("❗ Keine Instanz ausgewählt, bitte melden Sie sich neu an!"),
            })
        }
    };

    let response = client
        .get(instance.url.join("/data/read").unwrap())
        .query(&[("path", "/tmp/pppoe.ip_config")])
        .basic_auth("rustkrazy", Some(&instance.password))
        .send();

    Ok(match response.await {
        Ok(response) => handle_connection_status_response(response).await,
        Err(e) => ConnectionStatus {
            session: format!("❗ Abfrage fehlgeschlagen: {}", e),
            ipv4: format!("❗ Abfrage fehlgeschlagen: {}", e),
            ipv6: format!("❗ Abfrage fehlgeschlagen: {}", e),
        },
    })
}

async fn handle_connection_status_response(response: Response) -> ConnectionStatus {
    let status = response.status();
    if status.is_success() {
        match response.json::<ConnectionFile>().await {
            Ok(connection) => ConnectionStatus {
                session: connection.session_summary(),
                ipv4: connection.ipv4_summary(),
                ipv6: connection.ipv6_summary(),
            },
            Err(e) => ConnectionStatus {
                session: format!("❗ Fehlerhafte Parameterdatei. Fehler: {}", e),
                ipv4: format!("❗ Fehlerhafte Parameterdatei. Fehler: {}", e),
                ipv6: format!("❗ Fehlerhafte Parameterdatei. Fehler: {}", e),
            },
        }
    } else if status == StatusCode::UNAUTHORIZED {
        ConnectionStatus {
            session: String::from(
                "❗ Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!",
            ),
            ipv4: String::from("❗ Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!"),
            ipv6: String::from("❗ Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!"),
        }
    } else if status == StatusCode::NOT_FOUND {
        let connection = ConnectionFile::default();
        ConnectionStatus {
            session: connection.session_summary(),
            ipv4: connection.ipv4_summary(),
            ipv6: connection.ipv6_summary(),
        }
    } else if status.is_client_error() {
        ConnectionStatus {
            session: format!("❗ Clientseitiger Fehler: {}", status),
            ipv4: format!("❗ Clientseitiger Fehler: {}", status),
            ipv6: format!("❗ Clientseitiger Fehler: {}", status),
        }
    } else if status.is_server_error() {
        ConnectionStatus {
            session: format!("❗ Serverseitiger Fehler: {}", status),
            ipv4: format!("❗ Serverseitiger Fehler: {}", status),
            ipv6: format!("❗ Serverseitiger Fehler: {}", status),
        }
    } else {
        ConnectionStatus {
            session: format!("❗ Unerwarteter Statuscode: {}", status),
            ipv4: format!("❗ Unerwarteter Statuscode: {}", status),
            ipv6: format!("❗ Unerwarteter Statuscode: {}", status),
        }
    }
}

#[tauri::command]
async fn dhcpv6_status(state: State<'_, Mutex<Session>>) -> Result<Dhcpv6Status, ()> {
    let (client, instance) = {
        let state = state.lock().unwrap();
        (state.client.clone(), state.instance.clone())
    };
    let instance = match instance {
        Some(instance) => instance,
        None => {
            return Ok(Dhcpv6Status::with_all(String::from(
                "❗ Keine Instanz ausgewählt, bitte melden Sie sich neu an!",
            )))
        }
    };

    let response = client
        .get(instance.url.join("/data/read").unwrap())
        .query(&[("path", "/data/dhcp6.lease")])
        .basic_auth("rustkrazy", Some(&instance.password))
        .send();

    Ok(match response.await {
        Ok(response) => handle_dhcpv6_status_response(response).await,
        Err(e) => Dhcpv6Status::with_all(format!("❗ Abfrage fehlgeschlagen: {}", e)),
    })
}

async fn handle_dhcpv6_status_response(response: Response) -> Dhcpv6Status {
    let status = response.status();
    if status.is_success() {
        match response.json::<Dhcpv6Lease>().await {
            Ok(lease) => Dhcpv6Status::from(lease),
            Err(e) => Dhcpv6Status::with_all(format!("❗ Fehlerhafte Leasedatei. Fehler: {}", e)),
        }
    } else if status == StatusCode::UNAUTHORIZED {
        Dhcpv6Status::with_all(String::from(
            "❗ Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!",
        ))
    } else if status == StatusCode::NOT_FOUND {
        Dhcpv6Status::no_lease()
    } else if status.is_client_error() {
        Dhcpv6Status::with_all(format!("❗ Clientseitiger Fehler: {}", status))
    } else if status.is_server_error() {
        Dhcpv6Status::with_all(format!("❗ Serverseitiger Fehler: {}", status))
    } else {
        Dhcpv6Status::with_all(format!("❗ Unerwarteter Statuscode: {}", status))
    }
}

#[tauri::command]
async fn load_duid(state: State<'_, Mutex<Session>>) -> Result<Duid, ()> {
    let (client, instance) = {
        let state = state.lock().unwrap();
        (state.client.clone(), state.instance.clone())
    };
    let instance = match instance {
        Some(instance) => instance,
        None => {
            return Ok(Duid {
                duid: String::new(),
                status_text: String::from(
                    "Keine Instanz ausgewählt, bitte melden Sie sich neu an!",
                ),
            })
        }
    };

    let response = client
        .get(instance.url.join("/data/read").unwrap())
        .query(&[("path", "/data/dhcp6.duid")])
        .basic_auth("rustkrazy", Some(&instance.password))
        .send();

    Ok(match response.await {
        Ok(response) => handle_load_duid_response(response).await,
        Err(e) => Duid {
            duid: String::new(),
            status_text: format!("Abruf des aktuellen Client-DUID fehlgeschlagen: {}", e),
        },
    })
}

async fn handle_load_duid_response(response: Response) -> Duid {
    let status = response.status();
    if status.is_success() {
        let bytes = match response.bytes().await {
            Ok(bytes) => bytes,
            Err(e) => {
                return Duid {
                    duid: String::new(),
                    status_text: format!(
                    "Keine Rohdaten vom Server erhalten, bitte Neustart durchführen. Fehler: {}",
                    e
                ),
                }
            }
        };

        Duid {
            duid: hex::encode(bytes),
            status_text: String::new(),
        }
    } else if status == StatusCode::UNAUTHORIZED {
        Duid {
            duid: String::new(),
            status_text: String::from(
                "Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!",
            ),
        }
    } else if status == StatusCode::NOT_FOUND {
        Duid{
    duid:String::new(),
    status_text:String::from("Kein Client-DUID gespeichert (erster Systemstart oder Stromausfall?), wird bei Bedarf zufällig generiert und gespeichert"),
    }
    } else if status.is_client_error() {
        Duid {
            duid: String::new(),
            status_text: format!("Clientseitiger Fehler: {}", status),
        }
    } else if status.is_server_error() {
        Duid {
            duid: String::new(),
            status_text: format!("Serverseitiger Fehler: {}", status),
        }
    } else {
        Duid {
            duid: String::new(),
            status_text: format!("Unerwarteter Statuscode: {}", status),
        }
    }
}

#[tauri::command]
async fn change_duid(duid: String, state: State<'_, Mutex<Session>>) -> Result<String, ()> {
    let (client, instance) = {
        let state = state.lock().unwrap();
        (state.client.clone(), state.instance.clone())
    };
    let instance = match instance {
        Some(instance) => instance,
        None => {
            return Ok(String::from(
                "Keine Instanz ausgewählt, bitte melden Sie sich neu an!",
            ))
        }
    };

    let bytes = match hex::decode(&duid) {
        Ok(bytes) => bytes,
        Err(e) => {
            return Ok(format!(
                "Eingabe ist keine gültige Hexadezimalsequenz: {}",
                e
            ))
        }
    };

    let response = client
        .post(instance.url.join("/data/write").unwrap())
        .query(&[("path", "/data/dhcp6.duid")])
        .basic_auth("rustkrazy", Some(&instance.password))
        .body(bytes)
        .send();

    Ok(match response.await {
        Ok(response) => handle_change_duid_response(response),
        Err(e) => format!("Änderung fehlgeschlagen: {}", e),
    })
}

fn handle_change_duid_response(response: Response) -> String {
    let status = response.status();
    if status.is_success() {
        String::from("Änderung erfolgreich")
    } else if status == StatusCode::UNAUTHORIZED {
        String::from("Ungültiges Verwaltungspasswort, bitte melden Sie sich neu an!")
    } else if status.is_client_error() {
        format!("Clientseitiger Fehler: {}", status)
    } else if status.is_server_error() {
        format!("Serverseitiger Fehler: {}", status)
    } else {
        format!("Unerwarteter Statuscode: {}", status)
    }
}

fn main() {
    tauri::Builder::default()
        .manage(Mutex::new(Session {
            client: Client::builder()
                .danger_accept_invalid_certs(true)
                .build()
                .expect("error creating http client"),
            instance: None,
        }))
        .invoke_handler(tauri::generate_handler![
            connect,
            disconnect,
            load_wan_credentials,
            change_wan_credentials,
            kill,
            connection_status,
            dhcpv6_status,
            load_duid,
            change_duid
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}