Viewer, thumbnails worker, full sweeper
Browse files at this commitfea1d3f52699f6942190ccfda7cbfb6ce4c78fd6Parent: 6e0d0ad- feat
- viewer, thumbnails worker, full sweeper
- byte responses keep their own CSP and allow same-origin framing, PDFs unsandboxed
25 changed files +1447 -60
- Cargo.lock +165 -0
- Cargo.toml +1 -0
- crates/in-core/Cargo.toml +1 -0
- crates/in-core/src/lib.rs +1 -0
- crates/in-core/src/store/files.rs +70 -6
- crates/in-core/src/store/members.rs +49 -1
- crates/in-core/src/thumbs.rs +119 -0
- crates/in-web/assets/viewer.js +31 -0
- crates/in-web/build.rs +3 -1
- crates/in-web/src/api/upload.rs +7 -0
- crates/in-web/src/assets.rs +15 -0
- crates/in-web/src/boot.rs +2 -0
- crates/in-web/src/i18n/drive.rs +16 -4
- crates/in-web/src/main.rs +1 -0
- crates/in-web/src/pages/drive.rs +3 -3
- crates/in-web/src/pages/mod.rs +1 -0
- crates/in-web/src/pages/thumbs.rs +90 -0
- crates/in-web/src/pages/view.rs +305 -24
- crates/in-web/src/security.rs +19 -2
- crates/in-web/src/serve_bytes.rs +20 -7
- crates/in-web/src/sweeper.rs +234 -10
- crates/in-web/src/thumbs_worker.rs +180 -0
- crates/in-web/src/views/drive.rs +27 -1
- crates/in-web/src/views/mod.rs +2 -1
- style/_components.scss +85 -0
Cargo.lockmodified+165 -0
| @@ -2,6 +2,12 @@ | |||
| 2 | # It is not intended for manual editing. | 2 | # It is not intended for manual editing. |
| 3 | version = 4 | 3 | version = 4 |
| 4 | 4 | ||
| 5 | +[[package]] | ||
| 6 | +name = "adler2" | ||
| 7 | +version = "2.0.1" | ||
| 8 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 9 | +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | ||
| 10 | + | ||
| 5 | [[package]] | 11 | [[package]] |
| 6 | name = "aead" | 12 | name = "aead" |
| 7 | version = "0.5.2" | 13 | version = "0.5.2" |
| @@ -448,6 +454,12 @@ version = "1.5.0" | |||
| 448 | source = "registry+https://github.com/rust-lang/crates.io-index" | 454 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 449 | checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" | 455 | checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" |
| 450 | 456 | ||
| 457 | +[[package]] | ||
| 458 | +name = "byteorder-lite" | ||
| 459 | +version = "0.1.0" | ||
| 460 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 461 | +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" | ||
| 462 | + | ||
| 451 | [[package]] | 463 | [[package]] |
| 452 | name = "bytes" | 464 | name = "bytes" |
| 453 | version = "1.12.1" | 465 | version = "1.12.1" |
| @@ -617,6 +629,12 @@ version = "0.1.3" | |||
| 617 | source = "registry+https://github.com/rust-lang/crates.io-index" | 629 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 618 | checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" | 630 | checksum = "b9e769b5c8c8283982a987c6e948e540254f1058d5a74b8794914d4ef5fc2a24" |
| 619 | 631 | ||
| 632 | +[[package]] | ||
| 633 | +name = "color_quant" | ||
| 634 | +version = "1.1.0" | ||
| 635 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 636 | +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" | ||
| 637 | + | ||
| 620 | [[package]] | 638 | [[package]] |
| 621 | name = "colorchoice" | 639 | name = "colorchoice" |
| 622 | version = "1.0.5" | 640 | version = "1.0.5" |
| @@ -1152,6 +1170,15 @@ version = "2.5.0" | |||
| 1152 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1170 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1153 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | 1171 | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" |
| 1154 | 1172 | ||
| 1173 | +[[package]] | ||
| 1174 | +name = "fdeflate" | ||
| 1175 | +version = "0.3.7" | ||
| 1176 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1177 | +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" | ||
| 1178 | +dependencies = [ | ||
| 1179 | + "simd-adler32", | ||
| 1180 | +] | ||
| 1181 | + | ||
| 1155 | [[package]] | 1182 | [[package]] |
| 1156 | name = "ff" | 1183 | name = "ff" |
| 1157 | version = "0.13.1" | 1184 | version = "0.13.1" |
| @@ -1174,6 +1201,17 @@ version = "0.1.15" | |||
| 1174 | source = "registry+https://github.com/rust-lang/crates.io-index" | 1201 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 1175 | checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" | 1202 | checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" |
| 1176 | 1203 | ||
| 1204 | +[[package]] | ||
| 1205 | +name = "flate2" | ||
| 1206 | +version = "1.1.10" | ||
| 1207 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1208 | +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" | ||
| 1209 | +dependencies = [ | ||
| 1210 | + "crc32fast", | ||
| 1211 | + "miniz_oxide 0.9.1", | ||
| 1212 | + "zlib-rs", | ||
| 1213 | +] | ||
| 1214 | + | ||
| 1177 | [[package]] | 1215 | [[package]] |
| 1178 | name = "fnv" | 1216 | name = "fnv" |
| 1179 | version = "1.0.7" | 1217 | version = "1.0.7" |
| @@ -1370,6 +1408,16 @@ dependencies = [ | |||
| 1370 | "polyval", | 1408 | "polyval", |
| 1371 | ] | 1409 | ] |
| 1372 | 1410 | ||
| 1411 | +[[package]] | ||
| 1412 | +name = "gif" | ||
| 1413 | +version = "0.14.2" | ||
| 1414 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1415 | +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" | ||
| 1416 | +dependencies = [ | ||
| 1417 | + "color_quant", | ||
| 1418 | + "weezl", | ||
| 1419 | +] | ||
| 1420 | + | ||
| 1373 | [[package]] | 1421 | [[package]] |
| 1374 | name = "glob" | 1422 | name = "glob" |
| 1375 | version = "0.3.4" | 1423 | version = "0.3.4" |
| @@ -1856,6 +1904,34 @@ dependencies = [ | |||
| 1856 | "icu_properties", | 1904 | "icu_properties", |
| 1857 | ] | 1905 | ] |
| 1858 | 1906 | ||
| 1907 | +[[package]] | ||
| 1908 | +name = "image" | ||
| 1909 | +version = "0.25.10" | ||
| 1910 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1911 | +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" | ||
| 1912 | +dependencies = [ | ||
| 1913 | + "bytemuck", | ||
| 1914 | + "byteorder-lite", | ||
| 1915 | + "color_quant", | ||
| 1916 | + "gif", | ||
| 1917 | + "image-webp", | ||
| 1918 | + "moxcms", | ||
| 1919 | + "num-traits", | ||
| 1920 | + "png", | ||
| 1921 | + "zune-core", | ||
| 1922 | + "zune-jpeg", | ||
| 1923 | +] | ||
| 1924 | + | ||
| 1925 | +[[package]] | ||
| 1926 | +name = "image-webp" | ||
| 1927 | +version = "0.2.4" | ||
| 1928 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1929 | +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" | ||
| 1930 | +dependencies = [ | ||
| 1931 | + "byteorder-lite", | ||
| 1932 | + "quick-error", | ||
| 1933 | +] | ||
| 1934 | + | ||
| 1859 | [[package]] | 1935 | [[package]] |
| 1860 | name = "in-core" | 1936 | name = "in-core" |
| 1861 | version = "0.1.0" | 1937 | version = "0.1.0" |
| @@ -1868,6 +1944,7 @@ dependencies = [ | |||
| 1868 | "futures-util", | 1944 | "futures-util", |
| 1869 | "hex", | 1945 | "hex", |
| 1870 | "hmac 0.13.0", | 1946 | "hmac 0.13.0", |
| 1947 | + "image", | ||
| 1871 | "ipnet", | 1948 | "ipnet", |
| 1872 | "object_store", | 1949 | "object_store", |
| 1873 | "rand 0.10.3", | 1950 | "rand 0.10.3", |
| @@ -2374,6 +2451,26 @@ version = "0.2.1" | |||
| 2374 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2451 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2375 | checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" | 2452 | checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" |
| 2376 | 2453 | ||
| 2454 | +[[package]] | ||
| 2455 | +name = "miniz_oxide" | ||
| 2456 | +version = "0.8.9" | ||
| 2457 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2458 | +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" | ||
| 2459 | +dependencies = [ | ||
| 2460 | + "adler2", | ||
| 2461 | + "simd-adler32", | ||
| 2462 | +] | ||
| 2463 | + | ||
| 2464 | +[[package]] | ||
| 2465 | +name = "miniz_oxide" | ||
| 2466 | +version = "0.9.1" | ||
| 2467 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2468 | +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" | ||
| 2469 | +dependencies = [ | ||
| 2470 | + "adler2", | ||
| 2471 | + "simd-adler32", | ||
| 2472 | +] | ||
| 2473 | + | ||
| 2377 | [[package]] | 2474 | [[package]] |
| 2378 | name = "mio" | 2475 | name = "mio" |
| 2379 | version = "1.2.4" | 2476 | version = "1.2.4" |
| @@ -2385,6 +2482,16 @@ dependencies = [ | |||
| 2385 | "windows-sys 0.61.2", | 2482 | "windows-sys 0.61.2", |
| 2386 | ] | 2483 | ] |
| 2387 | 2484 | ||
| 2485 | +[[package]] | ||
| 2486 | +name = "moxcms" | ||
| 2487 | +version = "0.8.1" | ||
| 2488 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2489 | +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" | ||
| 2490 | +dependencies = [ | ||
| 2491 | + "num-traits", | ||
| 2492 | + "pxfm", | ||
| 2493 | +] | ||
| 2494 | + | ||
| 2388 | [[package]] | 2495 | [[package]] |
| 2389 | name = "multer" | 2496 | name = "multer" |
| 2390 | version = "3.1.0" | 2497 | version = "3.1.0" |
| @@ -2784,6 +2891,19 @@ version = "0.3.34" | |||
| 2784 | source = "registry+https://github.com/rust-lang/crates.io-index" | 2891 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 2785 | checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" | 2892 | checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" |
| 2786 | 2893 | ||
| 2894 | +[[package]] | ||
| 2895 | +name = "png" | ||
| 2896 | +version = "0.18.1" | ||
| 2897 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 2898 | +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" | ||
| 2899 | +dependencies = [ | ||
| 2900 | + "bitflags", | ||
| 2901 | + "crc32fast", | ||
| 2902 | + "fdeflate", | ||
| 2903 | + "flate2", | ||
| 2904 | + "miniz_oxide 0.8.9", | ||
| 2905 | +] | ||
| 2906 | + | ||
| 2787 | [[package]] | 2907 | [[package]] |
| 2788 | name = "polling" | 2908 | name = "polling" |
| 2789 | version = "3.11.0" | 2909 | version = "3.11.0" |
| @@ -2916,6 +3036,18 @@ dependencies = [ | |||
| 2916 | "syn 2.0.119", | 3036 | "syn 2.0.119", |
| 2917 | ] | 3037 | ] |
| 2918 | 3038 | ||
| 3039 | +[[package]] | ||
| 3040 | +name = "pxfm" | ||
| 3041 | +version = "0.1.30" | ||
| 3042 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3043 | +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" | ||
| 3044 | + | ||
| 3045 | +[[package]] | ||
| 3046 | +name = "quick-error" | ||
| 3047 | +version = "2.0.1" | ||
| 3048 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3049 | +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" | ||
| 3050 | + | ||
| 2919 | [[package]] | 3051 | [[package]] |
| 2920 | name = "quick-xml" | 3052 | name = "quick-xml" |
| 2921 | version = "0.41.0" | 3053 | version = "0.41.0" |
| @@ -3694,6 +3826,12 @@ dependencies = [ | |||
| 3694 | "rand_core 0.6.4", | 3826 | "rand_core 0.6.4", |
| 3695 | ] | 3827 | ] |
| 3696 | 3828 | ||
| 3829 | +[[package]] | ||
| 3830 | +name = "simd-adler32" | ||
| 3831 | +version = "0.3.10" | ||
| 3832 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 3833 | +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" | ||
| 3834 | + | ||
| 3697 | [[package]] | 3835 | [[package]] |
| 3698 | name = "simd_cesu8" | 3836 | name = "simd_cesu8" |
| 3699 | version = "1.2.0" | 3837 | version = "1.2.0" |
| @@ -5201,6 +5339,12 @@ dependencies = [ | |||
| 5201 | "rustls-pki-types", | 5339 | "rustls-pki-types", |
| 5202 | ] | 5340 | ] |
| 5203 | 5341 | ||
| 5342 | +[[package]] | ||
| 5343 | +name = "weezl" | ||
| 5344 | +version = "0.1.12" | ||
| 5345 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5346 | +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" | ||
| 5347 | + | ||
| 5204 | [[package]] | 5348 | [[package]] |
| 5205 | name = "which" | 5349 | name = "which" |
| 5206 | version = "4.4.2" | 5350 | version = "4.4.2" |
| @@ -5549,6 +5693,12 @@ dependencies = [ | |||
| 5549 | "syn 3.0.9", | 5693 | "syn 3.0.9", |
| 5550 | ] | 5694 | ] |
| 5551 | 5695 | ||
| 5696 | +[[package]] | ||
| 5697 | +name = "zlib-rs" | ||
| 5698 | +version = "0.6.8" | ||
| 5699 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5700 | +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" | ||
| 5701 | + | ||
| 5552 | [[package]] | 5702 | [[package]] |
| 5553 | name = "zmij" | 5703 | name = "zmij" |
| 5554 | version = "1.0.23" | 5704 | version = "1.0.23" |
| @@ -5582,3 +5732,18 @@ dependencies = [ | |||
| 5582 | "cc", | 5732 | "cc", |
| 5583 | "pkg-config", | 5733 | "pkg-config", |
| 5584 | ] | 5734 | ] |
| 5735 | + | ||
| 5736 | +[[package]] | ||
| 5737 | +name = "zune-core" | ||
| 5738 | +version = "0.5.3" | ||
| 5739 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5740 | +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" | ||
| 5741 | + | ||
| 5742 | +[[package]] | ||
| 5743 | +name = "zune-jpeg" | ||
| 5744 | +version = "0.5.15" | ||
| 5745 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 5746 | +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" | ||
| 5747 | +dependencies = [ | ||
| 5748 | + "zune-core", | ||
| 5749 | +] | ||
Cargo.tomlmodified+1 -0
| @@ -53,6 +53,7 @@ hmac = "0.13.0" | |||
| 53 | http = "1.5.0" | 53 | http = "1.5.0" |
| 54 | http-body = "1.1.0" | 54 | http-body = "1.1.0" |
| 55 | http-body-util = "0.1.5" | 55 | http-body-util = "0.1.5" |
| 56 | +image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "webp"] } | ||
| 56 | in-core = { path = "crates/in-core" } | 57 | in-core = { path = "crates/in-core" } |
| 57 | ipnet = "2.12.2" | 58 | ipnet = "2.12.2" |
| 58 | jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } | 59 | jsonwebtoken = { version = "11.1.0", default-features = false, features = ["rust_crypto"] } |
crates/in-core/Cargo.tomlmodified+1 -0
| @@ -13,6 +13,7 @@ base64.workspace = true | |||
| 13 | bytes.workspace = true | 13 | bytes.workspace = true |
| 14 | chacha20poly1305.workspace = true | 14 | chacha20poly1305.workspace = true |
| 15 | futures-util.workspace = true | 15 | futures-util.workspace = true |
| 16 | +image.workspace = true | ||
| 16 | hex.workspace = true | 17 | hex.workspace = true |
| 17 | hmac.workspace = true | 18 | hmac.workspace = true |
| 18 | ipnet.workspace = true | 19 | ipnet.workspace = true |
crates/in-core/src/lib.rsmodified+1 -0
| @@ -13,5 +13,6 @@ pub mod secret; | |||
| 13 | pub mod sniff; | 13 | pub mod sniff; |
| 14 | pub mod staging; | 14 | pub mod staging; |
| 15 | pub mod store; | 15 | pub mod store; |
| 16 | +pub mod thumbs; | ||
| 16 | pub mod time; | 17 | pub mod time; |
| 17 | pub mod token; | 18 | pub mod token; |
crates/in-core/src/store/files.rsmodified+70 -6
| @@ -82,9 +82,18 @@ pub fn files_blob_key(id: &str) -> String { | |||
| 82 | format!("files/{}/{id}", &id[..2]) | 82 | format!("files/{}/{id}", &id[..2]) |
| 83 | } | 83 | } |
| 84 | 84 | ||
| 85 | -/// The blob key of a file's thumbnail: `thumbs/<first two id characters>/<id>.webp`. | 85 | +/// The blob key of a file's thumbnail: `thumbs/<id>`. The key is flat, so one purge deletes it by id. |
| 86 | pub fn thumb_blob_key(id: &str) -> String { | 86 | pub fn thumb_blob_key(id: &str) -> String { |
| 87 | - format!("thumbs/{}/{id}.webp", &id[..2]) | 87 | + format!("thumbs/{id}") |
| 88 | +} | ||
| 89 | + | ||
| 90 | +/// The thumbnail state a new file starts in. Only the picture types the thumbnail decoder reads are | ||
| 91 | +/// `pending`; every other type is `none` and never gets a thumbnail. | ||
| 92 | +pub fn thumb_state_for(mime: &str) -> &'static str { | ||
| 93 | + match mime { | ||
| 94 | + "image/png" | "image/jpeg" | "image/webp" | "image/gif" => "pending", | ||
| 95 | + _ => "none", | ||
| 96 | + } | ||
| 88 | } | 97 | } |
| 89 | 98 | ||
| 90 | /// Maps a row selected with [`FILE_COLS`]. | 99 | /// Maps a row selected with [`FILE_COLS`]. |
| @@ -177,8 +186,8 @@ pub(crate) async fn insert_file_in(conn: &Connection, new: NewFile) -> Result<Fi | |||
| 177 | ) | 186 | ) |
| 178 | .await?; | 187 | .await?; |
| 179 | conn.execute( | 188 | conn.execute( |
| 180 | - "INSERT INTO files (id, owner, folder_id, name, mime, size, sha256, blob_key, \ | 189 | + "INSERT INTO files (id, owner, folder_id, name, mime, size, sha256, blob_key, thumb_state, \ |
| 181 | - created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)", | 190 | + created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)", |
| 182 | ( | 191 | ( |
| 183 | new.id.clone(), | 192 | new.id.clone(), |
| 184 | new.owner.clone(), | 193 | new.owner.clone(), |
| @@ -188,6 +197,7 @@ pub(crate) async fn insert_file_in(conn: &Connection, new: NewFile) -> Result<Fi | |||
| 188 | new.size, | 197 | new.size, |
| 189 | new.sha256.clone(), | 198 | new.sha256.clone(), |
| 190 | blob_key, | 199 | blob_key, |
| 200 | + thumb_state_for(&new.mime), | ||
| 191 | now.clone(), | 201 | now.clone(), |
| 192 | ), | 202 | ), |
| 193 | ) | 203 | ) |
| @@ -266,6 +276,58 @@ impl Store { | |||
| 266 | live_file(&conn, owner, id).await | 276 | live_file(&conn, owner, id).await |
| 267 | } | 277 | } |
| 268 | 278 | ||
| 279 | + /// Up to `limit` files whose thumbnail is still to be made, oldest first. | ||
| 280 | + pub async fn pending_thumbs(&self, limit: usize) -> Result<Vec<File>> { | ||
| 281 | + let conn = self.read_conn().await; | ||
| 282 | + fetch_all( | ||
| 283 | + &conn, | ||
| 284 | + &format!( | ||
| 285 | + "SELECT {FILE_COLS} FROM files WHERE thumb_state = 'pending' \ | ||
| 286 | + ORDER BY created_at, id LIMIT ?1" | ||
| 287 | + ), | ||
| 288 | + (limit.max(1) as i64,), | ||
| 289 | + map_file, | ||
| 290 | + ) | ||
| 291 | + .await | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + /// Sets the thumbnail state of a file to `ready` or `failed`. Returns `false` when the file has no row | ||
| 295 | + /// (it was purged while its thumbnail was made), so the caller can remove the bytes it stored. | ||
| 296 | + pub async fn set_thumb_state(&self, id: &str, state: &str) -> Result<bool> { | ||
| 297 | + if state != "ready" && state != "failed" { | ||
| 298 | + return Err(Error::Invalid("bad_thumb_state".into())); | ||
| 299 | + } | ||
| 300 | + let conn = self.inner.conn.lock().await; | ||
| 301 | + let changed = conn | ||
| 302 | + .execute( | ||
| 303 | + "UPDATE files SET thumb_state = ?2 WHERE id = ?1", | ||
| 304 | + (id.to_string(), state.to_string()), | ||
| 305 | + ) | ||
| 306 | + .await | ||
| 307 | + .map_err(db_err)?; | ||
| 308 | + Ok(changed > 0) | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + /// Every blob key that a row names: the bytes of each file, the thumbnail of each file, and the bytes of | ||
| 312 | + /// each object. The sweeper keeps these and removes any other blob that is old enough. | ||
| 313 | + pub async fn referenced_blob_keys(&self) -> Result<Vec<String>> { | ||
| 314 | + let conn = self.read_conn().await; | ||
| 315 | + let mut keys = fetch_all(&conn, "SELECT id, blob_key FROM files", (), |row| { | ||
| 316 | + Ok((col_text(row, 0)?, col_text(row, 1)?)) | ||
| 317 | + }) | ||
| 318 | + .await? | ||
| 319 | + .into_iter() | ||
| 320 | + .flat_map(|(id, blob_key)| [blob_key, thumb_blob_key(&id)]) | ||
| 321 | + .collect::<Vec<_>>(); | ||
| 322 | + keys.extend( | ||
| 323 | + fetch_all(&conn, "SELECT blob_key FROM objects", (), |row| { | ||
| 324 | + col_text(row, 0) | ||
| 325 | + }) | ||
| 326 | + .await?, | ||
| 327 | + ); | ||
| 328 | + Ok(keys) | ||
| 329 | + } | ||
| 330 | + | ||
| 269 | /// Counts one forced download of a file. The caller counts only a download that starts at byte 0. | 331 | /// Counts one forced download of a file. The caller counts only a download that starts at byte 0. |
| 270 | pub async fn record_download(&self, id: &str) -> Result<()> { | 332 | pub async fn record_download(&self, id: &str) -> Result<()> { |
| 271 | let conn = self.inner.conn.lock().await; | 333 | let conn = self.inner.conn.lock().await; |
| @@ -321,9 +383,11 @@ mod tests { | |||
| 321 | use super::*; | 383 | use super::*; |
| 322 | 384 | ||
| 323 | #[test] | 385 | #[test] |
| 324 | - fn blob_keys_follow_the_id_prefix_layout() { | 386 | + fn blob_keys_follow_the_id_layout() { |
| 325 | assert_eq!(files_blob_key("01abcdef"), "files/01/01abcdef"); | 387 | assert_eq!(files_blob_key("01abcdef"), "files/01/01abcdef"); |
| 326 | - assert_eq!(thumb_blob_key("01abcdef"), "thumbs/01/01abcdef.webp"); | 388 | + assert_eq!(thumb_blob_key("01abcdef"), "thumbs/01abcdef"); |
| 389 | + assert_eq!(thumb_state_for("image/png"), "pending"); | ||
| 390 | + assert_eq!(thumb_state_for("application/pdf"), "none"); | ||
| 327 | } | 391 | } |
| 328 | 392 | ||
| 329 | #[test] | 393 | #[test] |
crates/in-core/src/store/members.rsmodified+49 -1
| @@ -6,7 +6,7 @@ | |||
| 6 | use turso::Row; | 6 | use turso::Row; |
| 7 | 7 | ||
| 8 | use crate::error::{Error, Result}; | 8 | use crate::error::{Error, Result}; |
| 9 | -use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt}; | 9 | +use crate::store::{Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish}; |
| 10 | use crate::time::now_stamp; | 10 | use crate::time::now_stamp; |
| 11 | 11 | ||
| 12 | /// Column list for [`map_member`]. Keep the two in step. | 12 | /// Column list for [`map_member`]. Keep the two in step. |
| @@ -74,6 +74,17 @@ pub struct MemberFields { | |||
| 74 | } | 74 | } |
| 75 | 75 | ||
| 76 | /// Maps a row selected with [`MEMBER_COLS`]. | 76 | /// Maps a row selected with [`MEMBER_COLS`]. |
| 77 | +/// A member whose stored `used_bytes` disagreed with the sum of their files. `actual` is the value written. | ||
| 78 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 79 | +pub struct QuotaDrift { | ||
| 80 | + /// The member. | ||
| 81 | + pub sub: String, | ||
| 82 | + /// The value the row held before the check. | ||
| 83 | + pub stored: i64, | ||
| 84 | + /// The sum of the member's file sizes, now the stored value. | ||
| 85 | + pub actual: i64, | ||
| 86 | +} | ||
| 87 | + | ||
| 77 | pub fn map_member(row: &Row) -> Result<Member> { | 88 | pub fn map_member(row: &Row) -> Result<Member> { |
| 78 | Ok(Member { | 89 | Ok(Member { |
| 79 | sub: col_text(row, 0)?, | 90 | sub: col_text(row, 0)?, |
| @@ -250,6 +261,43 @@ impl Store { | |||
| 250 | Ok(()) | 261 | Ok(()) |
| 251 | } | 262 | } |
| 252 | 263 | ||
| 264 | + /// Recomputes every member's `used_bytes` from their files and writes back the ones that differ, in one | ||
| 265 | + /// transaction. Returns each corrected member with the stored and the recomputed value, so the caller | ||
| 266 | + /// can log the drift. Trashed files count, as they do in the quota rule. | ||
| 267 | + pub async fn reconcile_quota(&self) -> Result<Vec<QuotaDrift>> { | ||
| 268 | + let conn = self.inner.conn.lock().await; | ||
| 269 | + let tx = conn.unchecked_transaction().await.map_err(db_err)?; | ||
| 270 | + let outcome: Result<Vec<QuotaDrift>> = async { | ||
| 271 | + let drift = fetch_all( | ||
| 272 | + &tx, | ||
| 273 | + "SELECT m.sub, m.used_bytes, \ | ||
| 274 | + (SELECT COALESCE(SUM(f.size), 0) FROM files f WHERE f.owner = m.sub) \ | ||
| 275 | + FROM members m \ | ||
| 276 | + WHERE m.used_bytes <> (SELECT COALESCE(SUM(f.size), 0) FROM files f WHERE f.owner = m.sub)", | ||
| 277 | + (), | ||
| 278 | + |row| { | ||
| 279 | + Ok(QuotaDrift { | ||
| 280 | + sub: col_text(row, 0)?, | ||
| 281 | + stored: col_int(row, 1)?, | ||
| 282 | + actual: col_int(row, 2)?, | ||
| 283 | + }) | ||
| 284 | + }, | ||
| 285 | + ) | ||
| 286 | + .await?; | ||
| 287 | + for item in &drift { | ||
| 288 | + tx.execute( | ||
| 289 | + "UPDATE members SET used_bytes = ?2 WHERE sub = ?1", | ||
| 290 | + (item.sub.clone(), item.actual), | ||
| 291 | + ) | ||
| 292 | + .await | ||
| 293 | + .map_err(db_err)?; | ||
| 294 | + } | ||
| 295 | + Ok(drift) | ||
| 296 | + } | ||
| 297 | + .await; | ||
| 298 | + finish(tx, outcome).await | ||
| 299 | + } | ||
| 300 | + | ||
| 253 | /// Sets a member's theme. Only `system`, `light` and `dark` are accepted. | 301 | /// Sets a member's theme. Only `system`, `light` and `dark` are accepted. |
| 254 | pub async fn set_theme(&self, sub: &str, theme: &str) -> Result<()> { | 302 | pub async fn set_theme(&self, sub: &str, theme: &str) -> Result<()> { |
| 255 | if !THEMES.contains(&theme) { | 303 | if !THEMES.contains(&theme) { |
crates/in-core/src/thumbs.rsadded+119 -0
| @@ -0,0 +1,119 @@ | |||
| 1 | +//! Thumbnails of pictures: decode a PNG, JPEG, WebP or GIF and write a small lossless WebP no wider or taller | ||
| 2 | +//! than [`THUMB_EDGE`]. It is pure: bytes in, bytes out, no file access and no external program. | ||
| 3 | +//! | ||
| 4 | +//! The decoder runs under hard limits. A picture that claims more than [`MAX_DIMENSION`] pixels on a side, or | ||
| 5 | +//! would need more than [`MAX_ALLOC_BYTES`] to decode, is refused from its header, before any large buffer is | ||
| 6 | +//! allocated. A refused picture is `Invalid("bad_image")`; the thumbnail worker marks such a file `failed`. | ||
| 7 | + | ||
| 8 | +use std::io::Cursor; | ||
| 9 | + | ||
| 10 | +use image::{ImageFormat, ImageReader, Limits}; | ||
| 11 | + | ||
| 12 | +use crate::error::{Error, Result}; | ||
| 13 | + | ||
| 14 | +/// Longest edge of a thumbnail, in pixels. The aspect ratio is kept. | ||
| 15 | +pub const THUMB_EDGE: u32 = 320; | ||
| 16 | + | ||
| 17 | +/// Largest source picture the worker reads, in bytes. Larger files get no thumbnail. | ||
| 18 | +pub const MAX_SOURCE_BYTES: u64 = 64 * 1024 * 1024; | ||
| 19 | + | ||
| 20 | +/// Largest width or height the decoder accepts, in pixels: 10000 by 10000 is 100 megapixels. | ||
| 21 | +pub const MAX_DIMENSION: u32 = 10_000; | ||
| 22 | + | ||
| 23 | +/// Most memory the decoder may allocate for one picture: 256 MiB. | ||
| 24 | +pub const MAX_ALLOC_BYTES: u64 = 256 * 1024 * 1024; | ||
| 25 | + | ||
| 26 | +/// The formats that get thumbnails. Anything else is not decoded. | ||
| 27 | +const FORMATS: [ImageFormat; 4] = [ | ||
| 28 | + ImageFormat::Png, | ||
| 29 | + ImageFormat::Jpeg, | ||
| 30 | + ImageFormat::WebP, | ||
| 31 | + ImageFormat::Gif, | ||
| 32 | +]; | ||
| 33 | + | ||
| 34 | +/// Decodes `source` under the limits and returns a WebP thumbnail of it. | ||
| 35 | +/// | ||
| 36 | +/// The format is found from the leading bytes, never from a file name, and must be one of [`FORMATS`]. Any | ||
| 37 | +/// decoder error, including a limit, is `Invalid("bad_image")`. Nothing here panics on hostile input. | ||
| 38 | +pub fn make_thumbnail(source: &[u8]) -> Result<Vec<u8>> { | ||
| 39 | + let bad = || Error::Invalid("bad_image".into()); | ||
| 40 | + let mut reader = ImageReader::new(Cursor::new(source)) | ||
| 41 | + .with_guessed_format() | ||
| 42 | + .map_err(|_| bad())?; | ||
| 43 | + if !reader.format().is_some_and(|f| FORMATS.contains(&f)) { | ||
| 44 | + return Err(bad()); | ||
| 45 | + } | ||
| 46 | + let mut limits = Limits::default(); | ||
| 47 | + limits.max_image_width = Some(MAX_DIMENSION); | ||
| 48 | + limits.max_image_height = Some(MAX_DIMENSION); | ||
| 49 | + limits.max_alloc = Some(MAX_ALLOC_BYTES); | ||
| 50 | + reader.limits(limits); | ||
| 51 | + let picture = reader.decode().map_err(|_| bad())?; | ||
| 52 | + let thumb = picture.thumbnail(THUMB_EDGE, THUMB_EDGE); | ||
| 53 | + let mut out = Cursor::new(Vec::new()); | ||
| 54 | + thumb | ||
| 55 | + .write_to(&mut out, ImageFormat::WebP) | ||
| 56 | + .map_err(|_| bad())?; | ||
| 57 | + Ok(out.into_inner()) | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +#[cfg(test)] | ||
| 61 | +mod tests { | ||
| 62 | + use super::*; | ||
| 63 | + | ||
| 64 | + /// A 4x2 PNG made by the encoder, the source of the tests below. | ||
| 65 | + fn small_png() -> Vec<u8> { | ||
| 66 | + let img = image::RgbaImage::from_pixel(4, 2, image::Rgba([200, 30, 30, 255])); | ||
| 67 | + let mut out = Cursor::new(Vec::new()); | ||
| 68 | + img.write_to(&mut out, ImageFormat::Png).unwrap(); | ||
| 69 | + out.into_inner() | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + /// CRC-32 (the PNG chunk checksum), bit by bit. Only the tests use it. | ||
| 73 | + fn crc32(bytes: &[u8]) -> u32 { | ||
| 74 | + let mut crc = !0u32; | ||
| 75 | + for &byte in bytes { | ||
| 76 | + crc ^= u32::from(byte); | ||
| 77 | + for _ in 0..8 { | ||
| 78 | + crc = if crc & 1 == 1 { | ||
| 79 | + (crc >> 1) ^ 0xEDB8_8320 | ||
| 80 | + } else { | ||
| 81 | + crc >> 1 | ||
| 82 | + }; | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + !crc | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + #[test] | ||
| 89 | + fn a_small_png_becomes_a_webp_thumbnail() { | ||
| 90 | + let thumb = make_thumbnail(&small_png()).unwrap(); | ||
| 91 | + assert_eq!(&thumb[..4], b"RIFF"); | ||
| 92 | + assert_eq!(&thumb[8..12], b"WEBP"); | ||
| 93 | + assert!(image::load_from_memory(&thumb).is_ok()); | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + /// A PNG whose header claims 100000 by 100000 pixels. Its IHDR checksum is fixed up so that only the | ||
| 97 | + /// dimension limit can refuse it. It must fail cleanly, without a panic or a huge allocation. | ||
| 98 | + #[test] | ||
| 99 | + fn a_decompression_bomb_png_is_refused_without_a_panic() { | ||
| 100 | + let mut png = small_png(); | ||
| 101 | + // The IHDR chunk starts at byte 8: length (4), type (4), then width and height (4 each). | ||
| 102 | + assert_eq!(&png[12..16], b"IHDR"); | ||
| 103 | + png[16..20].copy_from_slice(&100_000u32.to_be_bytes()); | ||
| 104 | + png[20..24].copy_from_slice(&100_000u32.to_be_bytes()); | ||
| 105 | + let crc = crc32(&png[12..29]); | ||
| 106 | + png[29..33].copy_from_slice(&crc.to_be_bytes()); | ||
| 107 | + let result = make_thumbnail(&png); | ||
| 108 | + assert!( | ||
| 109 | + matches!(result, Err(Error::Invalid(ref m)) if m == "bad_image"), | ||
| 110 | + "a bomb must be refused: {result:?}" | ||
| 111 | + ); | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + #[test] | ||
| 115 | + fn non_pictures_are_refused() { | ||
| 116 | + assert!(make_thumbnail(b"plain text, not a picture").is_err()); | ||
| 117 | + assert!(make_thumbnail(b"").is_err()); | ||
| 118 | + } | ||
| 119 | +} | ||
crates/in-web/assets/viewer.jsadded+31 -0
| @@ -0,0 +1,31 @@ | |||
| 1 | +/** | ||
| 2 | + * viewer.js: the keyboard steps of the file viewer. Left goes to the previous file of the folder and right | ||
| 3 | + * to the next one. It follows the same links a mouse would (`a[data-nav]`), so soft navigation handles them. | ||
| 4 | + * It does nothing while a form field has the focus, while a modifier key is held, or on a page without those | ||
| 5 | + * links. | ||
| 6 | + */ | ||
| 7 | +(function () { | ||
| 8 | + "use strict"; | ||
| 9 | + | ||
| 10 | + document.addEventListener("keydown", function (event) { | ||
| 11 | + if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) { | ||
| 12 | + return; | ||
| 13 | + } | ||
| 14 | + if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") { | ||
| 15 | + return; | ||
| 16 | + } | ||
| 17 | + var target = event.target; | ||
| 18 | + if (target instanceof HTMLElement && | ||
| 19 | + (target.isContentEditable || /^(input|textarea|select)$/i.test(target.tagName))) { | ||
| 20 | + return; | ||
| 21 | + } | ||
| 22 | + var link = document.querySelector( | ||
| 23 | + event.key === "ArrowLeft" ? 'a[data-nav="prev"]' : 'a[data-nav="next"]' | ||
| 24 | + ); | ||
| 25 | + if (!link) { | ||
| 26 | + return; | ||
| 27 | + } | ||
| 28 | + event.preventDefault(); | ||
| 29 | + link.click(); | ||
| 30 | + }); | ||
| 31 | +})(); | ||
crates/in-web/build.rsmodified+3 -1
| @@ -1,6 +1,7 @@ | |||
| 1 | //! Build script of the `in` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it | 1 | //! Build script of the `in` binary. It compiles `style/main.scss` into `OUT_DIR/main.css`, and it |
| 2 | //! emits the build identity and the content hashes that the page links use as cache-busting | 2 | //! emits the build identity and the content hashes that the page links use as cache-busting |
| 3 | -//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V`, `IN_DRIVE_JS_V` and `IN_BUILD_SHA`. | 3 | +//! queries: `IN_MAIN_CSS_V`, `IN_NAV_JS_V`, `IN_PAGES_JS_V`, `IN_DRIVE_JS_V`, `IN_VIEWER_JS_V` and |
| 4 | +//! `IN_BUILD_SHA`. | ||
| 4 | //! | 5 | //! |
| 5 | //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a | 6 | //! It does not decide what is served: `src/assets.rs` embeds the files. It does not decide what a |
| 6 | //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles | 7 | //! page links to either: `src/assets.rs` builds the `?v=` URLs from these values. It only compiles |
| @@ -46,6 +47,7 @@ fn main() { | |||
| 46 | ("IN_NAV_JS_V", "assets/nav.js"), | 47 | ("IN_NAV_JS_V", "assets/nav.js"), |
| 47 | ("IN_PAGES_JS_V", "assets/pages.js"), | 48 | ("IN_PAGES_JS_V", "assets/pages.js"), |
| 48 | ("IN_DRIVE_JS_V", "assets/drive.js"), | 49 | ("IN_DRIVE_JS_V", "assets/drive.js"), |
| 50 | + ("IN_VIEWER_JS_V", "assets/viewer.js"), | ||
| 49 | ] { | 51 | ] { |
| 50 | let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); | 52 | let bytes = fs::read(manifest.join(file)).unwrap_or_else(|e| panic!("reading {file}: {e}")); |
| 51 | println!("cargo:rustc-env={var}={}", content_version(&bytes)); | 53 | println!("cargo:rustc-env={var}={}", content_version(&bytes)); |
crates/in-web/src/api/upload.rsmodified+7 -0
| @@ -608,6 +608,13 @@ mod tests { | |||
| 608 | .expect("request"); | 608 | .expect("request"); |
| 609 | let response = router(state.clone()).handle(request).await; | 609 | let response = router(state.clone()).handle(request).await; |
| 610 | assert_eq!(response.status(), StatusCode::OK); | 610 | assert_eq!(response.status(), StatusCode::OK); |
| 611 | + // The byte policy alone: the page policy must not be added on top of it. | ||
| 612 | + let policies: Vec<_> = response | ||
| 613 | + .headers() | ||
| 614 | + .get_all(http::header::CONTENT_SECURITY_POLICY) | ||
| 615 | + .iter() | ||
| 616 | + .collect(); | ||
| 617 | + assert_eq!(policies, [crate::serve_bytes::BYTES_CSP]); | ||
| 611 | let bytes = to_bytes(response.into_body(), 64 * 1024) | 618 | let bytes = to_bytes(response.into_body(), 64 * 1024) |
| 612 | .await | 619 | .await |
| 613 | .expect("body"); | 620 | .expect("body"); |
crates/in-web/src/assets.rsmodified+15 -0
| @@ -18,6 +18,10 @@ pub const NAV_JS_HREF: &str = concat!("/assets/nav.js?v=", env!("IN_NAV_JS_V")); | |||
| 18 | /// Link to the script of individual pages. | 18 | /// Link to the script of individual pages. |
| 19 | pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IN_PAGES_JS_V")); | 19 | pub const PAGES_JS_HREF: &str = concat!("/assets/pages.js?v=", env!("IN_PAGES_JS_V")); |
| 20 | 20 | ||
| 21 | +/// Link to the script of the viewer: the keyboard steps between files. Every page loads it; it does | ||
| 22 | +/// nothing unless a page has previous and next links. | ||
| 23 | +pub const VIEWER_JS_HREF: &str = concat!("/assets/viewer.js?v=", env!("IN_VIEWER_JS_V")); | ||
| 24 | + | ||
| 21 | /// Link to the upload queue of the drive pages. Only those pages load it. | 25 | /// Link to the upload queue of the drive pages. Only those pages load it. |
| 22 | pub const DRIVE_JS_HREF: &str = concat!("/assets/drive.js?v=", env!("IN_DRIVE_JS_V")); | 26 | pub const DRIVE_JS_HREF: &str = concat!("/assets/drive.js?v=", env!("IN_DRIVE_JS_V")); |
| 23 | 27 | ||
| @@ -25,6 +29,7 @@ const MAIN_CSS: &str = include_str!(concat!(env!("OUT_DIR"), "/main.css")); | |||
| 25 | const NAV_JS: &str = include_str!("../assets/nav.js"); | 29 | const NAV_JS: &str = include_str!("../assets/nav.js"); |
| 26 | const PAGES_JS: &str = include_str!("../assets/pages.js"); | 30 | const PAGES_JS: &str = include_str!("../assets/pages.js"); |
| 27 | const DRIVE_JS: &str = include_str!("../assets/drive.js"); | 31 | const DRIVE_JS: &str = include_str!("../assets/drive.js"); |
| 32 | +const VIEWER_JS: &str = include_str!("../assets/viewer.js"); | ||
| 28 | const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); | 33 | const OFFLINE_HTML: &str = include_str!("../assets/offline.html"); |
| 29 | const SW_JS: &str = include_str!("../assets/sw.js"); | 34 | const SW_JS: &str = include_str!("../assets/sw.js"); |
| 30 | 35 | ||
| @@ -69,6 +74,16 @@ async fn drive_js() -> Result<Asset> { | |||
| 69 | Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, DRIVE_JS)) | 74 | Ok(asset("text/javascript; charset=utf-8", IMMUTABLE, DRIVE_JS)) |
| 70 | } | 75 | } |
| 71 | 76 | ||
| 77 | +/// `GET /assets/viewer.js`. | ||
| 78 | +#[route(GET "/assets/viewer.js")] | ||
| 79 | +async fn viewer_js() -> Result<Asset> { | ||
| 80 | + Ok(asset( | ||
| 81 | + "text/javascript; charset=utf-8", | ||
| 82 | + IMMUTABLE, | ||
| 83 | + VIEWER_JS, | ||
| 84 | + )) | ||
| 85 | +} | ||
| 86 | + | ||
| 72 | /// `GET /assets/offline.html`. Also precached by the service worker. | 87 | /// `GET /assets/offline.html`. Also precached by the service worker. |
| 73 | #[route(GET "/assets/offline.html")] | 88 | #[route(GET "/assets/offline.html")] |
| 74 | async fn offline_html() -> Result<Asset> { | 89 | async fn offline_html() -> Result<Asset> { |
crates/in-web/src/boot.rsmodified+2 -0
| @@ -31,6 +31,7 @@ use crate::pages::not_found::NotFoundLayer; | |||
| 31 | use crate::security::{self, SecurityHeaders}; | 31 | use crate::security::{self, SecurityHeaders}; |
| 32 | use crate::state::AppState; | 32 | use crate::state::AppState; |
| 33 | use crate::sweeper; | 33 | use crate::sweeper; |
| 34 | +use crate::thumbs_worker; | ||
| 34 | 35 | ||
| 35 | /// Name of the instance key file inside the data directory. | 36 | /// Name of the instance key file inside the data directory. |
| 36 | const KEY_FILE: &str = "in.key"; | 37 | const KEY_FILE: &str = "in.key"; |
| @@ -49,6 +50,7 @@ pub async fn serve(config_path: &Path) -> Result<()> { | |||
| 49 | tokio::spawn(directory::run(state.clone(), stop_rx.clone())); | 50 | tokio::spawn(directory::run(state.clone(), stop_rx.clone())); |
| 50 | } | 51 | } |
| 51 | tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); | 52 | tokio::spawn(sweeper::run(state.clone(), stop_rx.clone())); |
| 53 | + tokio::spawn(thumbs_worker::run(state.clone(), stop_rx.clone())); | ||
| 52 | 54 | ||
| 53 | let listener = TcpListener::bind(listen).await.map_err(|error| { | 55 | let listener = TcpListener::bind(listen).await.map_err(|error| { |
| 54 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) | 56 | std::io::Error::new(error.kind(), format!("cannot bind {listen}: {error}")) |
crates/in-web/src/i18n/drive.rsmodified+16 -4
| @@ -80,8 +80,6 @@ pub enum DK { | |||
| 80 | PickHint, | 80 | PickHint, |
| 81 | /// Cancel a form and go back. | 81 | /// Cancel a form and go back. |
| 82 | Back, | 82 | Back, |
| 83 | - /// Field label: the MIME type. | ||
| 84 | - MimeType, | ||
| 85 | /// Drop overlay text on a drive page. | 83 | /// Drop overlay text on a drive page. |
| 86 | UploadDrop, | 84 | UploadDrop, |
| 87 | /// Queue row: an upload in progress. | 85 | /// Queue row: an upload in progress. |
| @@ -140,6 +138,14 @@ pub enum DK { | |||
| 140 | RefuseGeneric, | 138 | RefuseGeneric, |
| 141 | /// Refusal: the upload had no file in it. | 139 | /// Refusal: the upload had no file in it. |
| 142 | RefuseNoFile, | 140 | RefuseNoFile, |
| 141 | + /// The button to the previous file of the folder, in the current sort order. | ||
| 142 | + Previous, | ||
| 143 | + /// The button to the next file of the folder, in the current sort order. | ||
| 144 | + Next, | ||
| 145 | + /// The note under a text preview that is only the start of a longer file. | ||
| 146 | + TextTruncated, | ||
| 147 | + /// The note on the viewer of a type the page cannot show. | ||
| 148 | + NoPreview, | ||
| 143 | } | 149 | } |
| 144 | 150 | ||
| 145 | /// The text of `key` in `lang`. | 151 | /// The text of `key` in `lang`. |
| @@ -219,8 +225,6 @@ pub fn d(lang: Lang, key: DK) -> &'static str { | |||
| 219 | (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.", | 225 | (DK::PickHint, Lang::Tr) => "Taşınacağı klasörü seçin.", |
| 220 | (DK::Back, Lang::En) => "Back", | 226 | (DK::Back, Lang::En) => "Back", |
| 221 | (DK::Back, Lang::Tr) => "Geri", | 227 | (DK::Back, Lang::Tr) => "Geri", |
| 222 | - (DK::MimeType, Lang::En) => "Type", | ||
| 223 | - (DK::MimeType, Lang::Tr) => "Tür", | ||
| 224 | (DK::UploadDrop, Lang::En) => "Drop files anywhere on this page to upload them.", | 228 | (DK::UploadDrop, Lang::En) => "Drop files anywhere on this page to upload them.", |
| 225 | (DK::UploadDrop, Lang::Tr) => "Yüklemek için dosyaları bu sayfaya bırakın.", | 229 | (DK::UploadDrop, Lang::Tr) => "Yüklemek için dosyaları bu sayfaya bırakın.", |
| 226 | (DK::UploadUploading, Lang::En) => "Uploading", | 230 | (DK::UploadUploading, Lang::En) => "Uploading", |
| @@ -283,6 +287,14 @@ pub fn d(lang: Lang, key: DK) -> &'static str { | |||
| 283 | (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.", | 287 | (DK::RefuseGeneric, Lang::Tr) => "Değişiklik yapılamadı.", |
| 284 | (DK::RefuseNoFile, Lang::En) => "Choose at least one file.", | 288 | (DK::RefuseNoFile, Lang::En) => "Choose at least one file.", |
| 285 | (DK::RefuseNoFile, Lang::Tr) => "En az bir dosya seçin.", | 289 | (DK::RefuseNoFile, Lang::Tr) => "En az bir dosya seçin.", |
| 290 | + (DK::Previous, Lang::En) => "Previous", | ||
| 291 | + (DK::Previous, Lang::Tr) => "Önceki", | ||
| 292 | + (DK::Next, Lang::En) => "Next", | ||
| 293 | + (DK::Next, Lang::Tr) => "Sonraki", | ||
| 294 | + (DK::TextTruncated, Lang::En) => "Only the first 256 KiB of this file is shown.", | ||
| 295 | + (DK::TextTruncated, Lang::Tr) => "Bu dosyanın yalnızca ilk 256 KiB'si gösteriliyor.", | ||
| 296 | + (DK::NoPreview, Lang::En) => "This type of file cannot be previewed here.", | ||
| 297 | + (DK::NoPreview, Lang::Tr) => "Bu dosya türü burada önizlenemez.", | ||
| 286 | } | 298 | } |
| 287 | } | 299 | } |
| 288 | 300 | ||
crates/in-web/src/main.rsmodified+1 -0
| @@ -18,6 +18,7 @@ mod security; | |||
| 18 | mod serve_bytes; | 18 | mod serve_bytes; |
| 19 | mod state; | 19 | mod state; |
| 20 | mod sweeper; | 20 | mod sweeper; |
| 21 | +mod thumbs_worker; | ||
| 21 | mod views; | 22 | mod views; |
| 22 | 23 | ||
| 23 | use std::path::{Path, PathBuf}; | 24 | use std::path::{Path, PathBuf}; |
crates/in-web/src/pages/drive.rsmodified+3 -3
| @@ -436,7 +436,7 @@ struct LiveQuery { | |||
| 436 | folder: String, | 436 | folder: String, |
| 437 | } | 437 | } |
| 438 | 438 | ||
| 439 | -/// A fingerprint of what a listing shows: every row's id, name, size and last change. Equal text means | 439 | +/// A fingerprint of what a listing shows: every row's id, name, size, last change and thumbnail state. Equal text means |
| 440 | /// the page would look the same, so the stream stays quiet. | 440 | /// the page would look the same, so the stream stays quiet. |
| 441 | fn fingerprint(listing: &Listing) -> String { | 441 | fn fingerprint(listing: &Listing) -> String { |
| 442 | let mut text = String::new(); | 442 | let mut text = String::new(); |
| @@ -450,8 +450,8 @@ fn fingerprint(listing: &Listing) -> String { | |||
| 450 | for file in &listing.files { | 450 | for file in &listing.files { |
| 451 | let _ = writeln!( | 451 | let _ = writeln!( |
| 452 | text, | 452 | text, |
| 453 | - "f|{}|{}|{}|{}", | 453 | + "f|{}|{}|{}|{}|{}", |
| 454 | - file.id, file.name, file.size, file.updated_at | 454 | + file.id, file.name, file.size, file.updated_at, file.thumb_state |
| 455 | ); | 455 | ); |
| 456 | } | 456 | } |
| 457 | text | 457 | text |
crates/in-web/src/pages/mod.rsmodified+1 -0
| @@ -7,5 +7,6 @@ pub mod home; | |||
| 7 | pub mod not_found; | 7 | pub mod not_found; |
| 8 | pub mod photo; | 8 | pub mod photo; |
| 9 | pub mod sign_in; | 9 | pub mod sign_in; |
| 10 | +pub mod thumbs; | ||
| 10 | pub mod trash; | 11 | pub mod trash; |
| 11 | pub mod view; | 12 | pub mod view; |
crates/in-web/src/pages/thumbs.rsadded+90 -0
| @@ -0,0 +1,90 @@ | |||
| 1 | +//! The thumbnail of a file (`GET /thumb/{id}`). It is served by `serve_bytes`, so it has the same range, | ||
| 2 | +//! validator and header rules as the file bytes. Only a file whose thumbnail is `ready` has one; any other | ||
| 3 | +//! file, including a video, a PDF, a text file, a pending or a failed picture, is `404`. | ||
| 4 | +//! | ||
| 5 | +//! Authorization is the file's `View` check (`files::file_for`): a file the viewer may not see is `404`. | ||
| 6 | + | ||
| 7 | +use in_core::authz::Action; | ||
| 8 | +use in_core::store::files::thumb_blob_key; | ||
| 9 | +use sha2::{Digest, Sha256}; | ||
| 10 | +use topcoat::Result; | ||
| 11 | +use topcoat::context::{Cx, app_context}; | ||
| 12 | +use topcoat::router::error::not_found; | ||
| 13 | +use topcoat::router::{path_param_segment, route}; | ||
| 14 | + | ||
| 15 | +use crate::auth::require_member; | ||
| 16 | +use crate::pages::files::file_for; | ||
| 17 | +use crate::serve_bytes::{ByteAnswer, ByteSource, Disposition, serve_bytes}; | ||
| 18 | +use crate::state::AppState; | ||
| 19 | + | ||
| 20 | +/// The validator of a thumbnail: the SHA-256 of a fixed label and the file's own digest. It differs from the | ||
| 21 | +/// file's ETag, because the thumbnail is other bytes, and it changes only when the file's bytes change. | ||
| 22 | +pub fn thumb_validator(file_sha256: &str) -> String { | ||
| 23 | + Sha256::digest(format!("thumb:{file_sha256}")) | ||
| 24 | + .iter() | ||
| 25 | + .map(|b| format!("{b:02x}")) | ||
| 26 | + .collect() | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// `GET /thumb/{id}`: the WebP thumbnail of a picture. | ||
| 30 | +#[route(GET "/thumb/{id}")] | ||
| 31 | +async fn thumb(cx: &Cx) -> Result<ByteAnswer> { | ||
| 32 | + let state = app_context::<AppState>(cx); | ||
| 33 | + let viewer = require_member(cx).await?; | ||
| 34 | + let id = path_param_segment(cx, "id").to_owned(); | ||
| 35 | + let file = file_for(state, &viewer, &id, Action::View).await?; | ||
| 36 | + if file.thumb_state != "ready" { | ||
| 37 | + return Err(not_found().into()); | ||
| 38 | + } | ||
| 39 | + let key = thumb_blob_key(&file.id); | ||
| 40 | + let size = state.blobs.size(&key).await?.ok_or_else(not_found)?; | ||
| 41 | + let validator = thumb_validator(&file.sha256); | ||
| 42 | + let source = ByteSource { | ||
| 43 | + blob_key: &key, | ||
| 44 | + size, | ||
| 45 | + sha256: &validator, | ||
| 46 | + mime: "image/webp", | ||
| 47 | + name: &file.name, | ||
| 48 | + }; | ||
| 49 | + serve_bytes(cx, state.blobs.as_ref(), &source, Disposition::Inline).await | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +#[cfg(test)] | ||
| 53 | +mod tests { | ||
| 54 | + use crate::auth::{SESSION_COOKIE, test_support::signed_in}; | ||
| 55 | + use crate::boot::{router, test_state}; | ||
| 56 | + use http::Request; | ||
| 57 | + use http::header::COOKIE; | ||
| 58 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 59 | + use in_core::store::files::NewFile; | ||
| 60 | + use in_core::store::new_id; | ||
| 61 | + use topcoat::router::Body; | ||
| 62 | + | ||
| 63 | + /// A thumbnail of a text file is `404`: only pictures get thumbnails. | ||
| 64 | + #[tokio::test] | ||
| 65 | + async fn a_thumbnail_of_a_non_picture_is_not_found() { | ||
| 66 | + let (_dir, state) = test_state().await; | ||
| 67 | + let token = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 68 | + let id = new_id(); | ||
| 69 | + state | ||
| 70 | + .store | ||
| 71 | + .insert_file(NewFile { | ||
| 72 | + id: id.clone(), | ||
| 73 | + owner: "ann".into(), | ||
| 74 | + folder: None, | ||
| 75 | + name: "notes.txt".into(), | ||
| 76 | + mime: "text/plain".into(), | ||
| 77 | + size: 0, | ||
| 78 | + sha256: "0".repeat(64), | ||
| 79 | + staged_claims: 0, | ||
| 80 | + }) | ||
| 81 | + .await | ||
| 82 | + .expect("row"); | ||
| 83 | + let request = Request::get(format!("/thumb/{id}")) | ||
| 84 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 85 | + .body(Body::empty()) | ||
| 86 | + .expect("request"); | ||
| 87 | + let response = router(state.clone()).handle(request).await; | ||
| 88 | + assert_eq!(response.status(), 404); | ||
| 89 | + } | ||
| 90 | +} | ||
crates/in-web/src/pages/view.rsmodified+305 -24
| @@ -1,46 +1,205 @@ | |||
| 1 | -//! The viewer page of a file (`GET /view/{id}`). This is the minimal version: the name, size, type, the | 1 | +//! The viewer of a file (`GET /view/{id}`). The file is shown by its type: an image in an `<img>`, video and |
| 2 | -//! last change, and the links to the bytes (shown, and downloaded). The image, video, audio, PDF and | 2 | +//! audio in `<video>` and `<audio>` on the bytes (the bytes answer `Range`), a PDF in an `<iframe>` on the bytes, |
| 3 | -//! text viewers come with the viewer step, and replace the body of this page. | 3 | +//! plain text as its first 256 KiB in a `<pre>`, and anything else as a card with a download link. Above the |
| 4 | +//! file are the previous and next file of the folder in the listing's sort order; below it are the row actions | ||
| 5 | +//! (download, rename, move, trash). | ||
| 4 | //! | 6 | //! |
| 5 | -//! Authorization is the file's `View` check (`files::file_for`): a file the viewer may not see is `404`. | 7 | +//! Authorization is the file's `View` check (`files::file_for`): a file the viewer may not see is `404`. The |
| 8 | +//! previous and next files come from the same owner's folder, so they are never another person's. A trashed | ||
| 9 | +//! file is shown to its owner without neighbours. | ||
| 10 | +//! | ||
| 11 | +//! The page CSP is the global one. It has no `media-src` or `frame-src`, so `default-src 'self'` applies to | ||
| 12 | +//! both, which allows the same-origin bytes this page embeds. The bytes keep their own sandboxed CSP. | ||
| 6 | 13 | ||
| 14 | +use futures_util::StreamExt; | ||
| 7 | use in_core::authz::Action; | 15 | use in_core::authz::Action; |
| 8 | use in_core::store::files::File; | 16 | use in_core::store::files::File; |
| 17 | +use in_core::store::folders::Listing; | ||
| 9 | use topcoat::Result; | 18 | use topcoat::Result; |
| 10 | use topcoat::context::{Cx, app_context}; | 19 | use topcoat::context::{Cx, app_context}; |
| 11 | use topcoat::router::page; | 20 | use topcoat::router::page; |
| 12 | -use topcoat::router::path_param_segment; | 21 | +use topcoat::router::{parse_query_params, path_param_segment}; |
| 13 | use topcoat::view::{View, component, view}; | 22 | use topcoat::view::{View, component, view}; |
| 14 | 23 | ||
| 15 | use crate::auth::require_member; | 24 | use crate::auth::require_member; |
| 16 | use crate::i18n::Lang; | 25 | use crate::i18n::Lang; |
| 17 | use crate::i18n::drive::{DK, d}; | 26 | use crate::i18n::drive::{DK, d}; |
| 18 | -use crate::pages::drive::viewer_lang; | 27 | +use crate::pages::drive::{ListQuery, SortKey, sort_listing, viewer_lang}; |
| 19 | use crate::pages::files::file_for; | 28 | use crate::pages::files::file_for; |
| 29 | +use crate::serve_bytes::inline_safe; | ||
| 20 | use crate::state::AppState; | 30 | use crate::state::AppState; |
| 21 | -use crate::views::drive::{size_text, stamp_text}; | 31 | +use crate::views::drive::{flash, row_menu, size_text, stamp_text}; |
| 22 | use crate::views::{ViewerInfo, shell}; | 32 | use crate::views::{ViewerInfo, shell}; |
| 23 | 33 | ||
| 24 | -/// The details of a file and the two links to its bytes. | 34 | +/// How much of a text file the viewer reads and shows: 256 KiB. The rest is not read. |
| 35 | +pub const TEXT_PREVIEW_BYTES: u64 = 256 * 1024; | ||
| 36 | + | ||
| 37 | +/// Which viewer a file gets, by its stored type: `image`, `video`, `audio`, `pdf`, `text`, or `other`. A type | ||
| 38 | +/// the byte route would not show inline (SVG, HEIC, HTML) is `other`, so the page never embeds it. | ||
| 39 | +pub fn viewer_kind(mime: &str) -> &'static str { | ||
| 40 | + if !inline_safe(mime) { | ||
| 41 | + return "other"; | ||
| 42 | + } | ||
| 43 | + let essence = mime | ||
| 44 | + .split(';') | ||
| 45 | + .next() | ||
| 46 | + .unwrap_or_default() | ||
| 47 | + .trim() | ||
| 48 | + .to_ascii_lowercase(); | ||
| 49 | + if essence.starts_with("image/") { | ||
| 50 | + "image" | ||
| 51 | + } else if essence.starts_with("video/") { | ||
| 52 | + "video" | ||
| 53 | + } else if essence.starts_with("audio/") { | ||
| 54 | + "audio" | ||
| 55 | + } else if essence == "application/pdf" { | ||
| 56 | + "pdf" | ||
| 57 | + } else if essence == "text/plain" { | ||
| 58 | + "text" | ||
| 59 | + } else { | ||
| 60 | + "other" | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// The first [`TEXT_PREVIEW_BYTES`] of a text file, decoded leniently, and whether the file is longer. | ||
| 65 | +async fn text_head(state: &AppState, file: &File) -> Result<(String, bool)> { | ||
| 66 | + let size = u64::try_from(file.size).unwrap_or(0); | ||
| 67 | + let len = size.min(TEXT_PREVIEW_BYTES); | ||
| 68 | + let mut frames = state.blobs.open_range(&file.blob_key, 0, len).await?; | ||
| 69 | + let mut bytes = Vec::with_capacity(len as usize); | ||
| 70 | + while let Some(frame) = frames.next().await { | ||
| 71 | + bytes.extend_from_slice(&frame?); | ||
| 72 | + } | ||
| 73 | + Ok(( | ||
| 74 | + String::from_utf8_lossy(&bytes).into_owned(), | ||
| 75 | + size > TEXT_PREVIEW_BYTES, | ||
| 76 | + )) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// The viewer links of the files before and after `file` in its folder, in the listing's sort order. Each is a | ||
| 80 | +/// `/view` link that carries the sort, so stepping through keeps the order. Empty when there is none. | ||
| 81 | +async fn neighbours( | ||
| 82 | + state: &AppState, | ||
| 83 | + owner: &str, | ||
| 84 | + file: &File, | ||
| 85 | + query: &ListQuery, | ||
| 86 | +) -> Result<(String, String)> { | ||
| 87 | + if file.trashed_at.is_some() { | ||
| 88 | + return Ok((String::new(), String::new())); | ||
| 89 | + } | ||
| 90 | + let key = SortKey::of(&query.sort); | ||
| 91 | + let descending = query.dir == "desc"; | ||
| 92 | + let mut listing: Listing = state | ||
| 93 | + .store | ||
| 94 | + .list_children(owner, file.folder_id.as_deref()) | ||
| 95 | + .await?; | ||
| 96 | + sort_listing(&mut listing, key, descending); | ||
| 97 | + let Some(at) = listing.files.iter().position(|f| f.id == file.id) else { | ||
| 98 | + return Ok((String::new(), String::new())); | ||
| 99 | + }; | ||
| 100 | + let dir = if descending { "desc" } else { "asc" }; | ||
| 101 | + let link = |other: &File| format!("/view/{}?sort={}&dir={dir}", other.id, key.word()); | ||
| 102 | + let prev = at | ||
| 103 | + .checked_sub(1) | ||
| 104 | + .and_then(|i| listing.files.get(i)) | ||
| 105 | + .map(link) | ||
| 106 | + .unwrap_or_default(); | ||
| 107 | + let next = listing.files.get(at + 1).map(link).unwrap_or_default(); | ||
| 108 | + Ok((prev, next)) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// The previous and next links. A missing neighbour is simply not shown. | ||
| 25 | #[component] | 112 | #[component] |
| 26 | -pub async fn file_details( | 113 | +pub async fn viewer_nav(lang: Lang, prev: &str, next: &str) -> Result<impl View> { |
| 114 | + Ok(view! { | ||
| 115 | + <nav class="viewer-nav" aria-label=(d(lang, DK::Name))> | ||
| 116 | + if !prev.is_empty() { | ||
| 117 | + <a class="button" data-nav="prev" rel="prev" href=(prev)>"\u{2190} " (d(lang, DK::Previous))</a> | ||
| 118 | + } | ||
| 119 | + if !next.is_empty() { | ||
| 120 | + <a class="button" data-nav="next" rel="next" href=(next)>(d(lang, DK::Next)) " \u{2192}"</a> | ||
| 121 | + } | ||
| 122 | + </nav> | ||
| 123 | + }) | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// The file itself, shown by its kind. The bytes come from `/file/{id}` (shown inline, the byte route allows | ||
| 127 | +/// it for these kinds). Text is escaped here, so a `<script>` in a file is shown as text. | ||
| 128 | +#[component] | ||
| 129 | +pub async fn viewer_stage( | ||
| 27 | lang: Lang, | 130 | lang: Lang, |
| 28 | file: &File, | 131 | file: &File, |
| 29 | - open: &str, | 132 | + kind: &str, |
| 30 | - download: &str, | 133 | + text: &str, |
| 134 | + truncated: bool, | ||
| 31 | ) -> Result<impl View> { | 135 | ) -> Result<impl View> { |
| 136 | + let src = format!("/file/{}", file.id); | ||
| 137 | + let download = format!("/file/{}?dl=1", file.id); | ||
| 32 | Ok(view! { | 138 | Ok(view! { |
| 33 | - <section class="drive file-page"> | 139 | + <div class="viewer-stage" data-kind=(kind)> |
| 140 | + if kind == "image" { | ||
| 141 | + <img class="viewer-image" src=(src.as_str()) alt=(file.name.as_str())> | ||
| 142 | + } | ||
| 143 | + if kind == "video" { | ||
| 144 | + <video class="viewer-video" controls="" preload="metadata" src=(src.as_str())> | ||
| 145 | + <a href=(download.as_str())>(d(lang, DK::Download))</a> | ||
| 146 | + </video> | ||
| 147 | + } | ||
| 148 | + if kind == "audio" { | ||
| 149 | + <audio class="viewer-audio" controls="" preload="metadata" src=(src.as_str())> | ||
| 150 | + <a href=(download.as_str())>(d(lang, DK::Download))</a> | ||
| 151 | + </audio> | ||
| 152 | + } | ||
| 153 | + if kind == "pdf" { | ||
| 154 | + <iframe class="viewer-frame" src=(src.as_str()) title=(file.name.as_str())></iframe> | ||
| 155 | + } | ||
| 156 | + if kind == "text" { | ||
| 157 | + <pre class="viewer-text">(text)</pre> | ||
| 158 | + if truncated { | ||
| 159 | + <p class="muted">(d(lang, DK::TextTruncated))</p> | ||
| 160 | + } | ||
| 161 | + } | ||
| 162 | + if kind == "other" { | ||
| 163 | + <div class="viewer-card"> | ||
| 164 | + <p class="muted">(d(lang, DK::NoPreview))</p> | ||
| 165 | + </div> | ||
| 166 | + } | ||
| 167 | + </div> | ||
| 168 | + }) | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +/// The whole page content below the shell: the back link, the flash line, the name and details, the | ||
| 172 | +/// neighbours, the file, and the actions. | ||
| 173 | +#[component] | ||
| 174 | +pub async fn viewer_body( | ||
| 175 | + lang: Lang, | ||
| 176 | + file: &File, | ||
| 177 | + back: &str, | ||
| 178 | + csrf: &str, | ||
| 179 | + kind: &str, | ||
| 180 | + text: &str, | ||
| 181 | + truncated: bool, | ||
| 182 | + prev: &str, | ||
| 183 | + next: &str, | ||
| 184 | + notice: &str, | ||
| 185 | + refusal: &str, | ||
| 186 | +) -> Result<impl View> { | ||
| 187 | + let download = format!("/file/{}?dl=1", file.id); | ||
| 188 | + let open = format!("/file/{}", file.id); | ||
| 189 | + let here = format!("/view/{}", file.id); | ||
| 190 | + Ok(view! { | ||
| 191 | + <section class="drive viewer-page"> | ||
| 192 | + <p><a href=(back)>"\u{2190} " (d(lang, DK::Back))</a></p> | ||
| 193 | + flash(lang: lang, notice: notice, refusal: refusal) | ||
| 34 | <h1>(file.name.as_str())</h1> | 194 | <h1>(file.name.as_str())</h1> |
| 35 | - <dl class="details"> | 195 | + <p class="muted">(file.mime.as_str()) " \u{b7} " (size_text(file.size)) " \u{b7} " (stamp_text(&file.updated_at))</p> |
| 36 | - <dt>(d(lang, DK::Size))</dt><dd>(size_text(file.size))</dd> | 196 | + viewer_nav(lang: lang, prev: prev, next: next) |
| 37 | - <dt>(d(lang, DK::MimeType))</dt><dd>(file.mime.as_str())</dd> | 197 | + viewer_stage(lang: lang, file: file, kind: kind, text: text, truncated: truncated) |
| 38 | - <dt>(d(lang, DK::Modified))</dt><dd>(stamp_text(&file.updated_at))</dd> | 198 | + <div class="actions"> |
| 39 | - </dl> | 199 | + <a class="button primary" href=(download.as_str())>(d(lang, DK::Download))</a> |
| 40 | - <p class="actions"> | 200 | + <a class="button" href=(open.as_str())>(d(lang, DK::OpenRaw))</a> |
| 41 | - <a class="button primary" href=(download)>(d(lang, DK::Download))</a> | 201 | + row_menu(lang: lang, csrf: csrf, back: here.as_str(), kind: "file", id: file.id.as_str(), name: file.name.as_str()) |
| 42 | - <a class="button" href=(open)>(d(lang, DK::OpenRaw))</a> | 202 | + </div> |
| 43 | - </p> | ||
| 44 | </section> | 203 | </section> |
| 45 | }) | 204 | }) |
| 46 | } | 205 | } |
| @@ -52,14 +211,136 @@ async fn view_page(cx: &Cx) -> Result<impl View> { | |||
| 52 | let viewer = require_member(cx).await?; | 211 | let viewer = require_member(cx).await?; |
| 53 | let lang = viewer_lang(cx, &viewer); | 212 | let lang = viewer_lang(cx, &viewer); |
| 54 | let id = path_param_segment(cx, "id").to_owned(); | 213 | let id = path_param_segment(cx, "id").to_owned(); |
| 214 | + let query: ListQuery = parse_query_params(cx).unwrap_or_default(); | ||
| 55 | let file = file_for(state, &viewer, &id, Action::View).await?; | 215 | let file = file_for(state, &viewer, &id, Action::View).await?; |
| 216 | + let kind = viewer_kind(&file.mime); | ||
| 217 | + let (text, truncated) = if kind == "text" { | ||
| 218 | + text_head(state, &file).await? | ||
| 219 | + } else { | ||
| 220 | + (String::new(), false) | ||
| 221 | + }; | ||
| 222 | + let (prev, next) = neighbours(state, &viewer.member.sub, &file, &query).await?; | ||
| 223 | + let back = if file.trashed_at.is_some() { | ||
| 224 | + "/trash".to_owned() | ||
| 225 | + } else { | ||
| 226 | + match file.folder_id.as_deref() { | ||
| 227 | + Some(folder) => format!("/drive/{folder}"), | ||
| 228 | + None => "/drive".to_owned(), | ||
| 229 | + } | ||
| 230 | + }; | ||
| 231 | + let csrf = viewer.session.csrf_token.clone(); | ||
| 56 | let info = ViewerInfo::of(&viewer); | 232 | let info = ViewerInfo::of(&viewer); |
| 57 | - let open = format!("/file/{}", file.id); | ||
| 58 | - let download = format!("/file/{}?dl=1", file.id); | ||
| 59 | let title = file.name.clone(); | 233 | let title = file.name.clone(); |
| 60 | Ok(view! { | 234 | Ok(view! { |
| 61 | shell(title: title.as_str(), lang: lang, viewer: Some(&info), | 235 | shell(title: title.as_str(), lang: lang, viewer: Some(&info), |
| 62 | - file_details(lang: lang, file: &file, open: open.as_str(), download: download.as_str()) | 236 | + viewer_body(lang: lang, file: &file, back: back.as_str(), csrf: csrf.as_str(), kind: kind, |
| 237 | + text: text.as_str(), truncated: truncated, prev: prev.as_str(), next: next.as_str(), | ||
| 238 | + notice: query.notice.as_str(), refusal: query.refusal.as_str()) | ||
| 63 | ) | 239 | ) |
| 64 | }) | 240 | }) |
| 65 | } | 241 | } |
| 242 | + | ||
| 243 | +#[cfg(test)] | ||
| 244 | +mod tests { | ||
| 245 | + use super::*; | ||
| 246 | + use crate::auth::SESSION_COOKIE; | ||
| 247 | + use crate::auth::test_support::signed_in; | ||
| 248 | + use crate::boot::{router, test_state}; | ||
| 249 | + use http::Request; | ||
| 250 | + use http::header::COOKIE; | ||
| 251 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 252 | + use in_core::staging::{Staged, StagedFile}; | ||
| 253 | + use in_core::store::files::{NewFile, files_blob_key}; | ||
| 254 | + use in_core::store::new_id; | ||
| 255 | + use topcoat::router::{Body, to_bytes}; | ||
| 256 | + | ||
| 257 | + /// A file of `owner` with `bytes` stored under its key and a row of type `mime`. | ||
| 258 | + async fn stored_file( | ||
| 259 | + state: &AppState, | ||
| 260 | + owner: &str, | ||
| 261 | + name: &str, | ||
| 262 | + bytes: &[u8], | ||
| 263 | + mime: &str, | ||
| 264 | + ) -> File { | ||
| 265 | + let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) | ||
| 266 | + .await | ||
| 267 | + .expect("staging"); | ||
| 268 | + staged.write(bytes).await.expect("write"); | ||
| 269 | + let Staged { path, sha256, .. } = staged.finish().await.expect("finish"); | ||
| 270 | + let id = new_id(); | ||
| 271 | + state | ||
| 272 | + .blobs | ||
| 273 | + .put_file(&files_blob_key(&id), &path) | ||
| 274 | + .await | ||
| 275 | + .expect("blob"); | ||
| 276 | + state | ||
| 277 | + .store | ||
| 278 | + .insert_file(NewFile { | ||
| 279 | + id, | ||
| 280 | + owner: owner.into(), | ||
| 281 | + folder: None, | ||
| 282 | + name: name.into(), | ||
| 283 | + mime: mime.into(), | ||
| 284 | + size: bytes.len() as i64, | ||
| 285 | + sha256, | ||
| 286 | + staged_claims: 0, | ||
| 287 | + }) | ||
| 288 | + .await | ||
| 289 | + .expect("row") | ||
| 290 | + } | ||
| 291 | + | ||
| 292 | + async fn get_as(state: &AppState, path: &str, token: &str) -> (u16, String) { | ||
| 293 | + let request = Request::get(path) | ||
| 294 | + .header(COOKIE, format!("{SESSION_COOKIE}={token}")) | ||
| 295 | + .body(Body::empty()) | ||
| 296 | + .expect("request"); | ||
| 297 | + let response = router(state.clone()).handle(request).await; | ||
| 298 | + let status = response.status().as_u16(); | ||
| 299 | + let body = to_bytes(response.into_body(), 1 << 20).await.expect("body"); | ||
| 300 | + (status, String::from_utf8_lossy(&body).into_owned()) | ||
| 301 | + } | ||
| 302 | + | ||
| 303 | + #[test] | ||
| 304 | + fn viewer_kinds_follow_the_inline_rules() { | ||
| 305 | + assert_eq!(viewer_kind("image/png"), "image"); | ||
| 306 | + assert_eq!(viewer_kind("image/svg+xml"), "other"); | ||
| 307 | + assert_eq!(viewer_kind("image/heic"), "other"); | ||
| 308 | + assert_eq!(viewer_kind("video/mp4"), "video"); | ||
| 309 | + assert_eq!(viewer_kind("audio/mpeg"), "audio"); | ||
| 310 | + assert_eq!(viewer_kind("application/pdf"), "pdf"); | ||
| 311 | + assert_eq!(viewer_kind("text/plain; charset=utf-8"), "text"); | ||
| 312 | + assert_eq!(viewer_kind("text/html"), "other"); | ||
| 313 | + assert_eq!(viewer_kind("application/zip"), "other"); | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + #[tokio::test] | ||
| 317 | + async fn another_members_file_has_no_viewer() { | ||
| 318 | + let (_dir, state) = test_state().await; | ||
| 319 | + let _ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 320 | + let bob = signed_in(&state, "bob", DEFAULT_MEMBER_QUOTA).await; | ||
| 321 | + let file = stored_file(&state, "ann", "notes.txt", b"hello", "text/plain").await; | ||
| 322 | + let (status, _) = get_as(&state, &format!("/view/{}", file.id), &bob).await; | ||
| 323 | + assert_eq!(status, 404, "a foreign id must look missing"); | ||
| 324 | + } | ||
| 325 | + | ||
| 326 | + #[tokio::test] | ||
| 327 | + async fn a_text_preview_escapes_markup() { | ||
| 328 | + let (_dir, state) = test_state().await; | ||
| 329 | + let ann = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 330 | + let file = stored_file( | ||
| 331 | + &state, | ||
| 332 | + "ann", | ||
| 333 | + "page.txt", | ||
| 334 | + b"<script>alert(1)</script>", | ||
| 335 | + "text/plain", | ||
| 336 | + ) | ||
| 337 | + .await; | ||
| 338 | + let (status, html) = get_as(&state, &format!("/view/{}", file.id), &ann).await; | ||
| 339 | + assert_eq!(status, 200); | ||
| 340 | + assert!( | ||
| 341 | + html.contains("<script>alert(1)</script>"), | ||
| 342 | + "{html}" | ||
| 343 | + ); | ||
| 344 | + assert!(!html.contains("<script>alert(1)"), "the text must not run"); | ||
| 345 | + } | ||
| 346 | +} | ||
crates/in-web/src/security.rsmodified+19 -2
| @@ -63,8 +63,25 @@ impl Layer for SecurityHeaders { | |||
| 63 | 63 | ||
| 64 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { | 64 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 65 | Box::pin(async move { | 65 | Box::pin(async move { |
| 66 | - response_headers(cx).extend(self.headers.clone()); | 66 | + match next.run(cx, body).await { |
| 67 | - next.run(cx, body).await | 67 | + // A header the route set itself wins: byte responses carry their own sandboxed |
| 68 | + // policy, and two policies would apply both (the page one forbids framing). | ||
| 69 | + Ok(mut response) => { | ||
| 70 | + let headers = response.headers_mut(); | ||
| 71 | + for (name, value) in &self.headers { | ||
| 72 | + if !headers.contains_key(name) { | ||
| 73 | + headers.insert(name.clone(), value.clone()); | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | + Ok(response) | ||
| 77 | + } | ||
| 78 | + // Errors become responses after the layers have run; the per-request slot gives | ||
| 79 | + // them the headers too. | ||
| 80 | + Err(error) => { | ||
| 81 | + response_headers(cx).extend(self.headers.clone()); | ||
| 82 | + Err(error) | ||
| 83 | + } | ||
| 84 | + } | ||
| 68 | }) | 85 | }) |
| 69 | } | 86 | } |
| 70 | } | 87 | } |
crates/in-web/src/serve_bytes.rsmodified+20 -7
| @@ -17,7 +17,7 @@ use futures_util::TryStreamExt; | |||
| 17 | use http::header::{ | 17 | use http::header::{ |
| 18 | ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, | 18 | ACCEPT_RANGES, CACHE_CONTROL, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE, |
| 19 | CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, | 19 | CONTENT_SECURITY_POLICY, CONTENT_TYPE, ETAG, IF_NONE_MATCH, IF_RANGE, RANGE, |
| 20 | - X_CONTENT_TYPE_OPTIONS, | 20 | + X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS, |
| 21 | }; | 21 | }; |
| 22 | use http_body::Frame; | 22 | use http_body::Frame; |
| 23 | use http_body_util::StreamBody; | 23 | use http_body_util::StreamBody; |
| @@ -56,8 +56,15 @@ pub type ByteAnswer = (StatusCode, HeaderMap, Body); | |||
| 56 | 56 | ||
| 57 | /// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and | 57 | /// `Content-Security-Policy` of every byte response. The sandbox makes the document opaque, and |
| 58 | /// `default-src 'none'` stops it from loading anything but its own image, media or style. | 58 | /// `default-src 'none'` stops it from loading anything but its own image, media or style. |
| 59 | -pub const BYTES_CSP: &str = | 59 | +/// Only the viewer page of this origin may frame the bytes. |
| 60 | - "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'"; | 60 | +pub const BYTES_CSP: &str = "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; \ |
| 61 | + style-src 'unsafe-inline'; frame-ancestors 'self'"; | ||
| 62 | + | ||
| 63 | +/// The same policy without `sandbox`, for PDFs only: browsers refuse to run their PDF viewer in a | ||
| 64 | +/// sandboxed document. A PDF is never interpreted as HTML (`nosniff`, fixed type), and the viewers | ||
| 65 | +/// keep PDF scripts away from the origin. | ||
| 66 | +pub const PDF_CSP: &str = "default-src 'none'; img-src 'self'; media-src 'self'; \ | ||
| 67 | + style-src 'unsafe-inline'; frame-ancestors 'self'"; | ||
| 61 | 68 | ||
| 62 | /// Cache policy of content addressed by id and hash: the bytes behind a URL never change. | 69 | /// Cache policy of content addressed by id and hash: the bytes behind a URL never change. |
| 63 | const BYTES_CACHE: &str = "private, max-age=31536000, immutable"; | 70 | const BYTES_CACHE: &str = "private, max-age=31536000, immutable"; |
| @@ -257,12 +264,18 @@ pub fn content_disposition(kind: Disposition, name: &str) -> String { | |||
| 257 | } | 264 | } |
| 258 | 265 | ||
| 259 | /// The headers every byte response carries, whatever its status. | 266 | /// The headers every byte response carries, whatever its status. |
| 260 | -fn common_headers(etag: &str) -> HeaderMap { | 267 | +fn common_headers(etag: &str, mime: &str) -> HeaderMap { |
| 261 | let mut headers = HeaderMap::new(); | 268 | let mut headers = HeaderMap::new(); |
| 262 | insert(&mut headers, ETAG, etag); | 269 | insert(&mut headers, ETAG, etag); |
| 263 | headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); | 270 | headers.insert(ACCEPT_RANGES, HeaderValue::from_static("bytes")); |
| 264 | headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); | 271 | headers.insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff")); |
| 265 | - headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(BYTES_CSP)); | 272 | + let csp = if mime == "application/pdf" { |
| 273 | + PDF_CSP | ||
| 274 | + } else { | ||
| 275 | + BYTES_CSP | ||
| 276 | + }; | ||
| 277 | + headers.insert(CONTENT_SECURITY_POLICY, HeaderValue::from_static(csp)); | ||
| 278 | + headers.insert(X_FRAME_OPTIONS, HeaderValue::from_static("SAMEORIGIN")); | ||
| 266 | headers.insert( | 279 | headers.insert( |
| 267 | HeaderName::from_static("cross-origin-resource-policy"), | 280 | HeaderName::from_static("cross-origin-resource-policy"), |
| 268 | HeaderValue::from_static("same-origin"), | 281 | HeaderValue::from_static("same-origin"), |
| @@ -281,7 +294,7 @@ fn insert(headers: &mut HeaderMap, name: http::HeaderName, value: &str) { | |||
| 281 | 294 | ||
| 282 | /// The `416` answer: no body, and the length the client may ask again within. | 295 | /// The `416` answer: no body, and the length the client may ask again within. |
| 283 | fn unsatisfiable(etag: &str, len: u64) -> ByteAnswer { | 296 | fn unsatisfiable(etag: &str, len: u64) -> ByteAnswer { |
| 284 | - let mut headers = common_headers(etag); | 297 | + let mut headers = common_headers(etag, ""); |
| 285 | insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); | 298 | insert(&mut headers, CONTENT_RANGE, &format!("bytes */{len}")); |
| 286 | (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) | 299 | (StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()) |
| 287 | } | 300 | } |
| @@ -304,7 +317,7 @@ pub async fn serve_bytes( | |||
| 304 | Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, | 317 | Disposition::Inline if inline_safe(source.mime) => Disposition::Inline, |
| 305 | _ => Disposition::Attachment, | 318 | _ => Disposition::Attachment, |
| 306 | }; | 319 | }; |
| 307 | - let mut answer_headers = common_headers(&etag); | 320 | + let mut answer_headers = common_headers(&etag, source.mime); |
| 308 | insert( | 321 | insert( |
| 309 | &mut answer_headers, | 322 | &mut answer_headers, |
| 310 | CONTENT_DISPOSITION, | 323 | CONTENT_DISPOSITION, |
crates/in-web/src/sweeper.rsmodified+234 -10
| @@ -1,15 +1,25 @@ | |||
| 1 | -//! The hourly sweeper. It removes what has expired and nothing else: sessions past their expiry, back-channel | 1 | +//! The hourly sweeper. It removes what has expired or is no longer named by any row, and nothing else. Each |
| 2 | -//! logout ids past their expiry (the replay guard only needs them while the token could still arrive), and | 2 | +//! pass does these steps, and a failed step is logged while the others still run: |
| 3 | -//! open uploads that were not finished within 24 hours, with their staging directories. | ||
| 4 | //! | 3 | //! |
| 5 | -//! Each pass runs once at boot and then every hour, and stops with the shared stop flag. A failed pass is | 4 | +//! - sessions past their expiry, back-channel logout ids past their expiry, and open uploads not finished in |
| 6 | -//! logged and the next one runs as usual; nothing it does is needed for a request to be served correctly. | 5 | +//! 24 hours, with their staging directories; |
| 6 | +//! - trash older than `purge_after_days` (a setting, 30 by default), with its bytes; | ||
| 7 | +//! - blobs under `files/`, `thumbs/` and `objects/` that no row names and that are at least 24 hours old; | ||
| 8 | +//! - leftover files in `data_dir/tmp` at least 24 hours old; | ||
| 9 | +//! - once a day, the quota check: every member's `used_bytes` is recomputed from their files, and any | ||
| 10 | +//! difference is logged and corrected. | ||
| 11 | +//! | ||
| 12 | +//! The rows go first, in their own transactions; the bytes are deleted after the row that named them is gone. | ||
| 13 | +//! No blob is removed while a row names it, and none younger than 24 hours is removed for lacking a row, which | ||
| 14 | +//! covers a write whose row has not yet committed. | ||
| 7 | 15 | ||
| 8 | -use std::time::Duration; | 16 | +use std::collections::HashSet; |
| 17 | +use std::path::Path; | ||
| 18 | +use std::time::{Duration, SystemTime}; | ||
| 9 | 19 | ||
| 10 | use in_core::error::Result; | 20 | use in_core::error::Result; |
| 11 | -use in_core::staging::remove_upload_dir; | 21 | +use in_core::staging::{TMP_DIR, remove_upload_dir}; |
| 12 | -use in_core::time::now_stamp; | 22 | +use in_core::time::{now_stamp, stamp_before}; |
| 13 | use tokio::sync::watch; | 23 | use tokio::sync::watch; |
| 14 | 24 | ||
| 15 | use crate::state::AppState; | 25 | use crate::state::AppState; |
| @@ -17,6 +27,24 @@ use crate::state::AppState; | |||
| 17 | /// Time between two passes: one hour. | 27 | /// Time between two passes: one hour. |
| 18 | pub const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); | 28 | pub const SWEEP_EVERY: Duration = Duration::from_secs(60 * 60); |
| 19 | 29 | ||
| 30 | +/// Age a blob or a staged file must reach before the sweeper may remove it for lacking a row: 24 hours. | ||
| 31 | +pub const ORPHAN_GRACE: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 32 | + | ||
| 33 | +/// Trash older than this many days is purged when the `purge_after_days` setting is absent: 30. | ||
| 34 | +pub const DEFAULT_PURGE_AFTER_DAYS: u64 = 30; | ||
| 35 | + | ||
| 36 | +/// The settings key that overrides [`DEFAULT_PURGE_AFTER_DAYS`]. | ||
| 37 | +pub const PURGE_SETTING: &str = "purge_after_days"; | ||
| 38 | + | ||
| 39 | +/// The settings key that records when the quota check last ran. | ||
| 40 | +const DRIFT_SETTING: &str = "quota_drift_checked_at"; | ||
| 41 | + | ||
| 42 | +/// Time between two quota checks: a day. | ||
| 43 | +const DRIFT_EVERY: Duration = Duration::from_secs(24 * 60 * 60); | ||
| 44 | + | ||
| 45 | +/// The blob prefixes the sweeper owns. `objects/` is included because the `objects` table names its keys. | ||
| 46 | +const BLOB_PREFIXES: [&str; 3] = ["files/", "thumbs/", "objects/"]; | ||
| 47 | + | ||
| 20 | /// Runs passes until the stop flag is set. | 48 | /// Runs passes until the stop flag is set. |
| 21 | pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { | 49 | pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { |
| 22 | loop { | 50 | loop { |
| @@ -30,8 +58,8 @@ pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { | |||
| 30 | } | 58 | } |
| 31 | } | 59 | } |
| 32 | 60 | ||
| 33 | -/// One pass. The rows go first, in their own transactions; the staging directories of the expired uploads | 61 | +/// One pass. The expiry steps come first; each later step is independent, so a failure in one is logged and |
| 34 | -/// go after, so a request that races the pass finds no row and writes nothing. | 62 | +/// the rest still run. |
| 35 | pub async fn sweep(state: &AppState) -> Result<()> { | 63 | pub async fn sweep(state: &AppState) -> Result<()> { |
| 36 | let now = now_stamp(); | 64 | let now = now_stamp(); |
| 37 | let sessions = state.store.sweep_expired_sessions(&now).await?; | 65 | let sessions = state.store.sweep_expired_sessions(&now).await?; |
| @@ -48,5 +76,201 @@ pub async fn sweep(state: &AppState) -> Result<()> { | |||
| 48 | expired_uploads = uploads.len(), | 76 | expired_uploads = uploads.len(), |
| 49 | "sweeper: pass done" | 77 | "sweeper: pass done" |
| 50 | ); | 78 | ); |
| 79 | + log_step("trash", purge_trash(state).await); | ||
| 80 | + log_step("blobs", sweep_blobs(state, SystemTime::now()).await); | ||
| 81 | + log_step( | ||
| 82 | + "tmp", | ||
| 83 | + sweep_tmp(&state.config.data_dir, SystemTime::now()).await, | ||
| 84 | + ); | ||
| 85 | + log_step("quota", check_quota_drift(state).await); | ||
| 51 | Ok(()) | 86 | Ok(()) |
| 52 | } | 87 | } |
| 88 | + | ||
| 89 | +/// Logs a failed step and drops its error, so one failing step does not stop the pass. | ||
| 90 | +fn log_step<T>(step: &str, outcome: Result<T>) { | ||
| 91 | + if let Err(error) = outcome { | ||
| 92 | + tracing::warn!(step, error = %error, "sweeper: step failed"); | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// The number of days trash is kept: the setting when it holds a number, else the default. Clamped to 1 to | ||
| 97 | +/// 3650 days. | ||
| 98 | +pub async fn purge_after_days(state: &AppState) -> Result<u64> { | ||
| 99 | + let value = state.store.get_setting(PURGE_SETTING).await?; | ||
| 100 | + Ok(value | ||
| 101 | + .and_then(|text| text.trim().parse::<u64>().ok()) | ||
| 102 | + .unwrap_or(DEFAULT_PURGE_AFTER_DAYS) | ||
| 103 | + .clamp(1, 3650)) | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// Purges trash older than the retention period, and deletes the bytes the store released. The rows go first; | ||
| 107 | +/// a blob that fails to delete is logged and left for a later pass to find as unreferenced. | ||
| 108 | +async fn purge_trash(state: &AppState) -> Result<usize> { | ||
| 109 | + let days = purge_after_days(state).await?; | ||
| 110 | + let cutoff = stamp_before(Duration::from_secs(days * 24 * 60 * 60)); | ||
| 111 | + let keys = state.store.purge_trashed_before(&cutoff).await?; | ||
| 112 | + let count = keys.len(); | ||
| 113 | + for key in &keys { | ||
| 114 | + if let Err(error) = state.blobs.delete(key).await { | ||
| 115 | + tracing::warn!(key = %key, error = %error, "sweeper: released blob not deleted"); | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + if count > 0 { | ||
| 119 | + tracing::info!(released_blobs = count, "sweeper: trash purged"); | ||
| 120 | + } | ||
| 121 | + Ok(count) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// True when `modified` is at least [`ORPHAN_GRACE`] before `now`. A timestamp in the future counts as young. | ||
| 125 | +fn is_old(modified: SystemTime, now: SystemTime) -> bool { | ||
| 126 | + now.duration_since(modified) | ||
| 127 | + .is_ok_and(|age| age >= ORPHAN_GRACE) | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/// Removes the blobs that no row names and that are at least [`ORPHAN_GRACE`] old, as of `now`. The set of | ||
| 131 | +/// referenced keys is read before the listing, so a blob written in between is young and kept. | ||
| 132 | +pub async fn sweep_blobs(state: &AppState, now: SystemTime) -> Result<usize> { | ||
| 133 | + let referenced: HashSet<String> = state | ||
| 134 | + .store | ||
| 135 | + .referenced_blob_keys() | ||
| 136 | + .await? | ||
| 137 | + .into_iter() | ||
| 138 | + .collect(); | ||
| 139 | + let mut removed = 0; | ||
| 140 | + for prefix in BLOB_PREFIXES { | ||
| 141 | + for (key, _size, modified) in state.blobs.list(prefix).await? { | ||
| 142 | + if referenced.contains(&key) || !is_old(modified, now) { | ||
| 143 | + continue; | ||
| 144 | + } | ||
| 145 | + match state.blobs.delete(&key).await { | ||
| 146 | + Ok(()) => removed += 1, | ||
| 147 | + Err(error) => { | ||
| 148 | + tracing::warn!(key = %key, error = %error, "sweeper: orphan blob not deleted"); | ||
| 149 | + } | ||
| 150 | + } | ||
| 151 | + } | ||
| 152 | + } | ||
| 153 | + if removed > 0 { | ||
| 154 | + tracing::info!( | ||
| 155 | + orphan_blobs = removed, | ||
| 156 | + "sweeper: unreferenced blobs removed" | ||
| 157 | + ); | ||
| 158 | + } | ||
| 159 | + Ok(removed) | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// Removes the plain files in `data_dir/tmp` that are at least [`ORPHAN_GRACE`] old. Links are never followed, | ||
| 163 | +/// and only regular files are removed. The directory is the fixed staging directory of the data directory. | ||
| 164 | +pub async fn sweep_tmp(data_dir: &Path, now: SystemTime) -> Result<usize> { | ||
| 165 | + let dir = data_dir.join(TMP_DIR); | ||
| 166 | + let mut entries = match tokio::fs::read_dir(&dir).await { | ||
| 167 | + Ok(entries) => entries, | ||
| 168 | + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0), | ||
| 169 | + Err(error) => return Err(error.into()), | ||
| 170 | + }; | ||
| 171 | + let mut removed = 0; | ||
| 172 | + while let Some(entry) = entries.next_entry().await? { | ||
| 173 | + let path = entry.path(); | ||
| 174 | + let Ok(meta) = tokio::fs::symlink_metadata(&path).await else { | ||
| 175 | + continue; | ||
| 176 | + }; | ||
| 177 | + if !meta.is_file() { | ||
| 178 | + continue; | ||
| 179 | + } | ||
| 180 | + let Ok(modified) = meta.modified() else { | ||
| 181 | + continue; | ||
| 182 | + }; | ||
| 183 | + if !is_old(modified, now) { | ||
| 184 | + continue; | ||
| 185 | + } | ||
| 186 | + match tokio::fs::remove_file(&path).await { | ||
| 187 | + Ok(()) => removed += 1, | ||
| 188 | + Err(error) => tracing::warn!(error = %error, "sweeper: staged leftover not removed"), | ||
| 189 | + } | ||
| 190 | + } | ||
| 191 | + if removed > 0 { | ||
| 192 | + tracing::info!( | ||
| 193 | + staged_leftovers = removed, | ||
| 194 | + "sweeper: staging leftovers removed" | ||
| 195 | + ); | ||
| 196 | + } | ||
| 197 | + Ok(removed) | ||
| 198 | +} | ||
| 199 | + | ||
| 200 | +/// Recomputes every member's used bytes from their files, at most once a day. Each difference is logged with | ||
| 201 | +/// the stored and the true value, and then corrected. Returns the number of members corrected. | ||
| 202 | +pub async fn check_quota_drift(state: &AppState) -> Result<usize> { | ||
| 203 | + if let Some(last) = state.store.get_setting(DRIFT_SETTING).await? | ||
| 204 | + && last > stamp_before(DRIFT_EVERY) | ||
| 205 | + { | ||
| 206 | + return Ok(0); | ||
| 207 | + } | ||
| 208 | + let drift = state.store.reconcile_quota().await?; | ||
| 209 | + for item in &drift { | ||
| 210 | + tracing::warn!( | ||
| 211 | + member = %item.sub, | ||
| 212 | + stored = item.stored, | ||
| 213 | + actual = item.actual, | ||
| 214 | + "sweeper: quota drift corrected" | ||
| 215 | + ); | ||
| 216 | + } | ||
| 217 | + state.store.set_setting(DRIFT_SETTING, &now_stamp()).await?; | ||
| 218 | + Ok(drift.len()) | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +#[cfg(test)] | ||
| 222 | +mod tests { | ||
| 223 | + use super::*; | ||
| 224 | + use crate::auth::test_support::signed_in; | ||
| 225 | + use crate::boot::test_state; | ||
| 226 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 227 | + use in_core::staging::StagedFile; | ||
| 228 | + use in_core::store::files::{NewFile, files_blob_key}; | ||
| 229 | + use in_core::store::new_id; | ||
| 230 | + | ||
| 231 | + /// Stores `bytes` under `key`, as an upload would: staged, then moved into the blob store. | ||
| 232 | + async fn put_bytes(state: &AppState, key: &str, bytes: &[u8]) { | ||
| 233 | + let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) | ||
| 234 | + .await | ||
| 235 | + .expect("staging"); | ||
| 236 | + staged.write(bytes).await.expect("write"); | ||
| 237 | + let staged = staged.finish().await.expect("finish"); | ||
| 238 | + state.blobs.put_file(key, &staged.path).await.expect("blob"); | ||
| 239 | + } | ||
| 240 | + | ||
| 241 | + /// A referenced blob survives every pass. An unreferenced blob survives while it is young and goes once it | ||
| 242 | + /// is older than the grace period. | ||
| 243 | + #[tokio::test] | ||
| 244 | + async fn referenced_blobs_stay_and_young_orphans_stay() { | ||
| 245 | + let (_dir, state) = test_state().await; | ||
| 246 | + let _ = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 247 | + let id = new_id(); | ||
| 248 | + let kept = files_blob_key(&id); | ||
| 249 | + put_bytes(&state, &kept, b"kept").await; | ||
| 250 | + state | ||
| 251 | + .store | ||
| 252 | + .insert_file(NewFile { | ||
| 253 | + id, | ||
| 254 | + owner: "ann".into(), | ||
| 255 | + folder: None, | ||
| 256 | + name: "kept.txt".into(), | ||
| 257 | + mime: "text/plain".into(), | ||
| 258 | + size: 4, | ||
| 259 | + sha256: "0".repeat(64), | ||
| 260 | + staged_claims: 0, | ||
| 261 | + }) | ||
| 262 | + .await | ||
| 263 | + .expect("row"); | ||
| 264 | + let orphan = "objects/svc-1/orphan"; | ||
| 265 | + put_bytes(&state, orphan, b"orphan").await; | ||
| 266 | + | ||
| 267 | + assert_eq!( | ||
| 268 | + sweep_blobs(&state, SystemTime::now()).await.expect("pass"), | ||
| 269 | + 0 | ||
| 270 | + ); | ||
| 271 | + let later = SystemTime::now() + ORPHAN_GRACE + Duration::from_secs(3600); | ||
| 272 | + assert_eq!(sweep_blobs(&state, later).await.expect("pass"), 1); | ||
| 273 | + assert_eq!(state.blobs.size(&kept).await.expect("size"), Some(4)); | ||
| 274 | + assert_eq!(state.blobs.size(orphan).await.expect("size"), None); | ||
| 275 | + } | ||
| 276 | +} | ||
crates/in-web/src/thumbs_worker.rsadded+180 -0
| @@ -0,0 +1,180 @@ | |||
| 1 | +//! The thumbnail worker. It takes the files whose thumbnail is `pending` (pictures of the types the decoder | ||
| 2 | +//! reads), makes a WebP thumbnail of each, stores it under `thumbs/<id>` and marks the file `ready`; a picture | ||
| 3 | +//! that cannot be decoded, or that is too large, is marked `failed`. It runs at most [`CONCURRENCY`] decodes at | ||
| 4 | +//! once, each on a blocking thread, and never runs an external program. | ||
| 5 | +//! | ||
| 6 | +//! Ordering: the thumbnail bytes are stored before the row says `ready`. If the file was purged while its | ||
| 7 | +//! thumbnail was made, the row update finds nothing and the stored bytes are deleted, so no row is left | ||
| 8 | +//! without its file. | ||
| 9 | + | ||
| 10 | +use std::time::Duration; | ||
| 11 | + | ||
| 12 | +use futures_util::{StreamExt, stream}; | ||
| 13 | +use in_core::error::{Error, Result}; | ||
| 14 | +use in_core::staging::{Staged, StagedFile}; | ||
| 15 | +use in_core::store::files::{File, thumb_blob_key}; | ||
| 16 | +use in_core::thumbs::{MAX_SOURCE_BYTES, make_thumbnail}; | ||
| 17 | +use tokio::sync::watch; | ||
| 18 | + | ||
| 19 | +use crate::live::Topic; | ||
| 20 | +use crate::state::AppState; | ||
| 21 | + | ||
| 22 | +/// Most files taken from the queue in one round. | ||
| 23 | +pub const BATCH: usize = 16; | ||
| 24 | + | ||
| 25 | +/// Most thumbnails made at the same time. | ||
| 26 | +pub const CONCURRENCY: usize = 2; | ||
| 27 | + | ||
| 28 | +/// How long the worker waits when the queue is empty before it looks again. | ||
| 29 | +pub const IDLE: Duration = Duration::from_secs(30); | ||
| 30 | + | ||
| 31 | +/// Largest thumbnail the worker stores. A 320 pixel lossless WebP is far below this. | ||
| 32 | +const MAX_THUMB_BYTES: u64 = 8 * 1024 * 1024; | ||
| 33 | + | ||
| 34 | +/// Runs rounds until the stop flag is set. A round that found work is followed at once by the next one. | ||
| 35 | +pub async fn run(state: AppState, mut stop: watch::Receiver<bool>) { | ||
| 36 | + loop { | ||
| 37 | + let handled = match work_batch(&state).await { | ||
| 38 | + Ok(count) => count, | ||
| 39 | + Err(error) => { | ||
| 40 | + tracing::warn!(error = %error, "thumbs: round failed"); | ||
| 41 | + 0 | ||
| 42 | + } | ||
| 43 | + }; | ||
| 44 | + let pause = if handled == 0 { IDLE } else { Duration::ZERO }; | ||
| 45 | + tokio::select! { | ||
| 46 | + _ = stop.wait_for(|stopped| *stopped) => return, | ||
| 47 | + () = tokio::time::sleep(pause) => {} | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// One round: up to [`BATCH`] pending files, [`CONCURRENCY`] at a time. Returns how many files it took. | ||
| 53 | +async fn work_batch(state: &AppState) -> Result<usize> { | ||
| 54 | + let files = state.store.pending_thumbs(BATCH).await?; | ||
| 55 | + let count = files.len(); | ||
| 56 | + stream::iter(files) | ||
| 57 | + .for_each_concurrent(CONCURRENCY, |file| make_one(state, file)) | ||
| 58 | + .await; | ||
| 59 | + Ok(count) | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// Makes the thumbnail of one file and records the outcome. Every taken file leaves `pending`, so the queue | ||
| 63 | +/// always shrinks. | ||
| 64 | +async fn make_one(state: &AppState, file: File) { | ||
| 65 | + let outcome = build(state, &file).await; | ||
| 66 | + let word = match outcome { | ||
| 67 | + Ok(()) => "ready", | ||
| 68 | + Err(ref error) => { | ||
| 69 | + tracing::info!(file = %file.id, error = %error, "thumbs: no thumbnail"); | ||
| 70 | + "failed" | ||
| 71 | + } | ||
| 72 | + }; | ||
| 73 | + match state.store.set_thumb_state(&file.id, word).await { | ||
| 74 | + Ok(true) => {} | ||
| 75 | + Ok(false) => { | ||
| 76 | + // The file was purged while its thumbnail was made. Its bytes are not named by any row now. | ||
| 77 | + if word == "ready" { | ||
| 78 | + let _ = state.blobs.delete(&thumb_blob_key(&file.id)).await; | ||
| 79 | + } | ||
| 80 | + } | ||
| 81 | + Err(error) => tracing::warn!(file = %file.id, error = %error, "thumbs: state not saved"), | ||
| 82 | + } | ||
| 83 | + state.live.bump(&Topic::Drive(file.owner.clone())); | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// Decodes the stored picture and stores its thumbnail. Any failure is returned, and the caller marks the | ||
| 87 | +/// file `failed`. | ||
| 88 | +async fn build(state: &AppState, file: &File) -> Result<()> { | ||
| 89 | + let size = u64::try_from(file.size).unwrap_or(u64::MAX); | ||
| 90 | + if size > MAX_SOURCE_BYTES { | ||
| 91 | + return Err(Error::Invalid("too_large".into())); | ||
| 92 | + } | ||
| 93 | + let source = read_source(state, file, size).await?; | ||
| 94 | + // The decoder is CPU work: it runs on a blocking thread, never on the async runtime. | ||
| 95 | + let webp = tokio::task::spawn_blocking(move || make_thumbnail(&source)) | ||
| 96 | + .await | ||
| 97 | + .map_err(|e| Error::Io(std::io::Error::other(e)))??; | ||
| 98 | + let mut staged = StagedFile::create(&state.config.data_dir, MAX_THUMB_BYTES).await?; | ||
| 99 | + if let Err(error) = staged.write(&webp).await { | ||
| 100 | + staged.abort().await; | ||
| 101 | + return Err(error); | ||
| 102 | + } | ||
| 103 | + let Staged { path, .. } = staged.finish().await?; | ||
| 104 | + if let Err(error) = state.blobs.put_file(&thumb_blob_key(&file.id), &path).await { | ||
| 105 | + let _ = tokio::fs::remove_file(&path).await; | ||
| 106 | + return Err(error); | ||
| 107 | + } | ||
| 108 | + Ok(()) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/// The whole stored picture, read in frames. `size` is at most [`MAX_SOURCE_BYTES`]. | ||
| 112 | +async fn read_source(state: &AppState, file: &File, size: u64) -> Result<Vec<u8>> { | ||
| 113 | + let mut frames = state.blobs.open_range(&file.blob_key, 0, size).await?; | ||
| 114 | + let mut bytes = Vec::with_capacity(size as usize); | ||
| 115 | + while let Some(frame) = frames.next().await { | ||
| 116 | + bytes.extend_from_slice(&frame?); | ||
| 117 | + } | ||
| 118 | + Ok(bytes) | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +#[cfg(test)] | ||
| 122 | +mod tests { | ||
| 123 | + use super::*; | ||
| 124 | + use crate::auth::test_support::signed_in; | ||
| 125 | + use crate::boot::test_state; | ||
| 126 | + use in_core::quota::DEFAULT_MEMBER_QUOTA; | ||
| 127 | + use in_core::staging::{Staged, StagedFile}; | ||
| 128 | + use in_core::store::files::{NewFile, files_blob_key}; | ||
| 129 | + use in_core::store::new_id; | ||
| 130 | + | ||
| 131 | + /// A PNG whose header claims 100000 by 100000 pixels, with valid chunk checksums. | ||
| 132 | + const BOMB_PNG: &[u8] = &[ | ||
| 133 | + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, | ||
| 134 | + 0x52, 0x00, 0x01, 0x86, 0xa0, 0x00, 0x01, 0x86, 0xa0, 0x08, 0x06, 0x00, 0x00, 0x00, 0xa8, | ||
| 135 | + 0x52, 0x0b, 0xc8, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, | ||
| 136 | + 0x60, 0x60, 0x60, 0x00, 0x00, 0x00, 0x05, 0x00, 0x01, 0xa5, 0xf6, 0x45, 0x40, 0x00, 0x00, | ||
| 137 | + 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, | ||
| 138 | + ]; | ||
| 139 | + | ||
| 140 | + /// A decompression bomb is marked `failed`, nothing is stored for it, and the queue is empty afterwards. | ||
| 141 | + #[tokio::test] | ||
| 142 | + async fn a_decompression_bomb_is_marked_failed_without_a_thumbnail() { | ||
| 143 | + let (_dir, state) = test_state().await; | ||
| 144 | + let _ = signed_in(&state, "ann", DEFAULT_MEMBER_QUOTA).await; | ||
| 145 | + let id = new_id(); | ||
| 146 | + let mut staged = StagedFile::create(&state.config.data_dir, 1 << 20) | ||
| 147 | + .await | ||
| 148 | + .expect("staging"); | ||
| 149 | + staged.write(BOMB_PNG).await.expect("write"); | ||
| 150 | + let Staged { path, sha256, .. } = staged.finish().await.expect("finish"); | ||
| 151 | + state | ||
| 152 | + .blobs | ||
| 153 | + .put_file(&files_blob_key(&id), &path) | ||
| 154 | + .await | ||
| 155 | + .expect("blob"); | ||
| 156 | + state | ||
| 157 | + .store | ||
| 158 | + .insert_file(NewFile { | ||
| 159 | + id: id.clone(), | ||
| 160 | + owner: "ann".into(), | ||
| 161 | + folder: None, | ||
| 162 | + name: "bomb.png".into(), | ||
| 163 | + mime: "image/png".into(), | ||
| 164 | + size: BOMB_PNG.len() as i64, | ||
| 165 | + sha256, | ||
| 166 | + staged_claims: 0, | ||
| 167 | + }) | ||
| 168 | + .await | ||
| 169 | + .expect("row"); | ||
| 170 | + | ||
| 171 | + assert_eq!(work_batch(&state).await.expect("round"), 1); | ||
| 172 | + let file = state.store.file(&id).await.expect("read").expect("row"); | ||
| 173 | + assert_eq!(file.thumb_state, "failed"); | ||
| 174 | + assert_eq!( | ||
| 175 | + state.blobs.size(&thumb_blob_key(&id)).await.expect("size"), | ||
| 176 | + None | ||
| 177 | + ); | ||
| 178 | + assert_eq!(work_batch(&state).await.expect("round"), 0); | ||
| 179 | + } | ||
| 180 | +} | ||
crates/in-web/src/views/drive.rsmodified+27 -1
| @@ -62,6 +62,25 @@ pub async fn flash(lang: Lang, notice: &str, refusal: &str) -> Result<impl View> | |||
| 62 | }) | 62 | }) |
| 63 | } | 63 | } |
| 64 | 64 | ||
| 65 | +/// A short label for a file's type, shown in place of a thumbnail: `IMG`, `VID`, `AUD`, `PDF`, `TXT`, or | ||
| 66 | +/// `FILE` for anything else. It is an abbreviation, so it needs no translation. | ||
| 67 | +pub fn kind_glyph(mime: &str) -> &'static str { | ||
| 68 | + let essence = mime.split(';').next().unwrap_or_default().trim(); | ||
| 69 | + if essence.starts_with("image/") { | ||
| 70 | + "IMG" | ||
| 71 | + } else if essence.starts_with("video/") { | ||
| 72 | + "VID" | ||
| 73 | + } else if essence.starts_with("audio/") { | ||
| 74 | + "AUD" | ||
| 75 | + } else if essence == "application/pdf" { | ||
| 76 | + "PDF" | ||
| 77 | + } else if essence == "text/plain" { | ||
| 78 | + "TXT" | ||
| 79 | + } else { | ||
| 80 | + "FILE" | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 65 | /// The breadcrumb trail, top level first. Empty for the top level, which needs no trail. | 84 | /// The breadcrumb trail, top level first. Empty for the top level, which needs no trail. |
| 66 | #[component] | 85 | #[component] |
| 67 | pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result<impl View> { | 86 | pub async fn crumbs(lang: Lang, trail: &[Folder]) -> Result<impl View> { |
| @@ -190,7 +209,14 @@ pub async fn listing_table( | |||
| 190 | for file in files { | 209 | for file in files { |
| 191 | <tr> | 210 | <tr> |
| 192 | <td><input type="checkbox" name="item" value=(format!("file:{}", file.id)) form="bulk-trash" aria-label=(file.name.as_str())></td> | 211 | <td><input type="checkbox" name="item" value=(format!("file:{}", file.id)) form="bulk-trash" aria-label=(file.name.as_str())></td> |
| 193 | - <td><a href=(format!("/view/{}", file.id))>(file.name.as_str())</a></td> | 212 | + <td class="name-cell"> |
| 213 | + if file.thumb_state == "ready" { | ||
| 214 | + <img class="thumb" src=(format!("/thumb/{}", file.id)) alt="" loading="lazy" width="40" height="40"> | ||
| 215 | + } else { | ||
| 216 | + <span class="thumb thumb-icon" aria-hidden="true">(kind_glyph(&file.mime))</span> | ||
| 217 | + } | ||
| 218 | + <a href=(format!("/view/{}?sort={sort}&dir={dir}", file.id))>(file.name.as_str())</a> | ||
| 219 | + </td> | ||
| 194 | <td>(size_text(file.size))</td> | 220 | <td>(size_text(file.size))</td> |
| 195 | <td class="muted">(stamp_text(&file.updated_at))</td> | 221 | <td class="muted">(stamp_text(&file.updated_at))</td> |
| 196 | <td>(d(lang, DK::FileKind))</td> | 222 | <td>(d(lang, DK::FileKind))</td> |
crates/in-web/src/views/mod.rsmodified+2 -1
| @@ -6,7 +6,7 @@ | |||
| 6 | use topcoat::Result; | 6 | use topcoat::Result; |
| 7 | use topcoat::view::{Child, View, component, view}; | 7 | use topcoat::view::{Child, View, component, view}; |
| 8 | 8 | ||
| 9 | -use crate::assets::{DRIVE_JS_HREF, MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF}; | 9 | +use crate::assets::{DRIVE_JS_HREF, MAIN_CSS_HREF, NAV_JS_HREF, PAGES_JS_HREF, VIEWER_JS_HREF}; |
| 10 | use crate::auth::Viewer; | 10 | use crate::auth::Viewer; |
| 11 | use crate::i18n::Lang; | 11 | use crate::i18n::Lang; |
| 12 | use crate::i18n::drive::{DK, d}; | 12 | use crate::i18n::drive::{DK, d}; |
| @@ -69,6 +69,7 @@ pub async fn shell( | |||
| 69 | <link rel="stylesheet" href=(MAIN_CSS_HREF)> | 69 | <link rel="stylesheet" href=(MAIN_CSS_HREF)> |
| 70 | <script src=(NAV_JS_HREF) defer=""></script> | 70 | <script src=(NAV_JS_HREF) defer=""></script> |
| 71 | <script src=(PAGES_JS_HREF) defer=""></script> | 71 | <script src=(PAGES_JS_HREF) defer=""></script> |
| 72 | + <script src=(VIEWER_JS_HREF) defer=""></script> | ||
| 72 | if drive_js { | 73 | if drive_js { |
| 73 | <script src=(DRIVE_JS_HREF) defer=""></script> | 74 | <script src=(DRIVE_JS_HREF) defer=""></script> |
| 74 | } | 75 | } |
style/_components.scssmodified+85 -0
| @@ -503,3 +503,88 @@ textarea::placeholder { | |||
| 503 | .drop-overlay.drop-overlay-show { | 503 | .drop-overlay.drop-overlay-show { |
| 504 | display: flex; | 504 | display: flex; |
| 505 | } | 505 | } |
| 506 | + | ||
| 507 | +// --- Thumbnails and the viewer --------------------------------------------------------------- | ||
| 508 | + | ||
| 509 | +.name-cell { | ||
| 510 | + display: flex; | ||
| 511 | + align-items: center; | ||
| 512 | + gap: var(--space-3); | ||
| 513 | +} | ||
| 514 | + | ||
| 515 | +.thumb { | ||
| 516 | + flex: none; | ||
| 517 | + width: 2.5rem; | ||
| 518 | + height: 2.5rem; | ||
| 519 | + border-radius: var(--radius-sm); | ||
| 520 | + object-fit: cover; | ||
| 521 | + background: var(--surface-2); | ||
| 522 | +} | ||
| 523 | + | ||
| 524 | +.thumb-icon { | ||
| 525 | + display: inline-flex; | ||
| 526 | + align-items: center; | ||
| 527 | + justify-content: center; | ||
| 528 | + border: 1px solid var(--border); | ||
| 529 | + color: var(--muted); | ||
| 530 | + font-family: var(--font-mono); | ||
| 531 | + font-size: 0.7rem; | ||
| 532 | +} | ||
| 533 | + | ||
| 534 | +.viewer-page .viewer-nav { | ||
| 535 | + display: flex; | ||
| 536 | + justify-content: space-between; | ||
| 537 | + gap: var(--space-2); | ||
| 538 | + margin-block: var(--space-3); | ||
| 539 | +} | ||
| 540 | + | ||
| 541 | +.viewer-stage { | ||
| 542 | + display: flex; | ||
| 543 | + flex-direction: column; | ||
| 544 | + align-items: center; | ||
| 545 | + gap: var(--space-3); | ||
| 546 | + min-height: 12rem; | ||
| 547 | +} | ||
| 548 | + | ||
| 549 | +.viewer-image { | ||
| 550 | + max-width: 100%; | ||
| 551 | + max-height: 75vh; | ||
| 552 | + object-fit: contain; | ||
| 553 | + border-radius: var(--radius-sm); | ||
| 554 | +} | ||
| 555 | + | ||
| 556 | +.viewer-video, | ||
| 557 | +.viewer-audio { | ||
| 558 | + max-width: 100%; | ||
| 559 | +} | ||
| 560 | + | ||
| 561 | +.viewer-video { | ||
| 562 | + max-height: 75vh; | ||
| 563 | +} | ||
| 564 | + | ||
| 565 | +.viewer-frame { | ||
| 566 | + width: 100%; | ||
| 567 | + height: 75vh; | ||
| 568 | + border: 1px solid var(--border); | ||
| 569 | + border-radius: var(--radius-sm); | ||
| 570 | +} | ||
| 571 | + | ||
| 572 | +.viewer-text { | ||
| 573 | + align-self: stretch; | ||
| 574 | + max-height: 75vh; | ||
| 575 | + overflow: auto; | ||
| 576 | + margin: 0; | ||
| 577 | + padding: var(--space-4); | ||
| 578 | + border: 1px solid var(--border); | ||
| 579 | + border-radius: var(--radius-sm); | ||
| 580 | + background: var(--surface); | ||
| 581 | + font-family: var(--font-mono); | ||
| 582 | + font-size: 0.875rem; | ||
| 583 | + white-space: pre-wrap; | ||
| 584 | + overflow-wrap: anywhere; | ||
| 585 | +} | ||
| 586 | + | ||
| 587 | +.viewer-card { | ||
| 588 | + padding: var(--space-6); | ||
| 589 | + text-align: center; | ||
| 590 | +} | ||