quarkdrive-webdav 1.3.9

A WebDAV client for quarkdrive
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
use std::future::Future;
use std::io;
use std::net::ToSocketAddrs;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use anyhow::Result;
use dav_server::{body::Body, DavConfig, DavHandler};
use headers::{authorization::Basic, Authorization, HeaderMapExt};
use hyper::service::Service;
use hyper::{Method, Request, Response};
use hyper_util::{
    rt::{TokioExecutor, TokioIo},
    server::conn::auto,
};
use tokio::net::TcpListener;
use tracing::{debug, error, info};

use crate::vfs::QuarkDriveFileSystem;

pub struct WebDavServer {
    pub host: String,
    pub port: u16,
    pub auth_user: Option<String>,
    pub auth_password: Option<String>,
    pub tls_config: Option<(PathBuf, PathBuf)>,
    pub handler: DavHandler,
    pub fs: QuarkDriveFileSystem,
    pub strip_prefix: Option<String>,
}

impl WebDavServer {
    pub async fn serve(self) -> Result<()> {
        let addr = (self.host, self.port)
            .to_socket_addrs()?
            .next()
            .ok_or_else(|| io::Error::from(io::ErrorKind::AddrNotAvailable))?;

        let make_svc = MakeSvc {
            auth_user: self.auth_user.clone(),
            auth_password: self.auth_password.clone(),
            handler: self.handler.clone(),
            fs: self.fs.clone(),
            strip_prefix: self.strip_prefix.clone(),
        };

        let listener = TcpListener::bind(&addr).await?;
        info!("listening on http://{}", listener.local_addr()?);

        loop {
            let (tcp, _) = listener.accept().await?;
            let io = TokioIo::new(tcp);
            let make_svc = make_svc.clone();

            tokio::spawn(async move {
                let service = match make_svc.call(()).await {
                    Ok(service) => service,
                    Err(_) => return,
                };

                if let Err(e) = auto::Builder::new(TokioExecutor::new())
                    .serve_connection(io, service)
                    .await
                {
                    error!("HTTP serve error: {}", e);
                }
            });
        }

        // 循环会持续运行,实际不会到达这里
        Ok(())
    }
}

#[derive(Clone)]
pub struct QuarkDriveWebDav {
    auth_user: Option<String>,
    auth_password: Option<String>,
    handler: DavHandler,
    fs: QuarkDriveFileSystem,
    strip_prefix: Option<String>,
}

impl QuarkDriveWebDav {
    fn is_browser_request(req: &Request<hyper::body::Incoming>) -> bool {
        if req.method() != Method::GET {
            return false;
        }
        if let Some(accept) = req.headers().get("accept") {
            if let Ok(accept_str) = accept.to_str() {
                return accept_str.contains("text/html");
            }
        }
        false
    }

    fn compute_fs_path(&self, req_path: &str) -> PathBuf {
        let path = if let Some(ref prefix) = self.strip_prefix {
            let prefix = prefix.trim_end_matches('/');
            req_path
                .strip_prefix(prefix)
                .unwrap_or(req_path)
        } else {
            req_path
        };

        let path = path.trim_start_matches('/');
        let path = path.trim_end_matches('/');
        let path = percent_decode(path);

        if self.fs.root == Path::new("/") {
            if path.is_empty() {
                PathBuf::from("/")
            } else {
                PathBuf::from("/").join(&path)
            }
        } else if path.is_empty() {
            self.fs.root.clone()
        } else {
            self.fs.root.join(&path)
        }
    }

    async fn handle_browser_request(
        &self,
        req_path: &str,
    ) -> Option<Response<Body>> {
        let fs_path = self.compute_fs_path(req_path);
        debug!(req_path = %req_path, fs_path = %fs_path.display(), "browser: checking path");

        let files = self.fs.dir_cache.get_or_insert(&fs_path.to_string_lossy()).await?;
        debug!(req_path = %req_path, count = files.len(), "browser: directory listing");

        let html = render_directory_html(req_path, &files);
        Some(
            Response::builder()
                .status(200)
                .header("Content-Type", "text/html; charset=utf-8")
                .body(Body::from(html))
                .unwrap(),
        )
    }
}

fn percent_decode(s: &str) -> String {
    percent_encoding::percent_decode_str(s)
        .decode_utf8_lossy()
        .into_owned()
}

fn html_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}

fn format_size(size: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = 1024 * KB;
    const GB: u64 = 1024 * MB;
    const TB: u64 = 1024 * GB;

    if size >= TB {
        format!("{:.1} TB", size as f64 / TB as f64)
    } else if size >= GB {
        format!("{:.1} GB", size as f64 / GB as f64)
    } else if size >= MB {
        format!("{:.1} MB", size as f64 / MB as f64)
    } else if size >= KB {
        format!("{:.1} KB", size as f64 / KB as f64)
    } else {
        format!("{} B", size)
    }
}

fn format_timestamp(ts_millis: u64) -> String {
    let secs = (ts_millis / 1000) as i64;
    let dt = chrono::DateTime::from_timestamp(secs, 0);
    match dt {
        Some(dt) => {
            use chrono::FixedOffset;
            let china = FixedOffset::east_opt(8 * 3600).unwrap();
            dt.with_timezone(&china).format("%Y-%m-%d %H:%M").to_string()
        }
        None => "-".to_string(),
    }
}

fn render_directory_html(req_path: &str, files: &[crate::drive::QuarkFile]) -> String {
    let display_path = percent_decode(req_path);
    let display_path = if display_path.is_empty() || display_path == "/" {
        "/".to_string()
    } else {
        display_path
    };

    let req_path_normalized = if req_path.ends_with('/') || req_path.is_empty() {
        req_path.to_string()
    } else {
        format!("{}/", req_path)
    };

    // Build breadcrumbs
    let mut breadcrumbs = String::from(r#"<a href="/">根目录</a>"#);
    if display_path != "/" {
        let parts: Vec<&str> = display_path.trim_matches('/').split('/').collect();
        let mut href = String::new();
        for (i, part) in parts.iter().enumerate() {
            href.push('/');
            href.push_str(&percent_encode_path(part));
            if i == parts.len() - 1 {
                breadcrumbs.push_str(&format!(
                    r#" / <span class="current">{}</span>"#,
                    html_escape(part)
                ));
            } else {
                breadcrumbs.push_str(&format!(
                    r#" / <a href="{}">{}</a>"#,
                    html_escape(&format!("{}/", href)),
                    html_escape(part)
                ));
            }
        }
    }

    // Separate dirs and files, sort by name
    let mut dirs: Vec<&crate::drive::QuarkFile> = files.iter().filter(|f| f.dir).collect();
    let mut regular_files: Vec<&crate::drive::QuarkFile> = files.iter().filter(|f| f.file).collect();
    dirs.sort_by(|a, b| a.file_name.to_lowercase().cmp(&b.file_name.to_lowercase()));
    regular_files.sort_by(|a, b| a.file_name.to_lowercase().cmp(&b.file_name.to_lowercase()));

    let mut rows = String::new();

    // Parent directory link
    if display_path != "/" {
        rows.push_str(r#"<tr class="parent"><td class="icon">📁</td><td class="name"><a href="../">..</a></td><td class="size">-</td><td class="date">-</td></tr>"#);
    }

    for dir in &dirs {
        let name = html_escape(&dir.file_name);
        let href = format!("{}{}/", req_path_normalized, percent_encode_path(&dir.file_name));
        let date = format_timestamp(dir.updated_at);
        rows.push_str(&format!(
            r#"<tr class="dir"><td class="icon">📁</td><td class="name"><a href="{}">{}</a></td><td class="size">-</td><td class="date">{}</td></tr>"#,
            html_escape(&href), name, date
        ));
    }

    for file in &regular_files {
        let name = html_escape(&file.file_name);
        let href = format!("{}{}", req_path_normalized, percent_encode_path(&file.file_name));
        let size = format_size(file.size);
        let date = format_timestamp(file.updated_at);
        let icon = file_icon(&file.file_name);
        rows.push_str(&format!(
            r#"<tr class="file"><td class="icon">{}</td><td class="name"><a href="{}">{}</a></td><td class="size">{}</td><td class="date">{}</td></tr>"#,
            icon, html_escape(&href), name, size, date
        ));
    }

    let total = dirs.len() + regular_files.len();

    format!(
        r#"<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>QuarkDrive - {title}</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%232563eb'/%3E%3Ctext x='32' y='40' font-family='Arial,Helvetica,sans-serif' font-size='26' font-weight='bold' fill='white' text-anchor='middle'%3EQW%3C/text%3E%3C/svg%3E">
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background: #f5f5f5; color: #333; line-height: 1.6; }}
.container {{ max-width: 960px; margin: 0 auto; padding: 20px; }}
.header {{ background: #fff; border-radius: 8px; padding: 16px 24px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }}
.header h1 {{ font-size: 18px; font-weight: 600; color: #1a1a1a; margin-bottom: 8px; }}
.breadcrumb {{ font-size: 14px; color: #666; }}
.breadcrumb a {{ color: #2563eb; text-decoration: none; }}
.breadcrumb a:hover {{ text-decoration: underline; }}
.breadcrumb .current {{ color: #333; font-weight: 500; }}
.content {{ background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); overflow: hidden; }}
table {{ width: 100%; border-collapse: collapse; }}
thead {{ background: #fafafa; }}
th {{ text-align: left; padding: 12px 16px; font-size: 13px; font-weight: 600; color: #666; border-bottom: 1px solid #eee; }}
td {{ padding: 10px 16px; border-bottom: 1px solid #f0f0f0; font-size: 14px; }}
tr:hover {{ background: #f8fafc; }}
tr.parent:hover {{ background: #f0f7ff; }}
tr.dir:hover {{ background: #f0f7ff; }}
.icon {{ width: 32px; text-align: center; }}
.name {{ word-break: break-all; }}
.name a {{ color: #1a1a1a; text-decoration: none; }}
.name a:hover {{ color: #2563eb; text-decoration: underline; }}
.dir .name a {{ font-weight: 500; }}
.size {{ width: 100px; text-align: right; color: #888; white-space: nowrap; }}
.date {{ width: 160px; color: #888; white-space: nowrap; }}
.footer {{ text-align: center; padding: 16px; font-size: 12px; color: #aaa; }}
.footer a {{ color: #aaa; text-decoration: none; }}
.footer a:hover {{ color: #2563eb; text-decoration: underline; }}
@media (max-width: 640px) {{
  .container {{ padding: 10px; }}
  .date {{ display: none; }}
  th:last-child {{ display: none; }}
  .size {{ width: 80px; }}
}}
</style>
</head>
<body>
<div class="container">
  <div class="header">
    <h1><a href="https://github.com/chenqimiao/quarkdrive-webdav" target="_blank" style="color:inherit;text-decoration:none;">QuarkDrive WebDAV</a></h1>
    <div class="breadcrumb">{breadcrumbs}</div>
  </div>
  <div class="content">
    <table>
      <thead><tr><th class="icon"></th><th>名称</th><th class="size">大小</th><th class="date">修改时间</th></tr></thead>
      <tbody>{rows}</tbody>
    </table>
  </div>
  <div class="footer">{total} 个项目 · <a href="https://github.com/chenqimiao/quarkdrive-webdav" target="_blank">GitHub</a></div>
</div>
</body>
</html>"#,
        title = html_escape(&display_path),
        breadcrumbs = breadcrumbs,
        rows = rows,
        total = total,
    )
}

fn percent_encode_path(s: &str) -> String {
    percent_encoding::utf8_percent_encode(s, percent_encoding::NON_ALPHANUMERIC).to_string()
}

fn file_icon(name: &str) -> &'static str {
    let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
    match ext.as_str() {
        "jpg" | "jpeg" | "png" | "gif" | "bmp" | "webp" | "svg" | "ico" => "🖼️",
        "mp4" | "avi" | "mkv" | "mov" | "wmv" | "flv" | "webm" | "m4v" | "ts" => "🎬",
        "mp3" | "wav" | "flac" | "aac" | "ogg" | "wma" | "m4a" => "🎵",
        "pdf" => "📕",
        "doc" | "docx" => "📝",
        "xls" | "xlsx" => "📊",
        "ppt" | "pptx" => "📎",
        "zip" | "rar" | "7z" | "tar" | "gz" | "bz2" | "xz" => "📦",
        "txt" | "md" | "log" | "csv" => "📄",
        "exe" | "msi" | "dmg" | "app" | "deb" | "rpm" => "⚙️",
        "html" | "css" | "js" | "json" | "xml" | "yaml" | "yml" | "toml" => "💻",
        "rs" | "py" | "java" | "c" | "cpp" | "go" | "rb" | "php" | "sh" => "💻",
        _ => "📄",
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // --- format_size tests ---

    #[test]
    fn test_format_size_bytes() {
        assert_eq!(format_size(0), "0 B");
        assert_eq!(format_size(1), "1 B");
        assert_eq!(format_size(1023), "1023 B");
    }

    #[test]
    fn test_format_size_kb() {
        assert_eq!(format_size(1024), "1.0 KB");
        assert_eq!(format_size(1536), "1.5 KB");
    }

    #[test]
    fn test_format_size_mb() {
        assert_eq!(format_size(1024 * 1024), "1.0 MB");
        assert_eq!(format_size(1024 * 1024 * 5), "5.0 MB");
    }

    #[test]
    fn test_format_size_gb() {
        assert_eq!(format_size(1024 * 1024 * 1024), "1.0 GB");
    }

    #[test]
    fn test_format_size_tb() {
        assert_eq!(format_size(1024u64 * 1024 * 1024 * 1024), "1.0 TB");
        assert_eq!(format_size(1024u64 * 1024 * 1024 * 1024 * 3), "3.0 TB");
    }

    // --- format_timestamp tests ---

    #[test]
    fn test_format_timestamp_normal() {
        // 2024-01-01 08:00 CST = 2024-01-01 00:00 UTC = 1704067200000 ms
        let result = format_timestamp(1704067200000);
        assert_eq!(result, "2024-01-01 08:00");
    }

    #[test]
    fn test_format_timestamp_zero() {
        // 0 ms => 1970-01-01 08:00 CST
        let result = format_timestamp(0);
        assert_eq!(result, "1970-01-01 08:00");
    }

    // --- html_escape tests ---

    #[test]
    fn test_html_escape_all_entities() {
        assert_eq!(html_escape("&<>\"'"), "&amp;&lt;&gt;&quot;&#x27;");
    }

    #[test]
    fn test_html_escape_empty() {
        assert_eq!(html_escape(""), "");
    }

    #[test]
    fn test_html_escape_no_special() {
        assert_eq!(html_escape("hello world"), "hello world");
    }

    #[test]
    fn test_html_escape_mixed() {
        assert_eq!(
            html_escape("a & b < c > d"),
            "a &amp; b &lt; c &gt; d"
        );
    }

    // --- file_icon tests ---

    #[test]
    fn test_file_icon_image() {
        assert_eq!(file_icon("photo.jpg"), "🖼️");
        assert_eq!(file_icon("photo.PNG"), "🖼️");
        assert_eq!(file_icon("photo.Jpeg"), "🖼️");
    }

    #[test]
    fn test_file_icon_video() {
        assert_eq!(file_icon("movie.mp4"), "🎬");
        assert_eq!(file_icon("movie.MKV"), "🎬");
    }

    #[test]
    fn test_file_icon_audio() {
        assert_eq!(file_icon("song.mp3"), "🎵");
        assert_eq!(file_icon("song.FLAC"), "🎵");
    }

    #[test]
    fn test_file_icon_document() {
        assert_eq!(file_icon("report.pdf"), "📕");
        assert_eq!(file_icon("report.doc"), "📝");
        assert_eq!(file_icon("data.xlsx"), "📊");
        assert_eq!(file_icon("slides.pptx"), "📎");
    }

    #[test]
    fn test_file_icon_archive() {
        assert_eq!(file_icon("archive.zip"), "📦");
        assert_eq!(file_icon("archive.tar"), "📦");
    }

    #[test]
    fn test_file_icon_code() {
        assert_eq!(file_icon("main.rs"), "💻");
        assert_eq!(file_icon("app.js"), "💻");
        assert_eq!(file_icon("config.yaml"), "💻");
    }

    #[test]
    fn test_file_icon_unknown() {
        assert_eq!(file_icon("file.xyz"), "📄");
        assert_eq!(file_icon("noext"), "📄");
    }

    // --- percent_encode_path / percent_decode tests ---

    #[test]
    fn test_percent_encode_path_chinese() {
        let encoded = percent_encode_path("你好");
        assert!(!encoded.contains(""));
        let decoded = percent_decode(&encoded);
        assert_eq!(decoded, "你好");
    }

    #[test]
    fn test_percent_encode_path_special_chars() {
        let encoded = percent_encode_path("file name (1).txt");
        assert!(!encoded.contains(' '));
        let decoded = percent_decode(&encoded);
        assert_eq!(decoded, "file name (1).txt");
    }

    #[test]
    fn test_percent_decode_empty() {
        assert_eq!(percent_decode(""), "");
    }

    #[test]
    fn test_percent_encode_roundtrip() {
        let original = "测试文件 & 文档.pdf";
        let encoded = percent_encode_path(original);
        let decoded = percent_decode(&encoded);
        assert_eq!(decoded, original);
    }

    // --- render_directory_html tests ---

    #[test]
    fn test_render_directory_html_root_empty() {
        let files: Vec<crate::drive::QuarkFile> = vec![];
        let html = render_directory_html("/", &files);
        assert!(html.contains("QuarkDrive"));
        assert!(html.contains("0 个项目"));
        // root should not have parent link
        assert!(!html.contains("href=\"../\""));
    }

    #[test]
    fn test_render_directory_html_with_files() {
        let files = vec![
            crate::drive::QuarkFile {
                fid: "1".to_string(),
                file_name: "子目录".to_string(),
                pdir_fid: "0".to_string(),
                size: 0,
                format_type: "".to_string(),
                status: 1,
                created_at: 1704067200000,
                updated_at: 1704067200000,
                dir: true,
                file: false,
                download_url: None,
                content_hash: None,
                parent_path: None,
            },
            crate::drive::QuarkFile {
                fid: "2".to_string(),
                file_name: "test.txt".to_string(),
                pdir_fid: "0".to_string(),
                size: 1024,
                format_type: "text/plain".to_string(),
                status: 1,
                created_at: 1704067200000,
                updated_at: 1704067200000,
                dir: false,
                file: true,
                download_url: None,
                content_hash: None,
                parent_path: None,
            },
        ];
        let html = render_directory_html("/docs", &files);
        assert!(html.contains("2 个项目"));
        // subdirectory should have parent link
        assert!(html.contains("href=\"../\""));
        // should contain the directory and file names
        assert!(html.contains("子目录"));
        assert!(html.contains("test.txt"));
        // file size should be formatted
        assert!(html.contains("1.0 KB"));
    }

    #[test]
    fn test_render_directory_html_sorting() {
        let files = vec![
            crate::drive::QuarkFile {
                fid: "1".to_string(),
                file_name: "b.txt".to_string(),
                pdir_fid: "0".to_string(),
                size: 100,
                format_type: "text/plain".to_string(),
                status: 1,
                created_at: 0,
                updated_at: 0,
                dir: false,
                file: true,
                download_url: None,
                content_hash: None,
                parent_path: None,
            },
            crate::drive::QuarkFile {
                fid: "2".to_string(),
                file_name: "a.txt".to_string(),
                pdir_fid: "0".to_string(),
                size: 200,
                format_type: "text/plain".to_string(),
                status: 1,
                created_at: 0,
                updated_at: 0,
                dir: false,
                file: true,
                download_url: None,
                content_hash: None,
                parent_path: None,
            },
        ];
        let html = render_directory_html("/", &files);
        let pos_a = html.find("a.txt").unwrap();
        let pos_b = html.find("b.txt").unwrap();
        // a.txt should come before b.txt (sorted alphabetically)
        assert!(pos_a < pos_b);
    }

    // --- compute_fs_path tests ---

    fn create_test_webdav(root: &str, strip_prefix: Option<&str>) -> QuarkDriveWebDav {
        use std::sync::Arc;
        use dashmap::DashMap;
        let cookie = Arc::new(DashMap::new());
        cookie.insert("test".to_string(), "value".to_string());
        let config = crate::drive::DriveConfig {
            api_base_url: "https://drive.quark.cn".to_string(),
            cookie,
        };
        let drive = crate::drive::QuarkDrive::new(config).unwrap();
        let fs = crate::vfs::QuarkDriveFileSystem::new(drive, root.to_string(), 100, 60).unwrap();
        let handler = DavHandler::builder()
            .filesystem(Box::new(fs.clone()))
            .build_handler();
        QuarkDriveWebDav {
            auth_user: None,
            auth_password: None,
            handler,
            fs,
            strip_prefix: strip_prefix.map(|s| s.to_string()),
        }
    }

    #[test]
    fn test_compute_fs_path_root() {
        let webdav = create_test_webdav("/", None);
        assert_eq!(webdav.compute_fs_path("/"), std::path::PathBuf::from("/"));
    }

    #[test]
    fn test_compute_fs_path_simple_file() {
        let webdav = create_test_webdav("/", None);
        assert_eq!(webdav.compute_fs_path("/test.txt"), std::path::PathBuf::from("/test.txt"));
    }

    #[test]
    fn test_compute_fs_path_nested() {
        let webdav = create_test_webdav("/", None);
        assert_eq!(
            webdav.compute_fs_path("/docs/report.pdf"),
            std::path::PathBuf::from("/docs/report.pdf")
        );
    }

    #[test]
    fn test_compute_fs_path_with_strip_prefix() {
        let webdav = create_test_webdav("/", Some("/dav"));
        // "/dav/test.txt" after stripping "/dav" → "/test.txt"
        assert_eq!(
            webdav.compute_fs_path("/dav/test.txt"),
            std::path::PathBuf::from("/test.txt")
        );
    }

    #[test]
    fn test_compute_fs_path_strip_prefix_root() {
        let webdav = create_test_webdav("/", Some("/dav"));
        assert_eq!(webdav.compute_fs_path("/dav/"), std::path::PathBuf::from("/"));
        assert_eq!(webdav.compute_fs_path("/dav"), std::path::PathBuf::from("/"));
    }

    #[test]
    fn test_compute_fs_path_with_custom_root() {
        let webdav = create_test_webdav("/myroot", None);
        assert_eq!(webdav.compute_fs_path("/"), std::path::PathBuf::from("/myroot"));
        assert_eq!(
            webdav.compute_fs_path("/test.txt"),
            std::path::PathBuf::from("/myroot/test.txt")
        );
    }

    #[test]
    fn test_compute_fs_path_trailing_slash() {
        let webdav = create_test_webdav("/", None);
        assert_eq!(
            webdav.compute_fs_path("/docs/"),
            std::path::PathBuf::from("/docs")
        );
    }

    #[test]
    fn test_compute_fs_path_percent_encoded() {
        let webdav = create_test_webdav("/", None);
        // "%E6%B5%8B%E8%AF%95" is percent-encoded "测试"
        let path = webdav.compute_fs_path("/%E6%B5%8B%E8%AF%95.txt");
        assert_eq!(path, std::path::PathBuf::from("/测试.txt"));
    }

    #[test]
    fn test_compute_fs_path_custom_root_and_prefix() {
        let webdav = create_test_webdav("/myroot", Some("/dav"));
        assert_eq!(
            webdav.compute_fs_path("/dav/file.txt"),
            std::path::PathBuf::from("/myroot/file.txt")
        );
    }

    // --- Digest header tests ---

    #[test]
    fn test_digest_hex_md5_to_base64() {
        use base64::Engine;
        // API normally returns hex MD5; we convert to base64 per RFC 3230
        let hex_md5 = "d41d8cd98f00b204e9800998ecf8427e"; // MD5 of empty string
        let md5_bytes = hex::decode(hex_md5).unwrap();
        let b64 = base64::engine::general_purpose::STANDARD.encode(&md5_bytes);
        assert_eq!(b64, "1B2M2Y8AsgTpgAmY7PhCfg==");
        let header_value = format!("md5={}", b64);
        assert!(hyper::header::HeaderValue::from_str(&header_value).is_ok());
    }

    #[test]
    fn test_digest_hex_md5_hello_world() {
        use base64::Engine;
        let hex_md5 = "5eb63bbbe01eeed093cb22bb8f5acdc3"; // MD5 of "hello world"
        let md5_bytes = hex::decode(hex_md5).unwrap();
        let b64 = base64::engine::general_purpose::STANDARD.encode(&md5_bytes);
        // Verify round-trip
        let decoded = base64::engine::general_purpose::STANDARD.decode(&b64).unwrap();
        assert_eq!(hex::encode(&decoded), hex_md5);
    }

    #[test]
    fn test_digest_fallback_already_base64() {
        // If hex::decode fails, the value is used as-is (base64 fallback)
        let already_b64 = "XrY7u+Ae7tCTyyK7j1rNww==";
        assert!(hex::decode(already_b64).is_err()); // not valid hex
        let header_value = format!("md5={}", already_b64);
        assert!(hyper::header::HeaderValue::from_str(&header_value).is_ok());
    }

    #[test]
    fn test_digest_header_format() {
        use base64::Engine;
        let hex_md5 = "d3bdad63084cd4dc4e7120ec48a11082"; // real file MD5
        let md5_bytes = hex::decode(hex_md5).unwrap();
        let b64 = base64::engine::general_purpose::STANDARD.encode(&md5_bytes);
        let header_value = format!("md5={}", b64);
        assert!(hyper::header::HeaderValue::from_str(&header_value).is_ok());
        assert!(header_value.starts_with("md5="));
    }

    // --- Want-Digest header parsing ---

    #[test]
    fn test_want_digest_contains_md5() {
        let val = "md5";
        assert!(val.to_lowercase().contains("md5"));
    }

    #[test]
    fn test_want_digest_contains_md5_mixed_case() {
        let val = "MD5;q=1, SHA-256;q=0.5";
        assert!(val.to_lowercase().contains("md5"));
    }

    #[test]
    fn test_want_digest_no_md5() {
        let val = "sha-256, sha-512";
        assert!(!val.to_lowercase().contains("md5"));
    }

    #[test]
    fn test_want_digest_logic() {
        // Simulate the Want-Digest decision logic from webdav.rs
        fn should_add_digest(want_digest: &Option<String>) -> bool {
            match want_digest {
                Some(val) => val.to_lowercase().contains("md5"),
                None => true, // No header = add by default
            }
        }

        assert!(should_add_digest(&None));
        assert!(should_add_digest(&Some("md5".to_string())));
        assert!(should_add_digest(&Some("MD5;q=1, SHA-256".to_string())));
        assert!(!should_add_digest(&Some("sha-256".to_string())));
        assert!(!should_add_digest(&Some("sha-512".to_string())));
    }
}

impl Service<Request<hyper::body::Incoming>> for QuarkDriveWebDav {
    type Response = Response<Body>;
    type Error = hyper::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn call(&self, req: Request<hyper::body::Incoming>) -> Self::Future {
        let should_auth = self.auth_user.is_some() && self.auth_password.is_some();
        let dav_server = self.handler.clone();
        let auth_user = self.auth_user.clone();
        let auth_pwd = self.auth_password.clone();
        let is_browser = Self::is_browser_request(&req);
        let req_path = req.uri().path().to_string();
        let req_method = req.method().clone();
        let want_digest = req
            .headers()
            .get("want-digest")
            .and_then(|v| v.to_str().ok().map(|s| s.to_string()));
        let browser_handler = self.clone();

        Box::pin(async move {
            let mut resp = if should_auth {
                let auth_user_val = auth_user.clone().unwrap();
                let auth_pwd_val = auth_pwd.clone().unwrap();

                let user = match req.headers().typed_get::<Authorization<Basic>>() {
                    Some(Authorization(basic))
                    if basic.username() == auth_user_val && basic.password() == auth_pwd_val =>
                        {
                            basic.username().to_string()
                        }
                    _ => {
                        return Ok(Response::builder()
                            .status(401)
                            .header("WWW-Authenticate", "Basic realm=\"quarkdrive-webdav\"")
                            .body(Body::from("Authentication required"))
                            .unwrap());
                    }
                };

                if is_browser {
                    if let Some(resp) = browser_handler.handle_browser_request(&req_path).await {
                        return Ok(resp);
                    }
                }

                let config = DavConfig::new().principal(user);
                dav_server.handle_with(config, req).await
            } else {
                if is_browser {
                    if let Some(resp) = browser_handler.handle_browser_request(&req_path).await {
                        return Ok(resp);
                    }
                }

                dav_server.handle(req).await
            };

            // RFC 3230: Add Digest header for GET 200 responses
            if req_method == Method::GET && resp.status() == hyper::StatusCode::OK {
                let should_add = match &want_digest {
                    Some(val) => val.to_lowercase().contains("md5"),
                    None => true,
                };
                if should_add {
                    let fs_path = browser_handler.compute_fs_path(&req_path);
                    if let Some(md5_val) =
                        browser_handler.fs.get_file_md5_for_path(&fs_path).await
                    {
                        // API normally returns hex MD5; convert to base64 per RFC 3230
                        let b64 = if let Ok(md5_bytes) = hex::decode(&md5_val) {
                            use base64::Engine;
                            base64::engine::general_purpose::STANDARD.encode(&md5_bytes)
                        } else {
                            // Already base64 or other format, use as-is
                            md5_val
                        };
                        if let Ok(val) =
                            hyper::header::HeaderValue::from_str(&format!("md5={}", b64))
                        {
                            resp.headers_mut().insert("digest", val);
                        }
                    }
                }
            }

            Ok(resp)
        })
    }
}

#[derive(Clone)]
pub struct MakeSvc {
    pub auth_user: Option<String>,
    pub auth_password: Option<String>,
    pub handler: DavHandler,
    pub fs: QuarkDriveFileSystem,
    pub strip_prefix: Option<String>,
}

impl Service<()> for MakeSvc {
    type Response = QuarkDriveWebDav;
    type Error = hyper::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn call(&self, _: ()) -> Self::Future {
        let auth_user = self.auth_user.clone();
        let auth_password = self.auth_password.clone();
        let handler = self.handler.clone();
        let fs = self.fs.clone();
        let strip_prefix = self.strip_prefix.clone();

        Box::pin(async move {
            Ok(QuarkDriveWebDav {
                auth_user,
                auth_password,
                handler,
                fs,
                strip_prefix,
            })
        })
    }
}