From 470a937d4b9e59b4437c242f4d50de00ead4db85 Mon Sep 17 00:00:00 2001 From: Mad0 Date: Tue, 10 Nov 2026 14:04:47 -0600 Subject: [PATCH 1/3] feat(gslides): add Google Slides vector extractor, 16:9 PDF compiler and gdocs platform --- browser-extension/chrome/src/detect.js | 17 + .../chrome/tests/detect.test.mjs | 12 + browser-extension/firefox/src/detect.js | 17 + src-tauri/Cargo.lock | 300 +++++- src-tauri/omniget-cli/src/commands/common.rs | 5 +- src-tauri/omniget-core/Cargo.toml | 2 + .../omniget-core/src/core/tools/gdocs.rs | 67 +- .../omniget-core/src/core/tools/gslides.rs | 933 ++++++++++++++++++ .../omniget-core/src/core/tools/jpeg_pdf.rs | 33 +- src-tauri/omniget-core/src/core/tools/mod.rs | 1 + src-tauri/omniget-core/src/platforms/gdocs.rs | 188 ++++ src-tauri/omniget-core/src/platforms/mod.rs | 6 + src-tauri/src/commands/tools/documents.rs | 18 +- src-tauri/src/core/url_parser.rs | 7 + src-tauri/src/lib.rs | 3 + src-tauri/src/local_bridge.rs | 201 ++++ src-tauri/src/platforms/mod.rs | 1 + src/components/icons/PlatformIcon.svelte | 6 + .../tools/documents/GdocsTool.svelte | 169 +++- src/lib/platform-display-names.ts | 1 + 20 files changed, 1955 insertions(+), 32 deletions(-) create mode 100644 src-tauri/omniget-core/src/core/tools/gslides.rs create mode 100644 src-tauri/omniget-core/src/platforms/gdocs.rs diff --git a/browser-extension/chrome/src/detect.js b/browser-extension/chrome/src/detect.js index 4e4c854e..9060c863 100644 --- a/browser-extension/chrome/src/detect.js +++ b/browser-extension/chrome/src/detect.js @@ -57,6 +57,7 @@ function detectPlatform(url) { if (matchesHost(host, "vimeo.com")) return "vimeo"; if (matchesHost(host, "udemy.com")) return "udemy"; if (matchesHost(host, "bilibili.com") || host === "b23.tv") return "bilibili"; + if (host === "docs.google.com") return "gdocs"; return null; } @@ -90,6 +91,8 @@ function detectContentType(platform, url) { return parseUdemy(segments); case "bilibili": return parseBilibili(segments); + case "gdocs": + return parseGdocs(segments); default: return "unknown"; } @@ -265,6 +268,20 @@ function parseBilibili(segments) { return segments[0] === "video" && segments[1] ? "video" : "unknown"; } +function parseGdocs(segments) { + if ( + (segments[0] === "presentation" || segments[0] === "document" || segments[0] === "spreadsheets") && + segments[1] === "d" && + segments[2] + ) { + if (segments[2] === "e") { + return segments[3] ? "post" : "unknown"; + } + return "post"; + } + return "unknown"; +} + function matchesHost(host, domain) { return host === domain || host.endsWith(`.${domain}`); } diff --git a/browser-extension/chrome/tests/detect.test.mjs b/browser-extension/chrome/tests/detect.test.mjs index a37d4d72..08de55cc 100644 --- a/browser-extension/chrome/tests/detect.test.mjs +++ b/browser-extension/chrome/tests/detect.test.mjs @@ -341,3 +341,15 @@ test("Bilibili: b23.tv short link", () => { test("Bilibili: homepage is unknown", () => { assertUnsupported("https://www.bilibili.com/", "bilibili", "unknown"); }); + +// ── Google Docs / Slides / Sheets ──────────────────────────────────────── + +test("Google Slides: standard presentation and pubembed", () => { + assertSupported("https://docs.google.com/presentation/d/1AbC_d-e/edit#slide=1", "gdocs", "post"); + assertSupported( + "https://docs.google.com/presentation/d/e/2PACX-1vMockDummyId1234567890abcdefghijklmnopqrstuvwxyz/pubembed?start=false", + "gdocs", + "post" + ); + assertUnsupported("https://docs.google.com/presentation/u/0/", "gdocs", "unknown"); +}); diff --git a/browser-extension/firefox/src/detect.js b/browser-extension/firefox/src/detect.js index 4e4c854e..9060c863 100644 --- a/browser-extension/firefox/src/detect.js +++ b/browser-extension/firefox/src/detect.js @@ -57,6 +57,7 @@ function detectPlatform(url) { if (matchesHost(host, "vimeo.com")) return "vimeo"; if (matchesHost(host, "udemy.com")) return "udemy"; if (matchesHost(host, "bilibili.com") || host === "b23.tv") return "bilibili"; + if (host === "docs.google.com") return "gdocs"; return null; } @@ -90,6 +91,8 @@ function detectContentType(platform, url) { return parseUdemy(segments); case "bilibili": return parseBilibili(segments); + case "gdocs": + return parseGdocs(segments); default: return "unknown"; } @@ -265,6 +268,20 @@ function parseBilibili(segments) { return segments[0] === "video" && segments[1] ? "video" : "unknown"; } +function parseGdocs(segments) { + if ( + (segments[0] === "presentation" || segments[0] === "document" || segments[0] === "spreadsheets") && + segments[1] === "d" && + segments[2] + ) { + if (segments[2] === "e") { + return segments[3] ? "post" : "unknown"; + } + return "post"; + } + return "unknown"; +} + function matchesHost(host, domain) { return host === domain || host.endsWith(`.${domain}`); } diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 207cb0ac..440fa40a 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -228,6 +228,18 @@ dependencies = [ "rustversion", ] +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + [[package]] name = "assert_cfg" version = "0.1.0" @@ -1389,6 +1401,15 @@ dependencies = [ "libc", ] +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cpubits" version = "0.1.1" @@ -1507,7 +1528,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" dependencies = [ "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -1615,6 +1636,12 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + [[package]] name = "dbus" version = "0.9.12" @@ -2086,6 +2113,15 @@ version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + [[package]] name = "event-listener" version = "2.5.3" @@ -2223,6 +2259,12 @@ dependencies = [ "zlib-rs", ] +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + [[package]] name = "fnv" version = "1.0.7" @@ -2241,6 +2283,29 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree", +] + +[[package]] +name = "fontdb" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3a6f9af55fb97ad673fb7a69533eb2f967648a06fa21f8c9bb2cd6d33975716" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", + "ttf-parser", +] + [[package]] name = "foreign-types" version = "0.3.2" @@ -2610,6 +2675,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "gif" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +dependencies = [ + "color_quant", + "weezl 0.1.12", +] + [[package]] name = "gif" version = "0.14.2" @@ -3417,8 +3492,8 @@ dependencies = [ "bytemuck", "byteorder-lite", "color_quant", - "gif", - "image-webp", + "gif 0.14.2", + "image-webp 0.2.4", "moxcms", "num-traits", "png 0.18.1", @@ -3427,6 +3502,16 @@ dependencies = [ "zune-jpeg 0.5.15", ] +[[package]] +name = "image-webp" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f79afb8cbee2ef20f59ccd477a218c12a93943d075b492015ecb1bb81f8ee904" +dependencies = [ + "byteorder-lite", + "quick-error", +] + [[package]] name = "image-webp" version = "0.2.4" @@ -3437,6 +3522,12 @@ dependencies = [ "quick-error", ] +[[package]] +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + [[package]] name = "indexmap" version = "1.9.3" @@ -3787,6 +3878,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "kurbo" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" +dependencies = [ + "arrayvec", + "euclid", + "smallvec", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -3885,6 +3987,12 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + [[package]] name = "libredox" version = "0.1.12" @@ -5179,6 +5287,7 @@ dependencies = [ "rand 0.10.2", "regex", "reqwest 0.12.28", + "resvg", "rust_xlsxwriter", "sanitize-filename", "serde", @@ -5647,6 +5756,12 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -6278,6 +6393,23 @@ dependencies = [ "web-sys", ] +[[package]] +name = "resvg" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a325d5e8d1cebddd070b13f44cec8071594ab67d1012797c121f27a669b7958" +dependencies = [ + "gif 0.13.3", + "image-webp 0.1.3", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", + "zune-jpeg 0.4.21", +] + [[package]] name = "rfd" version = "0.17.2" @@ -6304,6 +6436,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + [[package]] name = "ring" version = "0.17.14" @@ -6327,6 +6468,12 @@ dependencies = [ "libc", ] +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + [[package]] name = "rusqlite" version = "0.32.1" @@ -6501,6 +6648,24 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +[[package]] +name = "rustybuzz" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c85d1ccd519e61834798eb52c4e886e8c2d7d698dd3d6ce0b1b47eb8557f1181" +dependencies = [ + "bitflags 2.13.1", + "bytemuck", + "core_maths", + "log", + "smallvec", + "ttf-parser", + "unicode-bidi-mirroring", + "unicode-ccc", + "unicode-properties", + "unicode-script", +] + [[package]] name = "ryu" version = "1.0.23" @@ -6995,6 +7160,15 @@ version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2" +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" version = "1.0.2" @@ -7017,6 +7191,15 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + [[package]] name = "smallvec" version = "1.15.1" @@ -7124,6 +7307,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + [[package]] name = "string_cache" version = "0.9.0" @@ -7202,6 +7394,16 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "svgtypes" +version = "0.15.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo", + "siphasher", +] + [[package]] name = "swift-rs" version = "1.0.9" @@ -7950,6 +8152,32 @@ dependencies = [ "crunchy", ] +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png 0.17.16", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "tinystr" version = "0.8.2" @@ -8397,6 +8625,15 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "ttf-parser" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be21190ff5d38e8b4a2d3b6a3ae57f612cc39c96e83cedeaf7abc338a8bac4a" +dependencies = [ + "core_maths", +] + [[package]] name = "tungstenite" version = "0.24.0" @@ -8479,6 +8716,18 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" +[[package]] +name = "unicode-bidi-mirroring" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64af057ad7466495ca113126be61838d8af947f41d93a949980b2389a118082f" + +[[package]] +name = "unicode-ccc" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "260bc6647b3893a9a90668360803a15f96b85a5257b1c3a0c3daf6ae2496de42" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -8500,12 +8749,24 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +[[package]] +name = "unicode-script" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" + [[package]] name = "unicode-segmentation" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + [[package]] name = "unicode-width" version = "0.2.2" @@ -8567,6 +8828,33 @@ dependencies = [ "url", ] +[[package]] +name = "usvg" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7447e703d7223b067607655e625e0dbca80822880248937da65966194c4864e6" +dependencies = [ + "base64 0.22.1", + "data-url", + "flate2", + "fontdb", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "rustybuzz", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + [[package]] name = "utf-8" version = "0.7.6" @@ -10004,6 +10292,12 @@ dependencies = [ "markup5ever 0.38.0", ] +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + [[package]] name = "xz2" version = "0.1.7" diff --git a/src-tauri/omniget-cli/src/commands/common.rs b/src-tauri/omniget-cli/src/commands/common.rs index abb3e676..c87ab7b4 100644 --- a/src-tauri/omniget-cli/src/commands/common.rs +++ b/src-tauri/omniget-cli/src/commands/common.rs @@ -9,8 +9,8 @@ use omniget_core::models::media::{DownloadOptions, MediaInfo}; use omniget_core::models::settings::ProxySettings; use omniget_core::platforms::{ BilibiliDownloader, BlueskyDownloader, DirectFileDownloader, DouyinDownloader, - GenericYtdlpDownloader, InstagramDownloader, P2pDownloader, PinterestDownloader, - PlatformDownloader, RedditDownloader, ThreadsDownloader, TikTokDownloader, + GdocsDownloader, GenericYtdlpDownloader, InstagramDownloader, P2pDownloader, + PinterestDownloader, PlatformDownloader, RedditDownloader, ThreadsDownloader, TikTokDownloader, TwitchClipsDownloader, TwitterDownloader, VimeoDownloader, YouTubeDownloader, }; use tokio_util::sync::CancellationToken; @@ -93,6 +93,7 @@ pub fn core_platform_registry() -> PlatformRegistry { registry.register(Arc::new(BilibiliDownloader::new())); registry.register(Arc::new(DouyinDownloader::new())); registry.register(Arc::new(P2pDownloader::new())); + registry.register(Arc::new(GdocsDownloader::new())); registry.register(Arc::new(DirectFileDownloader::new())); registry.register(Arc::new(GenericYtdlpDownloader::new())); registry diff --git a/src-tauri/omniget-core/Cargo.toml b/src-tauri/omniget-core/Cargo.toml index 8d3b6472..b2d9e56a 100644 --- a/src-tauri/omniget-core/Cargo.toml +++ b/src-tauri/omniget-core/Cargo.toml @@ -65,6 +65,8 @@ trash = "5" enigo = { version = "0.6", default-features = false, features = ["x11rb"] } fs4 = "1" image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif", "ico"] } +# Renderizado vectorial SVG (Google Slides / Calameo -> PDF 16:9) em Rust puro. +resvg = "0.44" # Tags de audio (ID3/Vorbis/MP4) em Rust puro, sem binario externo. lofty = "0.25" # HTML -> Markdown para exportar posts (Substack/Medium), mesmo padrao do pdf-to-markdown. diff --git a/src-tauri/omniget-core/src/core/tools/gdocs.rs b/src-tauri/omniget-core/src/core/tools/gdocs.rs index 2f0a549f..4faeb9d5 100644 --- a/src-tauri/omniget-core/src/core/tools/gdocs.rs +++ b/src-tauri/omniget-core/src/core/tools/gdocs.rs @@ -11,24 +11,49 @@ pub struct GdocInfo { pub kind: String, pub id: String, pub formats: Vec, + #[serde(default)] + pub is_published: bool, } pub fn parse(url: &str) -> Option { + let pub_re = regex::Regex::new( + r"docs\.google\.com/(document|presentation|spreadsheets)/d/e/([A-Za-z0-9_-]+)", + ) + .ok()?; + if let Some(c) = pub_re.captures(url) { + let kind = c[1].to_string(); + let formats = match kind.as_str() { + "presentation" => vec!["pdf", "svg"], + "document" => vec!["pdf", "html"], + _ => vec!["pdf", "csv"], + }; + return Some(GdocInfo { + kind, + id: c[2].to_string(), + formats: formats.into_iter().map(String::from).collect(), + is_published: true, + }); + } + let re = regex::Regex::new( r"docs\.google\.com/(document|presentation|spreadsheets)/d/([A-Za-z0-9_-]+)", ) .ok()?; let c = re.captures(url)?; + if &c[2] == "e" { + return None; + } let kind = c[1].to_string(); let formats = match kind.as_str() { "document" => vec!["pdf", "docx", "odt", "txt", "epub", "html"], - "presentation" => vec!["pdf", "pptx", "odp", "txt"], + "presentation" => vec!["pdf", "pptx", "odp", "txt", "svg"], _ => vec!["pdf", "xlsx", "ods", "csv"], }; Some(GdocInfo { kind, id: c[2].to_string(), formats: formats.into_iter().map(String::from).collect(), + is_published: false, }) } @@ -68,16 +93,38 @@ pub async fn download( info.kind )); } - let client = super::client()?; + + if info.kind == "presentation" && (info.is_published || format == "svg") { + let res = super::gslides::download_presentation(url, format, dest_dir, progress).await?; + return Ok(res.output_path); + } + + let client = super::gslides::build_google_client(Some(url)).or_else(|_| super::client())?; let export = export_url(&info, format); let resp = client.get(&export).send().await?; - if resp.status().as_u16() == 401 || resp.status().as_u16() == 403 { + let status = resp.status(); + let is_html_redirect = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .map(|ct| ct.to_ascii_lowercase().starts_with("text/html") && format != "html") + .unwrap_or(false); + + if (!status.is_success() || is_html_redirect) && info.kind == "presentation" && format == "pdf" { + if let Ok(res) = + super::gslides::download_presentation(url, "pdf", dest_dir, progress.clone()).await + { + return Ok(res.output_path); + } + } + + if status.as_u16() == 401 || status.as_u16() == 403 { return Err(anyhow!( "o arquivo nao e publico; abra no navegador e use Arquivo > Fazer download" )); } - if !resp.status().is_success() { - return Err(anyhow!("Google Docs: HTTP {}", resp.status())); + if !status.is_success() { + return Err(anyhow!("Google Docs: HTTP {}", status)); } let name = resp .headers() @@ -110,11 +157,21 @@ mod tests { let i = parse("https://docs.google.com/presentation/d/1AbC_d-e/edit#slide=1").unwrap(); assert_eq!(i.kind, "presentation"); assert_eq!(i.id, "1AbC_d-e"); + assert!(!i.is_published); assert!(parse("https://drive.google.com/x").is_none()); assert_eq!( export_url(&i, "pdf"), "https://docs.google.com/presentation/d/1AbC_d-e/export?format=pdf" ); + + let pub_i = parse("https://docs.google.com/presentation/d/e/2PACX-1vMockDummyId1234567890abcdefghijklmnopqrstuvwxyz/pubembed?start=false&loop=false").unwrap(); + assert_eq!(pub_i.kind, "presentation"); + assert!(pub_i.is_published); + assert_eq!( + pub_i.id, + "2PACX-1vMockDummyId1234567890abcdefghijklmnopqrstuvwxyz" + ); + assert_eq!(pub_i.formats, vec!["pdf".to_string(), "svg".to_string()]); } #[test] diff --git a/src-tauri/omniget-core/src/core/tools/gslides.rs b/src-tauri/omniget-core/src/core/tools/gslides.rs new file mode 100644 index 00000000..d1e6b238 --- /dev/null +++ b/src-tauri/omniget-core/src/core/tools/gslides.rs @@ -0,0 +1,933 @@ +//! Extractor y compilador vectorial de Google Slides a PDF panorámico (16:9). +//! +//! Soporta: +//! 1. Enlaces publicados en la web (`/presentation/d/e/2PACX-.../pubembed` o `/pub`), +//! los cuales no disponen de `/export?format=pdf` (devuelven HTTP 404). +//! 2. Presentaciones restringidas donde `/export?format=pdf` devuelve 401/403 pero el +//! visor (`/embed` o `/htmlpresent`) entrega las diapositivas en bloques `SK_svgData`. +//! 3. Compilación local de carpetas de archivos `.svg` ordenados numéricamente (`resvg` + +//! `tiny-skia` -> PDF 16:9 de `1280 x 720 pt`) y recepción desde el script JS del +//! navegador a través del `local_bridge`. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, OnceLock}; + +use anyhow::{anyhow, Context}; +use base64::Engine; +use futures::stream::{self, StreamExt}; +use image::codecs::jpeg::JpegEncoder; +use image::ColorType; +use regex::Regex; +use resvg::{tiny_skia, usvg}; +use serde::{Deserialize, Serialize}; + +pub const SLIDE_WIDTH_PT: f64 = 1280.0; +pub const SLIDE_HEIGHT_PT: f64 = 720.0; + +/// Resolución de rasterizado en píxeles (Full HD 16:9) sobre página física de 1280x720 pt. +const RENDER_WIDTH_PX: u32 = 1920; +const RENDER_HEIGHT_PX: u32 = 1080; +const JPEG_QUALITY: u8 = 92; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct GslidesTarget { + pub id: String, + pub is_published: bool, +} + +impl GslidesTarget { + pub fn viewer_url(&self) -> String { + if self.is_published { + format!( + "https://docs.google.com/presentation/d/e/{}/pubembed?start=false&loop=false", + self.id + ) + } else { + format!( + "https://docs.google.com/presentation/d/{}/embed?start=false&loop=false", + self.id + ) + } + } + + pub fn htmlpresent_url(&self) -> String { + if self.is_published { + format!("https://docs.google.com/presentation/d/e/{}/pub", self.id) + } else { + format!( + "https://docs.google.com/presentation/d/{}/htmlpresent", + self.id + ) + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct GslidesDownloadResult { + pub title: String, + pub pages: usize, + pub output_path: String, + pub format: String, +} + +#[derive(Debug, Clone)] +pub struct ExtractedPresentation { + pub title: String, + pub svgs: Vec, +} + +/// Reconoce tanto `/presentation/d/e/2PACX-...` como `/presentation/d/{id}`. +pub fn parse_gslides_url(url: &str) -> Option { + static PUB_RE: OnceLock = OnceLock::new(); + static DOC_RE: OnceLock = OnceLock::new(); + + let pub_re = PUB_RE.get_or_init(|| { + Regex::new(r"docs\.google\.com/presentation/d/e/([A-Za-z0-9_-]+)").unwrap() + }); + if let Some(c) = pub_re.captures(url) { + return Some(GslidesTarget { + id: c[1].to_string(), + is_published: true, + }); + } + + let doc_re = DOC_RE + .get_or_init(|| Regex::new(r"docs\.google\.com/presentation/d/([A-Za-z0-9_-]+)").unwrap()); + let c = doc_re.captures(url)?; + let id = &c[1]; + if id == "e" { + return None; + } + Some(GslidesTarget { + id: id.to_string(), + is_published: false, + }) +} + +/// Decodifica cadenas literales de JavaScript como las que emite Google Slides +/// en `SK_svgData = '\x3csvg version\x3d\x221.1\x22 ...'`. +pub fn unescape_js_string(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + let bytes = raw.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'\\' && i + 1 < bytes.len() { + match bytes[i + 1] { + b'x' if i + 3 < bytes.len() => { + if let Ok(hex_str) = std::str::from_utf8(&bytes[i + 2..i + 4]) { + if let Ok(val) = u8::from_str_radix(hex_str, 16) { + out.push(val as char); + i += 4; + continue; + } + } + } + b'u' if i + 5 < bytes.len() => { + if let Ok(hex_str) = std::str::from_utf8(&bytes[i + 2..i + 6]) { + if let Ok(val) = u32::from_str_radix(hex_str, 16) { + if let Some(ch) = char::from_u32(val) { + out.push(ch); + i += 6; + continue; + } + } + } + } + b'/' => { + out.push('/'); + i += 2; + continue; + } + b'\\' => { + out.push('\\'); + i += 2; + continue; + } + b'\'' => { + out.push('\''); + i += 2; + continue; + } + b'"' => { + out.push('"'); + i += 2; + continue; + } + b'n' => { + out.push('\n'); + i += 2; + continue; + } + b'r' => { + out.push('\r'); + i += 2; + continue; + } + b't' => { + out.push('\t'); + i += 2; + continue; + } + _ => {} + } + } + // Avanza un carácter UTF-8 válido + let rest = &raw[i..]; + if let Some(ch) = rest.chars().next() { + out.push(ch); + i += ch.len_utf8(); + } else { + break; + } + } + out +} + +/// Fija explícitamente `width="1280px" height="720px" viewBox="0 0 1280 720"` +/// en el elemento `` raíz si aún no tiene `width`/`height` explícitos, +/// preservando el `viewBox` original si ya es proporcional o asignando `0 0 1280 720`. +pub fn normalize_slide_svg_geometry(svg: &str) -> String { + let trimmed = svg.trim(); + let Some(svg_start) = trimmed.find("') else { + return trimmed.to_string(); + }; + let tag_end = svg_start + tag_end_rel; + let open_tag = &trimmed[svg_start..=tag_end]; + + static WIDTH_RE: OnceLock = OnceLock::new(); + static HEIGHT_RE: OnceLock = OnceLock::new(); + static VIEWBOX_RE: OnceLock = OnceLock::new(); + + let width_re = WIDTH_RE.get_or_init(|| Regex::new(r#"\bwidth\s*=\s*"[^"]*""#).unwrap()); + let height_re = HEIGHT_RE.get_or_init(|| Regex::new(r#"\bheight\s*=\s*"[^"]*""#).unwrap()); + let viewbox_re = VIEWBOX_RE.get_or_init(|| Regex::new(r#"\bviewBox\s*=\s*"[^"]*""#).unwrap()); + + let mut cleaned = width_re.replace_all(open_tag, "").into_owned(); + cleaned = height_re.replace_all(&cleaned, "").into_owned(); + if !viewbox_re.is_match(&cleaned) { + cleaned = cleaned.replacen( + " String { + let mut t = raw + .replace("&", "&") + .replace(""", "\"") + .replace("'", "'") + .replace("<", "<") + .replace(">", ">"); + for suffix in [ + " - Presentaciones de Google", + " - Google Slides", + " - Apresentações Google", + " - Google 簡報", + " - Google 幻灯片", + " - Google スライド", + ] { + if let Some(stripped) = t.strip_suffix(suffix) { + t = stripped.to_string(); + } + } + for ext in [".pptx", ".ppt", ".odp", ".pdf"] { + if t.to_lowercase().ends_with(ext) && t.len() > ext.len() { + t.truncate(t.len() - ext.len()); + } + } + let trimmed = t.trim(); + if trimmed.is_empty() { + "presentacion_google_slides".to_string() + } else { + trimmed.to_string() + } +} + +pub fn extract_title_from_viewer_html(html: &str) -> String { + static VIEWER_TITLE_RE: OnceLock = OnceLock::new(); + static HTML_TITLE_RE: OnceLock = OnceLock::new(); + + let viewer_re = VIEWER_TITLE_RE + .get_or_init(|| Regex::new(r"title:\s*'((?:\\.|[^'])*)'").unwrap()); + let head_slice = &html[..html.len().min(350_000)]; + if let Some(c) = viewer_re.captures(head_slice) { + let decoded = unescape_js_string(&c[1]); + if !decoded.trim().is_empty() { + return clean_presentation_title(&decoded); + } + } + + let html_re = HTML_TITLE_RE + .get_or_init(|| Regex::new(r"(?is)]*>(.*?)").unwrap()); + if let Some(c) = html_re.captures(head_slice) { + let raw = c[1].trim(); + if !raw.is_empty() { + return clean_presentation_title(raw); + } + } + + "presentacion_google_slides".to_string() +} + +/// Extrae todos los bloques `SK_svgData` en el orden exacto de las diapositivas. +pub fn extract_viewer_slides(html: &str) -> ExtractedPresentation { + static SVG_DATA_RE: OnceLock = OnceLock::new(); + let re = SVG_DATA_RE + .get_or_init(|| Regex::new(r"SK_svgData\s*=\s*'((?:\\.|[^'])*)'").unwrap()); + + let title = extract_title_from_viewer_html(html); + let mut svgs = Vec::new(); + for cap in re.captures_iter(html) { + let decoded = unescape_js_string(&cap[1]); + if decoded.contains("`. +pub fn collect_remote_image_urls(svgs: &[String]) -> Vec { + static IMG_HREF_RE: OnceLock = OnceLock::new(); + let re = IMG_HREF_RE.get_or_init(|| { + Regex::new(r#"]*?\b(?:xlink:)?href\s*=\s*"(https?://[^"]+)""#).unwrap() + }); + + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for svg in svgs { + for cap in re.captures_iter(svg) { + let url = cap[1].replace("&", "&"); + if seen.insert(url.clone()) { + out.push(url); + } + } + } + out +} + +fn guess_image_mime(bytes: &[u8], content_type: Option<&str>) -> &'static str { + if bytes.starts_with(&[0x89, b'P', b'N', b'G']) { + return "image/png"; + } + if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + return "image/jpeg"; + } + if bytes.starts_with(b"GIF8") { + return "image/gif"; + } + if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + return "image/webp"; + } + if let Some(ct) = content_type { + let lower = ct.to_ascii_lowercase(); + if lower.contains("jpeg") || lower.contains("jpg") { + return "image/jpeg"; + } + if lower.contains("webp") { + return "image/webp"; + } + if lower.contains("gif") { + return "image/gif"; + } + if lower.contains("svg") { + return "image/svg+xml"; + } + } + "image/png" +} + +/// Descarga en paralelo las imágenes remotas referenciadas por los SVGs y las +/// incrusta como Data URLs (`data:;base64,...`) exactamente igual que +/// `svgImageToBase64` en el navegador, pero con deduplicación y concurrencia. +pub async fn embed_remote_images_base64( + client: &reqwest::Client, + svgs: &mut [String], + progress: &super::ProgressFn, + progress_id: &str, +) { + let urls = collect_remote_image_urls(svgs); + if urls.is_empty() { + return; + } + + let total_imgs = urls.len() as u64; + super::report( + progress, + progress_id, + "images", + 0, + Some(total_imgs), + Some(format!("Descargando {} recursos de imagen...", total_imgs)), + ); + + let fetched: Vec<(String, String)> = stream::iter(urls.into_iter().enumerate()) + .map(|(idx, url)| { + let client = client.clone(); + let progress = progress.clone(); + let progress_id = progress_id.to_string(); + async move { + let res = match client.get(&url).send().await { + Ok(r) if r.status().is_success() => { + let ct = r + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .map(|s| s.to_string()); + match r.bytes().await { + Ok(bytes) if !bytes.is_empty() => { + let mime = guess_image_mime(&bytes, ct.as_deref()); + let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes); + Some((url, format!("data:{};base64,{}", mime, b64))) + } + _ => None, + } + } + _ => None, + }; + if (idx + 1) % 5 == 0 || (idx + 1) as u64 == total_imgs { + super::report( + &progress, + &progress_id, + "images", + (idx + 1) as u64, + Some(total_imgs), + None, + ); + } + res + } + }) + .buffer_unordered(12) + .filter_map(|x| async move { x }) + .collect() + .await; + + if fetched.is_empty() { + return; + } + + let map: HashMap = fetched.into_iter().collect(); + + for svg in svgs.iter_mut() { + for (url, data_uri) in &map { + if svg.contains(url) { + *svg = svg.replace(url, data_uri); + } + let escaped = url.replace('&', "&"); + if escaped != *url && svg.contains(&escaped) { + *svg = svg.replace(&escaped, data_uri); + } + } + } +} + +fn shared_fontdb() -> Arc { + static FONTDB: OnceLock> = OnceLock::new(); + FONTDB + .get_or_init(|| { + let mut db = usvg::fontdb::Database::new(); + db.load_system_fonts(); + Arc::new(db) + }) + .clone() +} + +/// Renderiza un SVG a un buffer JPEG en memoria con proporción 16:9 usando `resvg` y `tiny-skia`. +pub fn render_svg_to_jpeg(svg_str: &str) -> anyhow::Result> { + let normalized = normalize_slide_svg_geometry(svg_str); + let opt = usvg::Options { + fontdb: shared_fontdb(), + ..Default::default() + }; + + let tree = usvg::Tree::from_data(normalized.as_bytes(), &opt) + .context("Error parseando el árbol SVG con usvg")?; + + let tree_size = tree.size(); + let target_w = RENDER_WIDTH_PX; + let target_h = RENDER_HEIGHT_PX; + + let mut pixmap = tiny_skia::Pixmap::new(target_w, target_h) + .ok_or_else(|| anyhow!("No se pudo reservar memoria para el pixmap {}x{}", target_w, target_h))?; + + // Fondo blanco por defecto para evitar transparencias negras al pasar a JPEG + pixmap.fill(tiny_skia::Color::WHITE); + + let sx = target_w as f32 / tree_size.width().max(1.0); + let sy = target_h as f32 / tree_size.height().max(1.0); + let transform = tiny_skia::Transform::from_scale(sx, sy); + + resvg::render(&tree, transform, &mut pixmap.as_mut()); + + // Convertir RGBA premultiplicado (tiny-skia) a RGB de 24 bits para JPEG + let rgba = pixmap.data(); + let mut rgb = Vec::with_capacity((target_w * target_h * 3) as usize); + for px in rgba.chunks_exact(4) { + let a = px[3] as u16; + if a == 255 { + rgb.push(px[0]); + rgb.push(px[1]); + rgb.push(px[2]); + } else if a == 0 { + rgb.push(255); + rgb.push(255); + rgb.push(255); + } else { + // Des-premultiplicar sobre fondo blanco + let r = ((px[0] as u16 * 255) / a).min(255) as u8; + let g = ((px[1] as u16 * 255) / a).min(255) as u8; + let b = ((px[2] as u16 * 255) / a).min(255) as u8; + rgb.push(r); + rgb.push(g); + rgb.push(b); + } + } + + let mut jpeg_buf = Vec::new(); + let mut encoder = JpegEncoder::new_with_quality(&mut jpeg_buf, JPEG_QUALITY); + encoder + .encode(&rgb, target_w, target_h, ColorType::Rgb8.into()) + .context("Error codificando diapositiva a JPEG")?; + + Ok(jpeg_buf) +} + +/// Compila una lista ordenada de SVGs en un documento PDF 16:9 (`1280 x 720 pt`). +pub fn compile_svgs_to_pdf( + svgs: &[String], + progress: &super::ProgressFn, + progress_id: &str, +) -> anyhow::Result> { + if svgs.is_empty() { + return Err(anyhow!("No hay diapositivas SVG para compilar")); + } + + let total = svgs.len() as u64; + let mut jpegs = Vec::with_capacity(svgs.len()); + + for (idx, svg_str) in svgs.iter().enumerate() { + super::report( + progress, + progress_id, + "compile", + idx as u64, + Some(total), + Some(format!("Renderizando diapositiva {}/{}...", idx + 1, total)), + ); + let jpeg = render_svg_to_jpeg(svg_str) + .with_context(|| format!("Error procesando diapositiva {}", idx + 1))?; + jpegs.push(jpeg); + } + + let pdf = super::jpeg_pdf::build_pdf_with_page_size(&jpegs, SLIDE_WIDTH_PT, SLIDE_HEIGHT_PT)?; + super::report(progress, progress_id, "done", total, Some(total), None); + Ok(pdf) +} + +/// Extrae el primer número de un nombre de archivo para ordenamiento natural +/// (`diapositiva_1.svg`, `diapositiva_2.svg`, ..., `diapositiva_10.svg`). +pub fn extraer_numero_slide(nombre: &str) -> usize { + static NUM_RE: OnceLock = OnceLock::new(); + let re = NUM_RE.get_or_init(|| Regex::new(r"(\d+)").unwrap()); + re.captures(nombre) + .and_then(|cap| cap.get(1)) + .and_then(|m| m.as_str().parse::().ok()) + .unwrap_or(0) +} + +/// Lista todos los archivos `.svg` de un directorio en orden numérico natural. +pub fn obtener_svgs_ordenados(directorio: &Path) -> anyhow::Result> { + let mut entradas: Vec = std::fs::read_dir(directorio) + .with_context(|| format!("No se pudo leer el directorio {}", directorio.display()))? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| { + p.extension() + .map(|ext| ext.eq_ignore_ascii_case("svg")) + .unwrap_or(false) + }) + .collect(); + + entradas.sort_by(|a, b| { + let na = a.file_name().unwrap_or_default().to_string_lossy(); + let nb = b.file_name().unwrap_or_default().to_string_lossy(); + extraer_numero_slide(&na) + .cmp(&extraer_numero_slide(&nb)) + .then_with(|| na.cmp(&nb)) + }); + + Ok(entradas) +} + +/// Compila todos los archivos `.svg` de una carpeta local en un PDF 16:9 (`1280 x 720 pt`). +pub async fn compile_svg_dir_to_pdf( + svg_dir: &str, + output_pdf: Option<&str>, + progress: super::ProgressFn, +) -> anyhow::Result { + let dir_path = PathBuf::from(svg_dir); + let paths = obtener_svgs_ordenados(&dir_path)?; + if paths.is_empty() { + return Err(anyhow!( + "No se encontraron archivos .svg en {}", + dir_path.display() + )); + } + + let mut svgs = Vec::with_capacity(paths.len()); + for p in &paths { + let content = tokio::fs::read_to_string(p) + .await + .with_context(|| format!("Error leyendo {}", p.display()))?; + svgs.push(content); + } + + let progress_id = format!("gslides-dir:{}", svg_dir); + if let Ok(client) = build_google_client(None) { + embed_remote_images_base64(&client, &mut svgs, &progress, &progress_id).await; + } + + let dir_title = dir_path + .file_name() + .map(|s| s.to_string_lossy().to_string()) + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| "presentacion_compilada".to_string()); + + let out_path = match output_pdf.map(str::trim).filter(|s| !s.is_empty()) { + Some(custom) => { + let p = PathBuf::from(custom); + if p.is_dir() { + p.join(format!("{}.pdf", super::sanitize_name(&dir_title))) + } else if p.extension().map(|e| e.eq_ignore_ascii_case("pdf")).unwrap_or(false) { + p + } else { + p.with_extension("pdf") + } + } + None => dir_path.join(format!("{}.pdf", super::sanitize_name(&dir_title))), + }; + + if let Some(parent) = out_path.parent() { + std::fs::create_dir_all(parent)?; + } + + let svgs_for_compile = svgs; + let progress_clone = progress.clone(); + let pid = progress_id.clone(); + let pdf_bytes = tokio::task::spawn_blocking(move || { + compile_svgs_to_pdf(&svgs_for_compile, &progress_clone, &pid) + }) + .await??; + + tokio::fs::write(&out_path, &pdf_bytes).await?; + + Ok(GslidesDownloadResult { + title: dir_title, + pages: paths.len(), + output_path: out_path.to_string_lossy().to_string(), + format: "pdf".to_string(), + }) +} + +pub fn build_google_client(url_hint: Option<&str>) -> anyhow::Result { + use reqwest::header::{HeaderMap, HeaderValue, USER_AGENT}; + let mut headers = HeaderMap::new(); + headers.insert( + USER_AGENT, + HeaderValue::from_static( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", + ), + ); + let mut builder = crate::core::http_client::apply_global_proxy(reqwest::Client::builder()) + .default_headers(headers) + .timeout(std::time::Duration::from_secs(600)); + + let probe_url = url_hint.unwrap_or("https://docs.google.com/presentation/"); + if let Some(jar) = crate::core::cookie_parser::load_extension_cookies_for_url(probe_url) { + builder = builder.cookie_provider(jar); + } + Ok(builder.build()?) +} + +/// Descarga y extrae las diapositivas de una presentación de Google Slides desde su visor +/// (`pubembed` / `embed` / `htmlpresent`), incrusta sus imágenes en Base64 y genera el +/// PDF 16:9 (`format == "pdf"`) o una carpeta con los `.svg` autocontenidos (`format == "svg"`). +pub async fn download_presentation( + url: &str, + format: &str, + dest_dir: &str, + progress: super::ProgressFn, +) -> anyhow::Result { + let target = parse_gslides_url(url).ok_or_else(|| { + anyhow!("Enlace de Google Slides no válido: {}", url) + })?; + + let client = build_google_client(Some(url))?; + let progress_id = format!("gslides:{}", target.id); + + super::report( + &progress, + &progress_id, + "fetch", + 0, + None, + Some("Obteniendo visor de Google Slides...".to_string()), + ); + + let mut html = String::new(); + for candidate in [target.viewer_url(), target.htmlpresent_url()] { + if let Ok(resp) = client.get(&candidate).send().await { + if resp.status().is_success() { + if let Ok(text) = resp.text().await { + if text.contains("SK_svgData") { + html = text; + break; + } + } + } + } + } + + if html.is_empty() { + return Err(anyhow!( + "No se encontraron diapositivas vectoriales en la presentación (puede requerir inicio de sesión o usar el extractor en navegador)." + )); + } + + let mut extracted = extract_viewer_slides(&html); + drop(html); + + if extracted.svgs.is_empty() { + return Err(anyhow!( + "No se encontraron bloques SK_svgData en la presentación." + )); + } + + let pages = extracted.svgs.len(); + embed_remote_images_base64(&client, &mut extracted.svgs, &progress, &progress_id).await; + + let safe_title = super::sanitize_name(&extracted.title); + let base_dir = PathBuf::from(dest_dir); + std::fs::create_dir_all(&base_dir)?; + + if format.eq_ignore_ascii_case("svg") { + let folder = base_dir.join(&safe_title); + std::fs::create_dir_all(&folder)?; + for (i, svg) in extracted.svgs.iter().enumerate() { + let file_path = folder.join(format!("diapositiva_{:03}.svg", i + 1)); + tokio::fs::write(&file_path, svg.as_bytes()).await?; + } + super::report( + &progress, + &progress_id, + "done", + pages as u64, + Some(pages as u64), + None, + ); + return Ok(GslidesDownloadResult { + title: extracted.title, + pages, + output_path: folder.to_string_lossy().to_string(), + format: "svg".to_string(), + }); + } + + let svgs = extracted.svgs; + let progress_clone = progress.clone(); + let pid = progress_id.clone(); + let pdf_bytes = tokio::task::spawn_blocking(move || { + compile_svgs_to_pdf(&svgs, &progress_clone, &pid) + }) + .await??; + + let pdf_path = base_dir.join(format!("{}.pdf", safe_title)); + tokio::fs::write(&pdf_path, &pdf_bytes).await?; + + Ok(GslidesDownloadResult { + title: extracted.title, + pages, + output_path: pdf_path.to_string_lossy().to_string(), + format: "pdf".to_string(), + }) +} + +/// Genera el script JavaScript / Bookmarklet adaptado para enviar diapositivas al +/// `local_bridge` de OmniGet en `http://127.0.0.1:/api`. +pub fn browser_extractor_script(port: u16) -> String { + let tpl = r##"javascript:(function(){ + const SERVER_URL = "http://127.0.0.1:__PORT__/api"; + let count = 1; + let lastSvgSignature = ""; + let duplicateCount = 0; + const deckTitle = (document.title || "presentacion_google_slides").replace(/\s*-\s*(Presentaciones de Google|Google Slides|Apresentações Google).*$/i, "").trim(); + + fetch(`${SERVER_URL}/reset`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ title: deckTitle }) + }); + + let btn = document.createElement("button"); + btn.textContent = "⏳ Enviando slides a OmniGet..."; + btn.style.cssText = "position:fixed;top:20px;right:20px;z-index:999999;padding:14px 22px;background:#4f46e5;color:white;font-weight:bold;border:none;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.35);font-family:system-ui,sans-serif;"; + document.body.appendChild(btn); + + async function svgImageToBase64(svgElement) { + let images = svgElement.querySelectorAll("image"); + for (let img of images) { + let href = img.getAttribute("xlink:href") || img.getAttribute("href"); + if (href && href.startsWith("http")) { + try { + let res = await fetch(href); + let blob = await res.blob(); + let base64 = await new Promise(resolve => { + let reader = new FileReader(); + reader.onloadend = () => resolve(reader.result); + reader.readAsDataURL(blob); + }); + img.setAttribute("xlink:href", base64); + if (img.hasAttribute("href")) img.setAttribute("href", base64); + } catch (e) { + console.warn("Fallo CORS en imagen:", href); + } + } + } + } + + function advance() { + let nextBtn = document.querySelector('[aria-label="Siguiente"]') || + document.querySelector('[aria-label="Next"]') || + document.querySelector('[aria-label="Próximo"]') || + document.querySelector('.punch-viewer-nav-next'); + if (nextBtn) { + nextBtn.click(); + } else { + let target = document.querySelector('.punch-viewer-content') || document.body; + target.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', keyCode: 39, bubbles: true })); + } + } + + async function stepCapture() { + let svgs = document.querySelectorAll("svg"); + let target = null; + svgs.forEach(s => { + let vb = s.getAttribute("viewBox"); + if (vb && vb.includes("1280") && vb.includes("720")) target = s; + }); + if (!target && svgs.length > 0) target = svgs[0]; + + if (target) { + let sig = target.innerHTML; + if (sig === lastSvgSignature && count > 1) { + if (++duplicateCount >= 2) { + btn.textContent = "⚙️ Compilando PDF 16:9 en OmniGet..."; + let r = await fetch(`${SERVER_URL}/compile`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ title: deckTitle }) + }); + let j = await r.json().catch(() => ({})); + btn.textContent = j.file ? `✅ PDF guardado: ${j.file}` : "✅ ¡PDF generado en OmniGet!"; + btn.style.background = "#10b981"; + setTimeout(() => btn.remove(), 6000); + return; + } + } else { + duplicateCount = 0; + lastSvgSignature = sig; + } + + let clone = target.cloneNode(true); + clone.setAttribute("width", "1280px"); + clone.setAttribute("height", "720px"); + clone.setAttribute("viewBox", "0 0 1280 720"); + + await svgImageToBase64(clone); + + let xml = new XMLSerializer().serializeToString(clone); + await fetch(`${SERVER_URL}/slide`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ index: count++, svg_content: xml, title: deckTitle }) + }); + + btn.textContent = `🚀 Enviado slide ${count - 1} a OmniGet...`; + } + + advance(); + setTimeout(stepCapture, 1800); + } + + setTimeout(stepCapture, 1200); +})();"##; + tpl.replace("__PORT__", &port.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_published_and_standard_urls() { + let pub_url = "https://docs.google.com/presentation/d/e/2PACX-1vMockDummyId1234567890abcdefghijklmnopqrstuvwxyz/pubembed?start=false&loop=false&delayms=3000&slide=id.p1"; + let t1 = parse_gslides_url(pub_url).unwrap(); + assert!(t1.is_published); + assert_eq!( + t1.id, + "2PACX-1vMockDummyId1234567890abcdefghijklmnopqrstuvwxyz" + ); + + let std_url = "https://docs.google.com/presentation/d/1AbC_d-e/edit#slide=id.p1"; + let t2 = parse_gslides_url(std_url).unwrap(); + assert!(!t2.is_published); + assert_eq!(t2.id, "1AbC_d-e"); + } + + #[test] + fn unescapes_sk_svg_data_and_extracts_slides() { + let sample_html = r#" + + + + "#; + let extracted = extract_viewer_slides(sample_html); + assert_eq!(extracted.title, "Sample Presentation Deck"); + assert_eq!(extracted.svgs.len(), 2); + assert!(extracted.svgs[0].contains(r#"width="1280px" height="720px""#)); + + let pdf = compile_svgs_to_pdf(&extracted.svgs, &super::super::noop_progress(), "test") + .expect("should compile valid 16:9 PDF"); + let pdf_str = String::from_utf8_lossy(&pdf); + assert!(pdf_str.starts_with("%PDF-1.4")); + assert!(pdf_str.contains("/Count 2")); + assert!(pdf_str.contains("/MediaBox [0 0 1280 720]")); + } + + #[test] + fn natural_slide_number_sorting() { + assert_eq!(extraer_numero_slide("diapositiva_1.svg"), 1); + assert_eq!(extraer_numero_slide("diapositiva_10.svg"), 10); + assert_eq!(extraer_numero_slide("slide_2.svg"), 2); + } +} diff --git a/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs b/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs index 7d100baf..60257965 100644 --- a/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs +++ b/src-tauri/omniget-core/src/core/tools/jpeg_pdf.rs @@ -54,6 +54,24 @@ pub fn is_jpeg(data: &[u8]) -> bool { /// Monta o PDF em memória. Página no tamanho da imagem em pontos (72 dpi). pub fn build_pdf(images: &[Vec]) -> anyhow::Result> { + build_pdf_inner(images, None) +} + +/// Monta o PDF em memória fixando o tamanho físico de cada página em pontos +/// (ex.: `1280.0 x 720.0` para apresentações 16:9), independentemente da +/// resolução em pixels do JPEG embutido. +pub fn build_pdf_with_page_size( + images: &[Vec], + page_width_pt: f64, + page_height_pt: f64, +) -> anyhow::Result> { + build_pdf_inner(images, Some((page_width_pt, page_height_pt))) +} + +fn build_pdf_inner( + images: &[Vec], + fixed_page_pt: Option<(f64, f64)>, +) -> anyhow::Result> { if images.is_empty() { return Err(anyhow!("nenhuma imagem")); } @@ -98,15 +116,18 @@ pub fn build_pdf(images: &[Vec]) -> anyhow::Result> { 4 => "/DeviceCMYK", _ => "/DeviceRGB", }; - let (w, h) = (info.width.max(1), info.height.max(1)); + let (img_w, img_h) = (info.width.max(1), info.height.max(1)); + let (page_w, page_h) = fixed_page_pt + .map(|(pw, ph)| (pw.max(1.0), ph.max(1.0))) + .unwrap_or((img_w as f64, img_h as f64)); push_obj( &mut out, &mut offsets, format!( "{} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /XObject << /Im0 {} 0 R >> >> /Contents {} 0 R >>\nendobj\n", obj_page(i), - w, - h, + page_w, + page_h, obj_img(i), obj_content(i) ) @@ -115,8 +136,8 @@ pub fn build_pdf(images: &[Vec]) -> anyhow::Result> { let mut xobj = format!( "{} 0 obj\n<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace {} /BitsPerComponent 8 /Filter /DCTDecode /Length {} >>\nstream\n", obj_img(i), - w, - h, + img_w, + img_h, cs, img.len() ) @@ -124,7 +145,7 @@ pub fn build_pdf(images: &[Vec]) -> anyhow::Result> { xobj.extend_from_slice(img); xobj.extend_from_slice(b"\nendstream\nendobj\n"); push_obj(&mut out, &mut offsets, &xobj); - let content = format!("q {} 0 0 {} 0 0 cm /Im0 Do Q", w, h); + let content = format!("q {} 0 0 {} 0 0 cm /Im0 Do Q", page_w, page_h); push_obj( &mut out, &mut offsets, diff --git a/src-tauri/omniget-core/src/core/tools/mod.rs b/src-tauri/omniget-core/src/core/tools/mod.rs index e0fbffd7..445575c2 100644 --- a/src-tauri/omniget-core/src/core/tools/mod.rs +++ b/src-tauri/omniget-core/src/core/tools/mod.rs @@ -23,6 +23,7 @@ pub mod gallery; pub mod games; pub mod gdocs; pub mod github; +pub mod gslides; pub mod hosts_block; pub mod humanize; pub mod icon_pack; diff --git a/src-tauri/omniget-core/src/platforms/gdocs.rs b/src-tauri/omniget-core/src/platforms/gdocs.rs new file mode 100644 index 00000000..a56ed4f6 --- /dev/null +++ b/src-tauri/omniget-core/src/platforms/gdocs.rs @@ -0,0 +1,188 @@ +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::anyhow; +use async_trait::async_trait; +use tokio::sync::mpsc; + +use crate::core::tools::{gdocs, gslides, ToolProgress}; +use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality}; +use crate::models::progress::ProgressUpdate; +use crate::platforms::traits::PlatformDownloader; + +pub struct GdocsDownloader; + +impl Default for GdocsDownloader { + fn default() -> Self { + Self::new() + } +} + +impl GdocsDownloader { + pub fn new() -> Self { + Self + } +} + +async fn fetch_presentation_title(url: &str) -> Option { + let target = gslides::parse_gslides_url(url)?; + let client = gslides::build_google_client(Some(url)).ok()?; + let resp = tokio::time::timeout( + std::time::Duration::from_secs(12), + client.get(target.viewer_url()).send(), + ) + .await + .ok()? + .ok()?; + if !resp.status().is_success() { + return None; + } + // Leer los primeros ~256 KB basta para extraer `` o `viewerData.title` + use futures::StreamExt; + let mut stream = resp.bytes_stream(); + let mut buf = Vec::with_capacity(262_144); + while let Some(Ok(chunk)) = stream.next().await { + buf.extend_from_slice(&chunk); + if buf.len() >= 262_144 { + break; + } + } + let html = String::from_utf8_lossy(&buf); + let title = gslides::extract_title_from_viewer_html(&html); + if title == "presentacion_google_slides" { + None + } else { + Some(title) + } +} + +fn compute_path_size(path: & std::path::Path) -> u64 { + if let Ok(meta) = std::fs::metadata(path) { + if meta.is_file() { + return meta.len(); + } + if meta.is_dir() { + return walkdir::WalkDir::new(path) + .into_iter() + .filter_map(|e| e.ok()) + .filter_map(|e| e.metadata().ok()) + .filter(|m| m.is_file()) + .map(|m| m.len()) + .sum(); + } + } + 0 +} + +#[async_trait] +impl PlatformDownloader for GdocsDownloader { + fn name(&self) -> &str { + "gdocs" + } + + fn can_handle(&self, url: &str) -> bool { + gdocs::parse(url).is_some() + } + + async fn get_media_info(&self, url: &str) -> anyhow::Result { + let parsed = gdocs::parse(url) + .ok_or_else(|| anyhow!("Enlace de Google Docs/Slides no válido"))?; + + let title = if parsed.kind == "presentation" { + fetch_presentation_title(url).await.unwrap_or_else(|| { + format!( + "Google Slides ({})", + &parsed.id[..parsed.id.len().min(12)] + ) + }) + } else { + format!( + "Google {} ({})", + parsed.kind, + &parsed.id[..parsed.id.len().min(12)] + ) + }; + + let qualities: Vec = parsed + .formats + .iter() + .map(|fmt| VideoQuality { + label: fmt.to_uppercase(), + width: if parsed.kind == "presentation" { 1280 } else { 0 }, + height: if parsed.kind == "presentation" { 720 } else { 0 }, + url: url.to_string(), + format: fmt.clone(), + }) + .collect(); + + Ok(MediaInfo { + title, + author: "Google Docs".to_string(), + platform: "gdocs".to_string(), + duration_seconds: None, + thumbnail_url: None, + available_qualities: qualities, + media_type: MediaType::File, + file_size_bytes: None, + }) + } + + async fn download( + &self, + info: &MediaInfo, + opts: &DownloadOptions, + progress: mpsc::Sender, + ) -> anyhow::Result { + let start = std::time::Instant::now(); + let _ = progress.send(ProgressUpdate::percent(1.0)).await; + + let target_url = opts + .page_url + .as_deref() + .or_else(|| info.available_qualities.first().map(|q| q.url.as_str())) + .ok_or_else(|| anyhow!("No hay URL disponible para Google Docs/Slides"))?; + + let parsed = gdocs::parse(target_url) + .ok_or_else(|| anyhow!("Enlace de Google Docs/Slides no válido"))?; + + let requested_format = opts + .format_id + .as_deref() + .or(opts.quality.as_deref()) + .map(|s| s.to_ascii_lowercase()) + .filter(|f| parsed.formats.iter().any(|pf| pf == f)) + .unwrap_or_else(|| "pdf".to_string()); + + let dest_dir = opts.output_dir.to_string_lossy().to_string(); + let tx = progress.clone(); + let tool_progress: crate::core::tools::ProgressFn = Arc::new(move |tp: ToolProgress| { + let pct = match (tp.stage.as_str(), tp.total) { + ("fetch", _) => 5.0, + ("images", Some(t)) if t > 0 => { + 5.0 + ((tp.done as f64 / t as f64) * 45.0).clamp(0.0, 45.0) + } + ("compile", Some(t)) if t > 0 => { + 50.0 + ((tp.done as f64 / t as f64) * 48.0).clamp(0.0, 48.0) + } + ("done", _) => 100.0, + (_, Some(t)) if t > 0 => ((tp.done as f64 / t as f64) * 95.0).clamp(0.0, 95.0), + _ => 10.0, + }; + let _ = tx.try_send(ProgressUpdate::percent(pct)); + }); + + let out_path_str = + gdocs::download(target_url, &requested_format, &dest_dir, tool_progress).await?; + let out_path = PathBuf::from(&out_path_str); + let size = compute_path_size(&out_path); + + let _ = progress.send(ProgressUpdate::percent(100.0)).await; + + Ok(DownloadResult { + file_path: out_path, + file_size_bytes: size, + duration_seconds: start.elapsed().as_secs_f64(), + torrent_id: None, + }) + } +} diff --git a/src-tauri/omniget-core/src/platforms/mod.rs b/src-tauri/omniget-core/src/platforms/mod.rs index 64fd7bd9..41c5412d 100644 --- a/src-tauri/omniget-core/src/platforms/mod.rs +++ b/src-tauri/omniget-core/src/platforms/mod.rs @@ -3,6 +3,7 @@ pub mod bluesky; pub mod cookie_provider; pub mod direct_file; pub mod douyin; +pub mod gdocs; pub mod generic_ytdlp; pub mod instagram; pub mod p2p; @@ -21,6 +22,7 @@ pub use bilibili::BilibiliDownloader; pub use bluesky::BlueskyDownloader; pub use direct_file::DirectFileDownloader; pub use douyin::DouyinDownloader; +pub use gdocs::GdocsDownloader; pub use generic_ytdlp::GenericYtdlpDownloader; pub use instagram::InstagramDownloader; pub use p2p::P2pDownloader; @@ -210,6 +212,10 @@ impl Platform { Some(Platform::Other("mgtv".to_string())) } else if matches("youku.com") { Some(Platform::Other("youku".to_string())) + } else if host == "docs.google.com" + && crate::core::tools::gdocs::parse(url_str).is_some() + { + Some(Platform::Other("gdocs".to_string())) } else if is_direct_file_url(url_str) { Some(Platform::Other("direct_file".to_string())) } else { diff --git a/src-tauri/src/commands/tools/documents.rs b/src-tauri/src/commands/tools/documents.rs index 5ab31020..40cb8036 100644 --- a/src-tauri/src/commands/tools/documents.rs +++ b/src-tauri/src/commands/tools/documents.rs @@ -1,4 +1,4 @@ -use omniget_core::core::tools::{calameo, gallery, gdocs, slides}; +use omniget_core::core::tools::{calameo, gallery, gdocs, gslides, slides}; use super::{err, progress}; @@ -30,6 +30,22 @@ pub async fn tool_gdocs_download( .map_err(err) } +#[tauri::command] +pub async fn tool_gslides_compile_dir( + app: tauri::AppHandle, + svg_dir: String, + output_pdf: Option, +) -> Result { + gslides::compile_svg_dir_to_pdf(&svg_dir, output_pdf.as_deref(), progress(&app)) + .await + .map_err(err) +} + +#[tauri::command] +pub fn tool_gslides_bridge_info() -> crate::local_bridge::SlidesBridgeStatus { + crate::local_bridge::slides_bridge_status() +} + #[tauri::command] pub async fn tool_calameo( app: tauri::AppHandle, diff --git a/src-tauri/src/core/url_parser.rs b/src-tauri/src/core/url_parser.rs index 88648462..1357cfc6 100644 --- a/src-tauri/src/core/url_parser.rs +++ b/src-tauri/src/core/url_parser.rs @@ -48,6 +48,13 @@ pub fn parse_url(url_str: &str) -> Option { "douyin" => parse_douyin(&segments), "tencentvideo" => parse_tencent(&segments), "xiaohongshu" => parse_xiaohongshu(&segments), + "gdocs" => { + if let Some(info) = omniget_core::core::tools::gdocs::parse(url_str) { + (Some(info.id), ParsedContentType::Post) + } else { + (None, ParsedContentType::Unknown) + } + } _ => (None, ParsedContentType::Unknown), }, }; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index da183bb5..d52d11fb 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -244,6 +244,7 @@ pub fn run() { torrent_session.clone(), ))); registry.register(Arc::new(omniget_core::platforms::P2pDownloader::new())); + registry.register(Arc::new(omniget_core::platforms::GdocsDownloader::new())); registry.register(Arc::new( omniget_core::platforms::DirectFileDownloader::new(), )); @@ -1003,6 +1004,8 @@ pub fn run() { commands::tools::documents::tool_slideshare, commands::tools::documents::tool_gdocs_parse, commands::tools::documents::tool_gdocs_download, + commands::tools::documents::tool_gslides_compile_dir, + commands::tools::documents::tool_gslides_bridge_info, commands::tools::documents::tool_calameo, commands::tools::documents::tool_gallery_status, commands::tools::documents::tool_gallery_install, diff --git a/src-tauri/src/local_bridge.rs b/src-tauri/src/local_bridge.rs index 84e63090..1c2cf828 100644 --- a/src-tauri/src/local_bridge.rs +++ b/src-tauri/src/local_bridge.rs @@ -517,6 +517,12 @@ pub async fn spawn(app: AppHandle) { .route("/v1/log/{id}", get(download_log)) .route("/v1/cookies", post(cookies_export)) .route("/mcp", post(mcp_post).get(mcp_get).delete(mcp_get)) + .route("/api/reset", post(slides_reset)) + .route( + "/api/slide", + post(slides_receive).layer(DefaultBodyLimit::max(32 * 1024 * 1024)), + ) + .route("/api/compile", post(slides_compile)) .with_state(state) .layer(cors); @@ -912,6 +918,201 @@ async fn mcp_get() -> Response { StatusCode::METHOD_NOT_ALLOWED.into_response() } +// ── Receptor local de diapositivas Google Slides (/api/reset, /api/slide, /api/compile) ── + +#[derive(Default)] +struct SlidesSession { + title: Option, + slides: Vec<(usize, String)>, + last_output: Option, +} + +static SLIDES_BUFFER: OnceLock> = OnceLock::new(); + +fn slides_buffer() -> &'static Mutex { + SLIDES_BUFFER.get_or_init(|| Mutex::new(SlidesSession::default())) +} + +#[derive(Debug, Clone, Serialize)] +pub struct SlidesBridgeStatus { + pub port: u16, + pub slide_count: usize, + pub last_output: Option, + pub script: String, +} + +pub fn slides_bridge_status() -> SlidesBridgeStatus { + let port = BOUND_PORT.load(Ordering::SeqCst); + let effective_port = if port == 0 { 47720 } else { port }; + let (slide_count, last_output) = slides_buffer() + .lock() + .ok() + .map(|s| (s.slides.len(), s.last_output.clone())) + .unwrap_or((0, None)); + SlidesBridgeStatus { + port: effective_port, + slide_count, + last_output, + script: omniget_core::core::tools::gslides::browser_extractor_script(effective_port), + } +} + +#[derive(Debug, Deserialize, Default)] +struct SlideResetBody { + #[serde(default)] + title: Option, +} + +#[derive(Debug, Deserialize)] +struct SlideReceiveBody { + index: usize, + svg_content: String, + #[serde(default)] + title: Option, +} + +async fn slides_reset( + State(state): State, + body: Option>, +) -> Response { + if let Ok(mut guard) = slides_buffer().lock() { + guard.slides.clear(); + guard.title = body.and_then(|b| b.0.title).filter(|t| !t.trim().is_empty()); + } + let _ = state.app.emit( + "gslides-bridge-progress", + serde_json::json!({ "slide_count": 0 }), + ); + ( + StatusCode::OK, + Json(serde_json::json!({ "status": "reset_successful" })), + ) + .into_response() +} + +async fn slides_receive( + State(state): State, + Json(data): Json, +) -> Response { + let count = if let Ok(mut guard) = slides_buffer().lock() { + if let Some(t) = data.title.filter(|t| !t.trim().is_empty()) { + guard.title = Some(t); + } + if let Some(existing) = guard.slides.iter_mut().find(|(idx, _)| *idx == data.index) { + existing.1 = data.svg_content; + } else { + guard.slides.push((data.index, data.svg_content)); + } + guard.slides.len() + } else { + 0 + }; + let _ = state.app.emit( + "gslides-bridge-progress", + serde_json::json!({ "slide_count": count, "index": data.index }), + ); + ( + StatusCode::OK, + Json(serde_json::json!({ "status": "ok", "slide_count": count })), + ) + .into_response() +} + +async fn slides_compile( + State(state): State, + body: Option>, +) -> Response { + let (mut indexed_svgs, title) = match slides_buffer().lock() { + Ok(mut guard) => { + if let Some(t) = body.and_then(|b| b.0.title).filter(|t| !t.trim().is_empty()) { + guard.title = Some(t); + } + ( + guard.slides.clone(), + guard + .title + .clone() + .unwrap_or_else(|| "presentacion_compilada".to_string()), + ) + } + Err(_) => (Vec::new(), "presentacion_compilada".to_string()), + }; + + if indexed_svgs.is_empty() { + return ( + StatusCode::BAD_REQUEST, + Json(serde_json::json!({ "status": "error", "detail": "No hay diapositivas acumuladas." })), + ) + .into_response(); + } + + indexed_svgs.sort_by_key(|(idx, _)| *idx); + let svgs: Vec = indexed_svgs.into_iter().map(|(_, s)| s).collect(); + let pages = svgs.len(); + + let settings = config::load_settings(&state.app); + let out_dir = if !settings.download.default_output_dir.as_os_str().is_empty() { + settings.download.default_output_dir.clone() + } else { + dirs::download_dir().unwrap_or_else(|| PathBuf::from(".")) + }; + let _ = std::fs::create_dir_all(&out_dir); + let safe_title = omniget_core::core::tools::sanitize_name(&title); + let out_file = out_dir.join(format!("{}.pdf", safe_title)); + + let compile_res = tokio::task::spawn_blocking(move || { + omniget_core::core::tools::gslides::compile_svgs_to_pdf( + &svgs, + &omniget_core::core::tools::noop_progress(), + "bridge-compile", + ) + }) + .await; + + let pdf_bytes = match compile_res { + Ok(Ok(b)) => b, + Ok(Err(e)) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "status": "error", "detail": e.to_string() })), + ) + .into_response(); + } + Err(e) => { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "status": "error", "detail": e.to_string() })), + ) + .into_response(); + } + }; + + if let Err(e) = tokio::fs::write(&out_file, &pdf_bytes).await { + return ( + StatusCode::INTERNAL_SERVER_ERROR, + Json(serde_json::json!({ "status": "error", "detail": e.to_string() })), + ) + .into_response(); + } + + let file_str = out_file.to_string_lossy().to_string(); + if let Ok(mut guard) = slides_buffer().lock() { + guard.last_output = Some(file_str.clone()); + guard.slides.clear(); + } + + let _ = state.app.emit( + "gslides-bridge-complete", + serde_json::json!({ "file": file_str, "pages": pages }), + ); + + ( + StatusCode::OK, + Json(serde_json::json!({ "status": "success", "file": file_str, "pages": pages })), + ) + .into_response() +} + #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rs index 7329b5ec..78ee8534 100644 --- a/src-tauri/src/platforms/mod.rs +++ b/src-tauri/src/platforms/mod.rs @@ -3,6 +3,7 @@ pub use omniget_core::platforms::traits; pub use omniget_core::platforms::BlueskyDownloader; pub use omniget_core::platforms::DirectFileDownloader; pub use omniget_core::platforms::DouyinDownloader; +pub use omniget_core::platforms::GdocsDownloader; pub use omniget_core::platforms::GenericYtdlpDownloader; pub use omniget_core::platforms::InstagramDownloader; pub use omniget_core::platforms::P2pDownloader; diff --git a/src/components/icons/PlatformIcon.svelte b/src/components/icons/PlatformIcon.svelte index 4b43d958..e9278118 100644 --- a/src/components/icons/PlatformIcon.svelte +++ b/src/components/icons/PlatformIcon.svelte @@ -95,6 +95,12 @@ +{:else if platform === "gdocs"} + + + + + {:else if platform === "generic"} diff --git a/src/components/tools/documents/GdocsTool.svelte b/src/components/tools/documents/GdocsTool.svelte index 077a88c5..5c1b6a4b 100644 --- a/src/components/tools/documents/GdocsTool.svelte +++ b/src/components/tools/documents/GdocsTool.svelte @@ -1,32 +1,132 @@ @@ -34,7 +134,7 @@
-
(info = null)} placeholder="https://docs.google.com/presentation/d/…" onkeydown={(e) => e.key === "Enter" && parse()} />
+
(info = null)} placeholder="https://docs.google.com/presentation/d/…" onkeydown={(e) => e.key === "Enter" && run()} />
{#if info} @@ -48,14 +148,53 @@
-
{$t("tools.gdocs.note")}
-
+
+ {#if busy || compilingSvgDir} +
{progress?.message ?? (progress ? `${progress.done}/${progress.total ?? "?"}` : "…")}
+
+ {:else} +
{$t("tools.gdocs.note")}
+ {/if} +
+
+ +
+
+
+
+
SVG → PDF (16:9)
+
{svgDir || $t("tools.common.ask_on_run")}
+
+
+ + +
+
+ {#if bridgeInfo} +
+
+
Bookmarklet / JS ({`127.0.0.1:${bridgeInfo.port}`})
+
{bridgeSlidesCount > 0 ? `${bridgeSlidesCount} slides en buffer` : "Extractor para consola o marcador del navegador"}
+
+
+ +
+
+ {/if} +
+
+ {#if out}
-
{out}
+
+ {#if compiledResult} +
{compiledResult.title} · {compiledResult.pages} slides
+ {/if} +
{out}
+
{/if} diff --git a/src/lib/platform-display-names.ts b/src/lib/platform-display-names.ts index 5484a5a8..2bb5661b 100644 --- a/src/lib/platform-display-names.ts +++ b/src/lib/platform-display-names.ts @@ -22,6 +22,7 @@ export const PLATFORM_DISPLAY_NAMES: Record = { metaanalysis: "Meta-Analysis Academy", magnet: "BitTorrent", p2p: "P2P", + gdocs: "Google Docs / Slides", direct_file: "Direct file", }; From 791e7e1214d1cb974d36e6037c021742e4b5812f Mon Sep 17 00:00:00 2001 From: Mad0 Date: Tue, 10 Nov 2026 19:16:58 -0600 Subject: [PATCH 2/3] sec(bridge): authenticate slides endpoints with Bearer token, validate pair origins, and verify Deno sha256 --- src-tauri/omniget-cli/src/commands/common.rs | 6 +- .../omniget-core/src/core/dependencies.rs | 6 ++ .../omniget-core/src/core/tools/gdocs.rs | 3 +- .../omniget-core/src/core/tools/gslides.rs | 78 +++++++++---------- src-tauri/omniget-core/src/platforms/gdocs.rs | 23 +++--- src-tauri/omniget-core/src/platforms/mod.rs | 4 +- src-tauri/src/local_bridge.rs | 59 ++++++++++++-- 7 files changed, 116 insertions(+), 63 deletions(-) diff --git a/src-tauri/omniget-cli/src/commands/common.rs b/src-tauri/omniget-cli/src/commands/common.rs index c87ab7b4..099ec709 100644 --- a/src-tauri/omniget-cli/src/commands/common.rs +++ b/src-tauri/omniget-cli/src/commands/common.rs @@ -8,9 +8,9 @@ use omniget_core::core::ytdlp; use omniget_core::models::media::{DownloadOptions, MediaInfo}; use omniget_core::models::settings::ProxySettings; use omniget_core::platforms::{ - BilibiliDownloader, BlueskyDownloader, DirectFileDownloader, DouyinDownloader, - GdocsDownloader, GenericYtdlpDownloader, InstagramDownloader, P2pDownloader, - PinterestDownloader, PlatformDownloader, RedditDownloader, ThreadsDownloader, TikTokDownloader, + BilibiliDownloader, BlueskyDownloader, DirectFileDownloader, DouyinDownloader, GdocsDownloader, + GenericYtdlpDownloader, InstagramDownloader, P2pDownloader, PinterestDownloader, + PlatformDownloader, RedditDownloader, ThreadsDownloader, TikTokDownloader, TwitchClipsDownloader, TwitterDownloader, VimeoDownloader, YouTubeDownloader, }; use tokio_util::sync::CancellationToken; diff --git a/src-tauri/omniget-core/src/core/dependencies.rs b/src-tauri/omniget-core/src/core/dependencies.rs index ab982701..1ceca57d 100644 --- a/src-tauri/omniget-core/src/core/dependencies.rs +++ b/src-tauri/omniget-core/src/core/dependencies.rs @@ -774,10 +774,15 @@ async fn download_deno() -> anyhow::Result { tracing::info!("Downloading Deno JS runtime from {}", url); + let asset_name = url.rsplit('/').next().unwrap_or("deno.zip"); + let sums_url = format!("{url}.sha256sum"); + let client = crate::core::http_client::apply_global_proxy(reqwest::Client::builder()) .timeout(std::time::Duration::from_secs(300)) .build()?; + let expected_sha256 = integrity::expected_from_sums_url(&client, &sums_url, asset_name).await?; + let response = client.get(url).send().await?; if !response.status().is_success() { return Err(anyhow!( @@ -787,6 +792,7 @@ async fn download_deno() -> anyhow::Result { } let bytes = response.bytes().await?; + integrity::verify_sha256(&bytes, &expected_sha256, "deno")?; let data = bytes.to_vec(); let bin_dir_clone = bin_dir.clone(); let deno_name_clone = deno_name.clone(); diff --git a/src-tauri/omniget-core/src/core/tools/gdocs.rs b/src-tauri/omniget-core/src/core/tools/gdocs.rs index 4faeb9d5..9c1e5baa 100644 --- a/src-tauri/omniget-core/src/core/tools/gdocs.rs +++ b/src-tauri/omniget-core/src/core/tools/gdocs.rs @@ -110,7 +110,8 @@ pub async fn download( .map(|ct| ct.to_ascii_lowercase().starts_with("text/html") && format != "html") .unwrap_or(false); - if (!status.is_success() || is_html_redirect) && info.kind == "presentation" && format == "pdf" { + if (!status.is_success() || is_html_redirect) && info.kind == "presentation" && format == "pdf" + { if let Ok(res) = super::gslides::download_presentation(url, "pdf", dest_dir, progress.clone()).await { diff --git a/src-tauri/omniget-core/src/core/tools/gslides.rs b/src-tauri/omniget-core/src/core/tools/gslides.rs index d1e6b238..01a00286 100644 --- a/src-tauri/omniget-core/src/core/tools/gslides.rs +++ b/src-tauri/omniget-core/src/core/tools/gslides.rs @@ -209,17 +209,9 @@ pub fn normalize_slide_svg_geometry(svg: &str) -> String { let mut cleaned = width_re.replace_all(open_tag, "").into_owned(); cleaned = height_re.replace_all(&cleaned, "").into_owned(); if !viewbox_re.is_match(&cleaned) { - cleaned = cleaned.replacen( - " String { static VIEWER_TITLE_RE: OnceLock = OnceLock::new(); static HTML_TITLE_RE: OnceLock = OnceLock::new(); - let viewer_re = VIEWER_TITLE_RE - .get_or_init(|| Regex::new(r"title:\s*'((?:\\.|[^'])*)'").unwrap()); + let viewer_re = + VIEWER_TITLE_RE.get_or_init(|| Regex::new(r"title:\s*'((?:\\.|[^'])*)'").unwrap()); let head_slice = &html[..html.len().min(350_000)]; if let Some(c) = viewer_re.captures(head_slice) { let decoded = unescape_js_string(&c[1]); @@ -274,8 +266,8 @@ pub fn extract_title_from_viewer_html(html: &str) -> String { } } - let html_re = HTML_TITLE_RE - .get_or_init(|| Regex::new(r"(?is)]*>(.*?)").unwrap()); + let html_re = + HTML_TITLE_RE.get_or_init(|| Regex::new(r"(?is)]*>(.*?)").unwrap()); if let Some(c) = html_re.captures(head_slice) { let raw = c[1].trim(); if !raw.is_empty() { @@ -289,8 +281,7 @@ pub fn extract_title_from_viewer_html(html: &str) -> String { /// Extrae todos los bloques `SK_svgData` en el orden exacto de las diapositivas. pub fn extract_viewer_slides(html: &str) -> ExtractedPresentation { static SVG_DATA_RE: OnceLock = OnceLock::new(); - let re = SVG_DATA_RE - .get_or_init(|| Regex::new(r"SK_svgData\s*=\s*'((?:\\.|[^'])*)'").unwrap()); + let re = SVG_DATA_RE.get_or_init(|| Regex::new(r"SK_svgData\s*=\s*'((?:\\.|[^'])*)'").unwrap()); let title = extract_title_from_viewer_html(html); let mut svgs = Vec::new(); @@ -467,8 +458,13 @@ pub fn render_svg_to_jpeg(svg_str: &str) -> anyhow::Result> { let target_w = RENDER_WIDTH_PX; let target_h = RENDER_HEIGHT_PX; - let mut pixmap = tiny_skia::Pixmap::new(target_w, target_h) - .ok_or_else(|| anyhow!("No se pudo reservar memoria para el pixmap {}x{}", target_w, target_h))?; + let mut pixmap = tiny_skia::Pixmap::new(target_w, target_h).ok_or_else(|| { + anyhow!( + "No se pudo reservar memoria para el pixmap {}x{}", + target_w, + target_h + ) + })?; // Fondo blanco por defecto para evitar transparencias negras al pasar a JPEG pixmap.fill(tiny_skia::Color::WHITE); @@ -488,18 +484,16 @@ pub fn render_svg_to_jpeg(svg_str: &str) -> anyhow::Result> { rgb.push(px[0]); rgb.push(px[1]); rgb.push(px[2]); - } else if a == 0 { + } else if let Some(r) = (px[0] as u16 * 255).checked_div(a) { + let g = (px[1] as u16 * 255) / a; + let b = (px[2] as u16 * 255) / a; + rgb.push(r.min(255) as u8); + rgb.push(g.min(255) as u8); + rgb.push(b.min(255) as u8); + } else { rgb.push(255); rgb.push(255); rgb.push(255); - } else { - // Des-premultiplicar sobre fondo blanco - let r = ((px[0] as u16 * 255) / a).min(255) as u8; - let g = ((px[1] as u16 * 255) / a).min(255) as u8; - let b = ((px[2] as u16 * 255) / a).min(255) as u8; - rgb.push(r); - rgb.push(g); - rgb.push(b); } } @@ -618,7 +612,11 @@ pub async fn compile_svg_dir_to_pdf( let p = PathBuf::from(custom); if p.is_dir() { p.join(format!("{}.pdf", super::sanitize_name(&dir_title))) - } else if p.extension().map(|e| e.eq_ignore_ascii_case("pdf")).unwrap_or(false) { + } else if p + .extension() + .map(|e| e.eq_ignore_ascii_case("pdf")) + .unwrap_or(false) + { p } else { p.with_extension("pdf") @@ -678,9 +676,8 @@ pub async fn download_presentation( dest_dir: &str, progress: super::ProgressFn, ) -> anyhow::Result { - let target = parse_gslides_url(url).ok_or_else(|| { - anyhow!("Enlace de Google Slides no válido: {}", url) - })?; + let target = parse_gslides_url(url) + .ok_or_else(|| anyhow!("Enlace de Google Slides no válido: {}", url))?; let client = build_google_client(Some(url))?; let progress_id = format!("gslides:{}", target.id); @@ -756,10 +753,9 @@ pub async fn download_presentation( let svgs = extracted.svgs; let progress_clone = progress.clone(); let pid = progress_id.clone(); - let pdf_bytes = tokio::task::spawn_blocking(move || { - compile_svgs_to_pdf(&svgs, &progress_clone, &pid) - }) - .await??; + let pdf_bytes = + tokio::task::spawn_blocking(move || compile_svgs_to_pdf(&svgs, &progress_clone, &pid)) + .await??; let pdf_path = base_dir.join(format!("{}.pdf", safe_title)); tokio::fs::write(&pdf_path, &pdf_bytes).await?; @@ -773,10 +769,11 @@ pub async fn download_presentation( } /// Genera el script JavaScript / Bookmarklet adaptado para enviar diapositivas al -/// `local_bridge` de OmniGet en `http://127.0.0.1:/api`. -pub fn browser_extractor_script(port: u16) -> String { +/// `local_bridge` de OmniGet en `http://127.0.0.1:/api` autenticado con token Bearer. +pub fn browser_extractor_script(port: u16, token: &str) -> String { let tpl = r##"javascript:(function(){ const SERVER_URL = "http://127.0.0.1:__PORT__/api"; + const AUTH_HEADERS = { "Content-Type": "application/json", "Authorization": "Bearer __TOKEN__" }; let count = 1; let lastSvgSignature = ""; let duplicateCount = 0; @@ -784,7 +781,7 @@ pub fn browser_extractor_script(port: u16) -> String { fetch(`${SERVER_URL}/reset`, { method: "POST", - headers: { "Content-Type": "application/json" }, + headers: AUTH_HEADERS, body: JSON.stringify({ title: deckTitle }) }); @@ -844,7 +841,7 @@ pub fn browser_extractor_script(port: u16) -> String { btn.textContent = "⚙️ Compilando PDF 16:9 en OmniGet..."; let r = await fetch(`${SERVER_URL}/compile`, { method: "POST", - headers: { "Content-Type": "application/json" }, + headers: AUTH_HEADERS, body: JSON.stringify({ title: deckTitle }) }); let j = await r.json().catch(() => ({})); @@ -868,7 +865,7 @@ pub fn browser_extractor_script(port: u16) -> String { let xml = new XMLSerializer().serializeToString(clone); await fetch(`${SERVER_URL}/slide`, { method: "POST", - headers: { "Content-Type": "application/json" }, + headers: AUTH_HEADERS, body: JSON.stringify({ index: count++, svg_content: xml, title: deckTitle }) }); @@ -882,6 +879,7 @@ pub fn browser_extractor_script(port: u16) -> String { setTimeout(stepCapture, 1200); })();"##; tpl.replace("__PORT__", &port.to_string()) + .replace("__TOKEN__", token) } #[cfg(test)] diff --git a/src-tauri/omniget-core/src/platforms/gdocs.rs b/src-tauri/omniget-core/src/platforms/gdocs.rs index a56ed4f6..8294dd31 100644 --- a/src-tauri/omniget-core/src/platforms/gdocs.rs +++ b/src-tauri/omniget-core/src/platforms/gdocs.rs @@ -56,7 +56,7 @@ async fn fetch_presentation_title(url: &str) -> Option { } } -fn compute_path_size(path: & std::path::Path) -> u64 { +fn compute_path_size(path: &std::path::Path) -> u64 { if let Ok(meta) = std::fs::metadata(path) { if meta.is_file() { return meta.len(); @@ -85,15 +85,12 @@ impl PlatformDownloader for GdocsDownloader { } async fn get_media_info(&self, url: &str) -> anyhow::Result { - let parsed = gdocs::parse(url) - .ok_or_else(|| anyhow!("Enlace de Google Docs/Slides no válido"))?; + let parsed = + gdocs::parse(url).ok_or_else(|| anyhow!("Enlace de Google Docs/Slides no válido"))?; let title = if parsed.kind == "presentation" { fetch_presentation_title(url).await.unwrap_or_else(|| { - format!( - "Google Slides ({})", - &parsed.id[..parsed.id.len().min(12)] - ) + format!("Google Slides ({})", &parsed.id[..parsed.id.len().min(12)]) }) } else { format!( @@ -108,8 +105,16 @@ impl PlatformDownloader for GdocsDownloader { .iter() .map(|fmt| VideoQuality { label: fmt.to_uppercase(), - width: if parsed.kind == "presentation" { 1280 } else { 0 }, - height: if parsed.kind == "presentation" { 720 } else { 0 }, + width: if parsed.kind == "presentation" { + 1280 + } else { + 0 + }, + height: if parsed.kind == "presentation" { + 720 + } else { + 0 + }, url: url.to_string(), format: fmt.clone(), }) diff --git a/src-tauri/omniget-core/src/platforms/mod.rs b/src-tauri/omniget-core/src/platforms/mod.rs index 41c5412d..528bfbe4 100644 --- a/src-tauri/omniget-core/src/platforms/mod.rs +++ b/src-tauri/omniget-core/src/platforms/mod.rs @@ -212,9 +212,7 @@ impl Platform { Some(Platform::Other("mgtv".to_string())) } else if matches("youku.com") { Some(Platform::Other("youku".to_string())) - } else if host == "docs.google.com" - && crate::core::tools::gdocs::parse(url_str).is_some() - { + } else if host == "docs.google.com" && crate::core::tools::gdocs::parse(url_str).is_some() { Some(Platform::Other("gdocs".to_string())) } else if is_direct_file_url(url_str) { Some(Platform::Other("direct_file".to_string())) diff --git a/src-tauri/src/local_bridge.rs b/src-tauri/src/local_bridge.rs index 1c2cf828..6b27b5f7 100644 --- a/src-tauri/src/local_bridge.rs +++ b/src-tauri/src/local_bridge.rs @@ -604,13 +604,19 @@ struct PairResponse { fn is_allowed_pair_origin(origin: &str) -> bool { let o = origin.trim(); - o.starts_with("chrome-extension://") + if o.starts_with("chrome-extension://") || o.starts_with("moz-extension://") || o.starts_with("safari-web-extension://") || o.starts_with("tauri://") - || o.starts_with("http://localhost") - || o.starts_with("http://127.0.0.1") - || o.starts_with("https://localhost") + { + return true; + } + if let Ok(parsed) = url::Url::parse(o) { + if matches!(parsed.scheme(), "http" | "https") { + return matches!(parsed.host_str(), Some("localhost" | "127.0.0.1")); + } + } + false } async fn pair(State(state): State, headers: HeaderMap) -> Response { @@ -944,6 +950,7 @@ pub struct SlidesBridgeStatus { pub fn slides_bridge_status() -> SlidesBridgeStatus { let port = BOUND_PORT.load(Ordering::SeqCst); let effective_port = if port == 0 { 47720 } else { port }; + let token = active_token().unwrap_or_default(); let (slide_count, last_output) = slides_buffer() .lock() .ok() @@ -953,7 +960,10 @@ pub fn slides_bridge_status() -> SlidesBridgeStatus { port: effective_port, slide_count, last_output, - script: omniget_core::core::tools::gslides::browser_extractor_script(effective_port), + script: omniget_core::core::tools::gslides::browser_extractor_script( + effective_port, + &token, + ), } } @@ -973,11 +983,17 @@ struct SlideReceiveBody { async fn slides_reset( State(state): State, + headers: HeaderMap, body: Option>, ) -> Response { + if !check_bearer(&headers, &state.token) { + return unauthorized(); + } if let Ok(mut guard) = slides_buffer().lock() { guard.slides.clear(); - guard.title = body.and_then(|b| b.0.title).filter(|t| !t.trim().is_empty()); + guard.title = body + .and_then(|b| b.0.title) + .filter(|t| !t.trim().is_empty()); } let _ = state.app.emit( "gslides-bridge-progress", @@ -992,8 +1008,12 @@ async fn slides_reset( async fn slides_receive( State(state): State, + headers: HeaderMap, Json(data): Json, ) -> Response { + if !check_bearer(&headers, &state.token) { + return unauthorized(); + } let count = if let Ok(mut guard) = slides_buffer().lock() { if let Some(t) = data.title.filter(|t| !t.trim().is_empty()) { guard.title = Some(t); @@ -1020,11 +1040,18 @@ async fn slides_receive( async fn slides_compile( State(state): State, + headers: HeaderMap, body: Option>, ) -> Response { + if !check_bearer(&headers, &state.token) { + return unauthorized(); + } let (mut indexed_svgs, title) = match slides_buffer().lock() { Ok(mut guard) => { - if let Some(t) = body.and_then(|b| b.0.title).filter(|t| !t.trim().is_empty()) { + if let Some(t) = body + .and_then(|b| b.0.title) + .filter(|t| !t.trim().is_empty()) + { guard.title = Some(t); } ( @@ -1171,6 +1198,24 @@ mod tests { assert_eq!(build_pairing_url(47720), "http://127.0.0.1:47720"); } + #[test] + fn allowed_pair_origin_rejects_spoofed_subdomains() { + assert!(is_allowed_pair_origin( + "chrome-extension://abcdefghijklmnop" + )); + assert!(is_allowed_pair_origin("moz-extension://1234-5678")); + assert!(is_allowed_pair_origin("tauri://localhost")); + assert!(is_allowed_pair_origin("http://localhost:1420")); + assert!(is_allowed_pair_origin("https://localhost:47720")); + assert!(is_allowed_pair_origin("http://127.0.0.1:47720")); + assert!(!is_allowed_pair_origin("https://localhost.evil.com")); + assert!(!is_allowed_pair_origin( + "http://localhost.attacker.tld:8080" + )); + assert!(!is_allowed_pair_origin("http://127.0.0.1.evil.com")); + assert!(!is_allowed_pair_origin("https://evil.com")); + } + #[test] fn byte_ranges_parse_into_specs() { use ByteRange::*; From 3826c7eda85d9a70786253ebc41a2d849343ee8e Mon Sep 17 00:00:00 2001 From: Mad0 Date: Tue, 10 Nov 2026 19:17:02 -0600 Subject: [PATCH 3/3] fix(docs): resolve broken Iconify icon URLs across documentation READMEs --- README.ja.md | 46 +++++++++++++++++++++++----------------------- README.md | 46 +++++++++++++++++++++++----------------------- README.ru.md | 46 +++++++++++++++++++++++----------------------- README_pt_br.md | 36 ++++++++++++++++++------------------ README_zh_CN.md | 36 ++++++++++++++++++------------------ 5 files changed, 105 insertions(+), 105 deletions(-) diff --git a/README.ja.md b/README.ja.md index 292d1433..06158f12 100644 --- a/README.ja.md +++ b/README.ja.md @@ -199,12 +199,12 @@ OmniGet は、よく使われるプラットフォーム向けのネイティブ | カテゴリ | サイトと形式 | |---|---| -| オンライン講座 オンライン講座 | 組み込みの Courses プラグインを通じて 38 のプラットフォーム(Hotmart、Udemy、Kiwify、Rocketseat、Coursera、Domestika、Skillshare など)に対応しています。すべてのレッスン、セクションの選択、添付ファイル、中断したところからの再開に対応しています。 | -| 動画と音声 動画と音声 | YouTube(動画、プレイリスト、チャンネル、ライブの最初から、チャプター、SponsorBlock)、Instagram、TikTok、X/Twitter、Reddit、Twitch(VOD、クリップ、ライブ)、Vimeo、Bluesky、Threads、Pinterest、Douyin | +| オンライン講座 オンライン講座 | 組み込みの Courses プラグインを通じて 38 のプラットフォーム(Hotmart、Udemy、Kiwify、Rocketseat、Coursera、Domestika、Skillshare など)に対応しています。すべてのレッスン、セクションの選択、添付ファイル、中断したところからの再開に対応しています。 | +| 動画と音声 動画と音声 | YouTube(動画、プレイリスト、チャンネル、ライブの最初から、チャプター、SponsorBlock)、Instagram、TikTok、X/Twitter、Reddit、Twitch(VOD、クリップ、ライブ)、Vimeo、Bluesky、Threads、Pinterest、Douyin | | Bilibili Bilibili(ログイン時) | ご利用のサブスクリプションに応じて 4K、HDR、Dolby Vision、Hi-Res ロスレス、Dolby Atmos に対応。弾幕コメントを XML、ASS、JSON で保存、Kodi や Jellyfin 向けの NFO ファイル、カスタムの命名テンプレート、番組、講座、お気に入り、後で見る、履歴を含む 11 種類の URL に対応 | -| 画像ギャラリー 画像ギャラリー | gallery-dl を通じて 250 以上のサイト(DeviantArt、Pixiv、ArtStation、Flickr、Tumblr、Imgur、Kemono など)からギャラリーやプロフィールを丸ごと取得 | -| 一括 一括 | 多数のリンクを貼り付けるか `.txt` を読み込み、サブレディット全体、Reddit や X のプロフィール、Instagram や Pinterest のプロフィール、Facebook のアルバムをダウンロード | -| ファイルと転送 ファイルと転送 | 内蔵の BitTorrent クライアントによる `.torrent` ファイルとマグネットリンク、HTTP による直接のファイル、HLS と DASH のマニフェスト、短い単語コードを使った 2 つの OmniGet 間での個人間転送 | +| 画像ギャラリー 画像ギャラリー | gallery-dl を通じて 250 以上のサイト(DeviantArt、Pixiv、ArtStation、Flickr、Tumblr、Imgur、Kemono など)からギャラリーやプロフィールを丸ごと取得 | +| 一括 一括 | 多数のリンクを貼り付けるか `.txt` を読み込み、サブレディット全体、Reddit や X のプロフィール、Instagram や Pinterest のプロフィール、Facebook のアルバムをダウンロード | +| ファイルと転送 ファイルと転送 | 内蔵の BitTorrent クライアントによる `.torrent` ファイルとマグネットリンク、HTTP による直接のファイル、HLS と DASH のマニフェスト、短い単語コードを使った 2 つの OmniGet 間での個人間転送 | | Telegram Telegram | 組み込みの Telegram プラグインを通じて、参加しているチャンネルやグループの写真、動画、ファイル、音声を、チャンネルごとに整理されたフォルダー(`OmniGram//`)に保存 | 一度設定すれば忘れてよいオプション:デフォルトの画質、音声のみの形式(MP3、M4A、Opus、FLAC、WAV)、字幕の言語と形式(SRT、VTT、ASS、埋め込みまたは別ファイル)、サムネイルとメタデータの埋め込み、ファイル名のテンプレート、プラットフォームごとの整理、既存ファイルのスキップ、チャプターごとの分割、速度制限、同時ダウンロード数、プロキシ。ルールを使えば、特定のチャンネルやホストを、毎回確認することなく、指定したフォルダーと画質に振り分けられます。フォロー中のチャンネルはバックグラウンドでチェックされ、新しいアップロードをトレイ通知付きで自動的にダウンロードすることもできます。 @@ -296,7 +296,7 @@ Firefox:Firefox の横にある **Settings → Plugins → Browser extension - **本当のサムネイル。** 釣り目的のカバー画像ではなく、CDN がすでに持っている 25%、50%、75% 地点のフレームを表示します。 - **Force H.264.** ブラウザ拡張機能のスイッチで、YouTube を VP9 や AV1 ではなく H.264 で再生させます。新しいコーデックでカクつくマシン向けです。 -### 音声と字幕 音声と字幕 (8) +### 音声と字幕 音声と字幕 (8) - **文字起こし。** whisper.cpp を使って、音声や動画をオフラインで字幕にします。モデルは必要に応じてダウンロードされ、macOS では Metal によるアクセラレーションが使われます。 - **テキスト読み上げ。** Microsoft Edge の自然な音声を無料で使い、同期した字幕ファイルも作成します。 @@ -305,7 +305,7 @@ Firefox:Firefox の横にある **Settings → Plugins → Browser extension - マシン上で動作する VoiceStudio を通じて、**声のクローン**、**声のデザイン**、**ボーカルの分離** が行えます。*beta* - **音声入力。** グローバルショートカットを押して話すと、whisper がカーソルの位置にテキストを入力します。*beta* -### 動画編集 動画編集 (14) +### 動画編集 動画編集 (14) - **クリップの切り出し。** ディスク上の動画を選んで、一部分を切り出します。結果はダウンロードキューに追加されます。 - **変換。** Convert プラグインを通じて、コンテナ、コーデック、解像度を変更したり、圧縮したりします。 @@ -321,7 +321,7 @@ Firefox:Firefox の横にある **Settings → Plugins → Browser extension - **画面の録画。** FFmpeg を通じて画面とシステム音声を録画し、直前の出来事を保存できるリプレイバッファーも備えています。*beta* - **タイムラインエディター。** *planned* -### オーディオ オーディオ (2) +### オーディオ オーディオ (2) - **ラウドネスの正規化。** 2 パスの EBU R128 で、ストリーミング、ポッドキャスト、放送が求める音量に合わせます。 - **ノイズ除去。** 録音からヒスノイズ、ファンの音、室内の雑音を取り除きます。追加のダウンロードは不要です。 @@ -413,13 +413,13 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **テーマとカラー。** Spicetify のテーマで Spotify クライアントをカスタマイズします。*beta* - **拡張機能。** Spicetify の Marketplace から拡張機能やカスタムアプリをインストールします。*beta* -### 音楽 音楽 (3) +### 音楽 音楽 (3) - **プレイリストから M3U へ。** エクスポートしたプレイリストを手持ちの音声ファイルと照合し、任意のローカルプレイヤー向けに `.m3u8` と `.pls` を書き出します。 - **同期歌詞。** LRCLIB から歌詞を取得し、各トラックの隣に `.lrc` を保存します。 - **Spotify の履歴。** 完全なデータエクスポートを開き、Wrapped では表示されないすべてを確認します。 -### LinkedIn LinkedIn (4) +### LinkedIn LinkedIn (4) 4 つとも、LinkedIn にリクエストできる公式のデータエクスポートを、あなたのマシン上で読み取ります。ログインは一切行いません。 @@ -428,13 +428,13 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **メッセージ。** チャット履歴を閲覧し、ローカルのページとして保存します。 - **プロフィールスコア。** オフラインでプロフィールの充実度をチェックし、足りないものを表示します。 -### ゲーム ゲーム (3) +### ゲーム ゲーム (3) - **Switch のアルバム。** Switch の SD カードからスクリーンショットとクリップを取り込み、ゲーム名と日付で名前を付けます。 - **クリップの整理。** Game Bar、ShadowPlay、OBS、Steam のキャプチャを、ゲームごとのフォルダーに振り分けます。 - **Linux で動く?** 1 つのゲーム、または Steam ライブラリ全体の ProtonDB のティアを表示します。 -### PDF PDF (13) +### PDF PDF (13) - **結合。** 複数の PDF を、選んだ順序で 1 つにまとめます。 - **分割。** ページを抽出するか、PDF を複数に分割します。 @@ -450,7 +450,7 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **安全な PDF。** PDF をピクセルから再構築し、スクリプトやフォームを取り除きます。 - **PDF から Markdown へ。** 見出し、リスト、表を含むきれいな Markdown にし、そのまま LLM に貼り付けられるようにします。 -### ドキュメント ドキュメント (5) +### ドキュメント ドキュメント (5) - **SlideShare から PDF へ。** すべてのスライドを最大サイズで取得し、1 つの PDF にまとめます。 - **Google ドキュメントのエクスポート。** 公開されている Docs、Slides、Sheets を PDF、DOCX、PPTX、XLSX で保存します。 @@ -458,7 +458,7 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **画像ギャラリー。** gallery-dl を使って、250 以上のサイトからギャラリーやプロフィールを丸ごと取得します。 - **Scribd.** あなた自身のセッションを使って、閲覧可能な書籍を PDF で保存します。*planned* -### 画像 画像 (9) +### 画像 画像 (9) - **アップスケール。** 任意の Vulkan GPU 上の Real-ESRGAN で、2 倍、3 倍、4 倍に拡大します。*beta* - **画像のリサイズ。** 幅、高さ、フィット、パーセントで一括リサイズし、必要に応じて形式も変換します。 @@ -470,7 +470,7 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **スプライトシート。** シートをフレームに切り分ける、フレームをアトラス付きでシートにまとめ直す、フォルダー内の画像をルールに従ってリサイズする、のいずれかを行います。 - **OCR.** 画像やスライドからテキストをコピーします。*beta* -### システム システム (10、Windows 専用の項目は明記) +### システム システム (10、Windows 専用の項目は明記) - **キャッシュのクリーンアップ。** OS ごとのルールで、一時ファイル、ログ、アプリのキャッシュを削除します。削除の前に一覧を確認できます。 - **ディスクアナライザー。** 容量を占めているものをツリーマップと最大のファイルの一覧で表示し、ゴミ箱に送るボタンも備えています。 @@ -483,7 +483,7 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **レジストリクリーナー。** 孤立したエントリーを、削除前に `.reg` でバックアップしてから削除します。Windows。*beta* - **ソフトウェアアップデーター。** winget、Chocolatey、Scoop を通じて、プログラムを一括で更新します。Windows。*beta* -### ファイル ファイル (5) +### ファイル ファイル (5) - **重複。** ハッシュで同一のファイルを見つけ、安全に空き容量を確保します。 - **一括リネーム。** 正規表現、連番、大文字・小文字の変換を、適用前のプレビュー付きで行います。 @@ -491,20 +491,20 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **ファイル検索。** Windows では Everything、macOS では Spotlight、Linux では fd を使って瞬時に検索します。 - **スリープ防止。** 長い処理の間、コンピューターがスリープしないようにします。 -### ダウンロード ダウンロード (2) +### ダウンロード ダウンロード (2) - **高速ダウンロード。** aria2 を使い、16 本の接続、再開、チェックサムで大きなファイルをダウンロードします。 - **HLS / DASH マニフェスト。** Referer と Cookie を付けて `.m3u8` または `.mpd` を貼り付けると、FFmpeg が MP4 で保存します。 -### 自動化 自動化 (1) +### 自動化 自動化 (1) - **オートクリッカー。** グローバルホットキー、上限、ランダムな範囲を設定して、指定したとおりの速度でクリックします。Windows、macOS、Linux。*beta* -### スマートフォン スマートフォン (1) +### スマートフォン スマートフォン (1) - **スマートフォンに送信。** ペアリングした KDE Connect デバイスに、ファイル、リンク、テキストを送ります。 -### AI AI (6) +### AI AI (6) - **価格の比較。** LiteLLM と models.dev の価格をもとに、同じモデルのプロバイダーごとのコストを比較します。 - **AI の支出。** OmniGet が AI に使った金額を、ローカルの台帳から日別、モデル別、タスク別に表示します。 @@ -513,7 +513,7 @@ Bilibili の動画のダウンロードはホーム画面から行います。 - **API キー。** キーとアカウントのためのローカルの保管庫です。接続テスト、OpenRouter、DeepSeek、SiliconFlow、New API の残高表示、Claude Code、Codex、Cherry Studio、opencode、`.env` ファイルへのエクスポートに対応しています。 - **MCP サーバー。** OmniGet のツールをローカルブリッジ上の Model Context Protocol で公開します。拡張機能と同じトークンで保護された 37 のツールがあり、Claude Code、Claude Desktop、Cursor、VS Code、Goose、Codex 向けのすぐに使える設定スニペットも用意されています。[AI エージェント向けの OmniGet](#ai-エージェント向けの-omniget-mcp-サーバーと-claude-code-プラグイン) をご覧ください。*beta* -### CTF と解析 CTF と解析 (6) +### CTF と解析 CTF と解析 (6) CTF(capture-the-flag)の問題、フォレンジックの課題、「このファイルは何?」という場面のための、6 つの小さなオフラインユーティリティです。 @@ -562,7 +562,7 @@ AI と通信するツールはすべて、**Settings → AI** で設定したプ Courses、Telegram、Convert の各プラグインを、バージョン、作者、権限、有効化スイッチとともに一覧表示している OmniGet の Marketplace

-### Courses Courses +### Courses Courses 組み込みの Courses プラグインは、**Hotmart**、**Udemy**、**Kiwify**、**Rocketseat**、**Coursera**、**Domestika**、**Skillshare**、**Alura**、**Ebac** を含む 38 の学習プラットフォームに対応しています。アプリ内の Web ビューからログインするか、拡張機能で保存した Cookie を使うか、利用可能な場合はアカウントの認証情報でログインします。OmniGet は購入済みの講座を一覧表示し、講座のアウトラインを開いて必要なセクションを選べるようにし(DRM で保護された講義はスキップされ、報告されます)、レッスンと添付ファイルを、必要に応じて通し番号を付けてダウンロードします。 @@ -570,7 +570,7 @@ AI と通信するツールはすべて、**Settings → AI** で設定したプ QR コードまたは電話番号でログインします。参加しているすべてのチャンネルとグループを閲覧し、写真、動画、ドキュメント、音声で絞り込み、ファイルを検索し、個別のメディアやチャットのアーカイブ全体を、進捗リスト付きでダウンロードできます。メディアのダウンロードは、サニタイズされたフォルダー名で `{download_dir}/OmniGram/{channel_name}/` に整理されます。 -### Convert Convert +### Convert Convert マシンが対応していれば GPU アクセラレーションを使って FFmpeg で変換します:動画と音声のコンテナ、コーデック、解像度、ビットレート、圧縮を変更でき、インターネット接続は不要です。 diff --git a/README.md b/README.md index 8f1af456..d0c390ea 100644 --- a/README.md +++ b/README.md @@ -199,12 +199,12 @@ OmniGet has native extractors for the platforms people use most, and hands every | Category | Sites and formats | |---|---| -| Online courses Online courses | 38 supported platforms (Hotmart, Udemy, Kiwify, Rocketseat, Coursera, Domestika, Skillshare, and more) through the embedded Courses plugin. Every lesson, section selection, attachments, resume where you stopped. | -| Video and audio Video and audio | YouTube (videos, playlists, channels, live from start, chapters, SponsorBlock), Instagram, TikTok, X/Twitter, Reddit, Twitch (VODs, clips, live), Vimeo, Bluesky, Threads, Pinterest, Douyin | +| Online courses Online courses | 38 supported platforms (Hotmart, Udemy, Kiwify, Rocketseat, Coursera, Domestika, Skillshare, and more) through the embedded Courses plugin. Every lesson, section selection, attachments, resume where you stopped. | +| Video and audio Video and audio | YouTube (videos, playlists, channels, live from start, chapters, SponsorBlock), Instagram, TikTok, X/Twitter, Reddit, Twitch (VODs, clips, live), Vimeo, Bluesky, Threads, Pinterest, Douyin | | Bilibili Bilibili, signed in | 4K, HDR, Dolby Vision, Hi-Res lossless and Dolby Atmos according to your subscription. Danmaku comments as XML, ASS or JSON, NFO files for Kodi and Jellyfin, custom naming templates, 11 URL types including bangumi, courses, favorites, watch later and history | -| Image galleries Image galleries | Whole galleries and profiles from 250+ sites through gallery-dl (DeviantArt, Pixiv, ArtStation, Flickr, Tumblr, Imgur, Kemono and more) | -| Bulk Bulk | Paste many links or load a `.txt`, download whole subreddits, Reddit and X profiles, Instagram and Pinterest profiles, Facebook albums | -| Files and transfer Files and transfer | `.torrent` files and magnet links with a built-in BitTorrent client, direct HTTP files, HLS and DASH manifests, and person-to-person transfer between two OmniGet installs with a short word code | +| Image galleries Image galleries | Whole galleries and profiles from 250+ sites through gallery-dl (DeviantArt, Pixiv, ArtStation, Flickr, Tumblr, Imgur, Kemono and more) | +| Bulk Bulk | Paste many links or load a `.txt`, download whole subreddits, Reddit and X profiles, Instagram and Pinterest profiles, Facebook albums | +| Files and transfer Files and transfer | `.torrent` files and magnet links with a built-in BitTorrent client, direct HTTP files, HLS and DASH manifests, and person-to-person transfer between two OmniGet installs with a short word code | | Telegram Telegram | Photos, videos, files and audio from any channel or group you belong to, saved into organized channel folders (`OmniGram//`), through the embedded Telegram plugin | Options you set once and forget: default quality, audio-only format (MP3, M4A, Opus, FLAC or WAV), subtitle languages and format (SRT, VTT, ASS, embedded or sidecar), thumbnail and metadata embedding, filename template, organize by platform, skip existing files, split by chapters, speed limit, concurrent downloads, proxy. Rules send a given channel or host to a folder and quality of your choice without asking again. Followed channels are checked in the background and can download new uploads automatically with a tray notification. @@ -296,7 +296,7 @@ Status legend: no mark means ready, **beta** means it works but has not been tes - **Real thumbnail.** The frames the CDN already has at 25, 50 and 75 percent, instead of the clickbait cover. - **Force H.264.** A switch in the browser extension that keeps YouTube on H.264 instead of VP9 and AV1, for machines that stutter on newer codecs. -### Speech and subtitles Speech and subtitles (8) +### Speech and subtitles Speech and subtitles (8) - **Transcribe.** Audio or video to subtitles with whisper.cpp, offline. Models download on demand, Metal acceleration on macOS. - **Text to speech.** Natural voices from Microsoft Edge, free, with a synced subtitle file. @@ -305,7 +305,7 @@ Status legend: no mark means ready, **beta** means it works but has not been tes - **Clone a voice**, **Design a voice** and **Isolate vocals** through a VoiceStudio install running on your machine. *beta* - **Dictation.** Press a global shortcut, speak, and whisper types the text where your cursor is. *beta* -### Video editing Video editing (14) +### Video editing Video editing (14) - **Cut a clip.** Pick a video on disk and cut out a section. The result lands in the downloads queue. - **Convert.** Change container, codec or resolution, or compress, through the Convert plugin. @@ -321,7 +321,7 @@ Status legend: no mark means ready, **beta** means it works but has not been tes - **Record screen.** Screen and system audio through FFmpeg, with a replay buffer that saves what just happened. *beta* - **Timeline editor.** *planned* -### Audio Audio (2) +### Audio Audio (2) - **Normalize loudness.** Two-pass EBU R128, so the audio lands where streaming, podcast or broadcast expects it. - **Remove noise.** Hiss, fan and room noise taken out of a recording, with nothing to download. @@ -413,13 +413,13 @@ Video downloads from Bilibili live on the home screen. These two are about the f - **Themes and colors.** Customize the Spotify client with Spicetify themes. *beta* - **Extensions.** Install Spicetify extensions and custom apps from its Marketplace. *beta* -### Music Music (3) +### Music Music (3) - **Playlist to M3U.** Match an exported playlist with the audio files you own and write `.m3u8` and `.pls` for any local player. - **Synced lyrics.** Fetch lyrics from LRCLIB and save an `.lrc` next to each track. - **Spotify history.** Open your full data export and see everything Wrapped leaves out. -### LinkedIn LinkedIn (4) +### LinkedIn LinkedIn (4) All four read the official data export LinkedIn lets you request, on your own machine. Nothing logs in. @@ -428,13 +428,13 @@ All four read the official data export LinkedIn lets you request, on your own ma - **Messages.** Browse your chat history and save it as a local page. - **Profile score.** An offline completeness check with what is missing. -### Games Games (3) +### Games Games (3) - **Switch album.** Import screenshots and clips from the Switch SD card, named by game and date. - **Clip organizer.** Sort Game Bar, ShadowPlay, OBS and Steam captures into folders by game. - **Runs on Linux?** The ProtonDB tier for one game or your whole Steam library. -### PDF PDF (13) +### PDF PDF (13) - **Merge.** Join several PDFs into one, in the order you choose. - **Split.** Extract pages or break a PDF into parts. @@ -450,7 +450,7 @@ All four read the official data export LinkedIn lets you request, on your own ma - **Safe PDF.** Rebuild a PDF from pixels to strip scripts and forms. - **PDF to Markdown.** Clean Markdown with headings, lists and tables, ready to paste into an LLM. -### Documents Documents (5) +### Documents Documents (5) - **SlideShare to PDF.** Every slide at the largest size, assembled into one PDF. - **Google Docs export.** Public Docs, Slides and Sheets as PDF, DOCX, PPTX or XLSX. @@ -458,7 +458,7 @@ All four read the official data export LinkedIn lets you request, on your own ma - **Image galleries.** Whole galleries and profiles from 250+ sites with gallery-dl. - **Scribd.** Save readable books as PDF using your own session. *planned* -### Images Images (9) +### Images Images (9) - **Upscale.** Real-ESRGAN on any Vulkan GPU, 2x, 3x or 4x. *beta* - **Resize images.** Batch resize by width, height, fit or percent, converting the format if you want. @@ -470,7 +470,7 @@ All four read the official data export LinkedIn lets you request, on your own ma - **Spritesheet.** Slice a sheet into frames, pack frames back with an atlas, or resize a folder by rule. - **OCR.** Copy the text out of images and slides. *beta* -### System System (10, Windows-only items marked) +### System System (10, Windows-only items marked) - **Clean caches.** Temp files, logs and app caches with rules per operating system. You review the list before anything is deleted. - **Disk analyzer.** What takes space, as a treemap plus the largest files, with a send-to-trash button. @@ -483,7 +483,7 @@ All four read the official data export LinkedIn lets you request, on your own ma - **Registry cleaner.** Orphaned entries, with a `.reg` backup before removal. Windows. *beta* - **Software updater.** Update programs in bulk through winget, Chocolatey and Scoop. Windows. *beta* -### Files Files (5) +### Files Files (5) - **Duplicates.** Find identical files by hash and free space safely. - **Bulk rename.** Regex, counters and case changes with a preview before applying. @@ -491,20 +491,20 @@ All four read the official data export LinkedIn lets you request, on your own ma - **Find files.** Instant search with Everything on Windows, Spotlight on macOS or fd on Linux. - **Keep awake.** Stop the computer from sleeping during long jobs. -### Downloads Downloads (2) +### Downloads Downloads (2) - **Accelerated download.** Big files with 16 connections, resume and checksum via aria2. - **HLS / DASH manifest.** Paste a `.m3u8` or `.mpd` with Referer and cookie. FFmpeg saves an MP4. -### Automation Automation (1) +### Automation Automation (1) - **Auto clicker.** Click at the exact speed you set, with a global hotkey, limits and random ranges. Windows, macOS and Linux. *beta* -### Phone Phone (1) +### Phone Phone (1) - **Send to phone.** Files, links and text to a paired KDE Connect device. -### AI AI (6) +### AI AI (6) - **Compare prices.** The cost of the same model across providers, with prices from LiteLLM and models.dev. - **AI spending.** How much OmniGet spent on AI, by day, model and task, from a local ledger. @@ -513,7 +513,7 @@ All four read the official data export LinkedIn lets you request, on your own ma - **API keys.** A local vault for keys and accounts, with a connection test, balance for OpenRouter, DeepSeek, SiliconFlow and New API, and export to Claude Code, Codex, Cherry Studio, opencode or a `.env` file. - **MCP server.** OmniGet's tools exposed over the Model Context Protocol on the local bridge, 37 tools behind the same token the extension uses, with ready-made config snippets for Claude Code, Claude Desktop, Cursor, VS Code, Goose and Codex. See [OmniGet for AI agents](#omniget-for-ai-agents-mcp-server-and-claude-code-plugin). *beta* -### CTF and analysis CTF and analysis (6) +### CTF and analysis CTF and analysis (6) Six small offline utilities for capture-the-flag puzzles, forensics homework and "what is this file" moments. @@ -562,7 +562,7 @@ Core plugins are embedded directly into the application binary, eliminating runt OmniGet Marketplace listing the Courses, Telegram and Convert plugins with version, author, permissions and enable switches

-### Courses Courses +### Courses Courses The embedded Courses plugin supports 38 learning platforms, including **Hotmart**, **Udemy**, **Kiwify**, **Rocketseat**, **Coursera**, **Domestika**, **Skillshare**, **Alura**, and **Ebac**. Sign in through a webview inside the app, with saved cookies from the extension, or with account credentials where available. OmniGet lists your purchases, opens the course outline so you can select the sections you want (DRM-protected lectures are skipped and reported), and downloads lessons and attachments with optional continuous numbering. @@ -570,7 +570,7 @@ The embedded Courses plugin supports 38 learning platforms, including **Hotmart* Sign in with a QR code or your phone number. Browse every channel and group you belong to, filter by photo, video, document or audio, search files, and download individual media or entire chat archives with a progress list. Media downloads are organized into `{download_dir}/OmniGram/{channel_name}/` with sanitized folder names. -### Convert Convert +### Convert Convert FFmpeg conversions with GPU acceleration where the machine has it: container, codec, resolution, bitrate and compression for video and audio, no internet required. diff --git a/README.ru.md b/README.ru.md index 378fb45c..7bcd975f 100644 --- a/README.ru.md +++ b/README.ru.md @@ -198,12 +198,12 @@ sudo pacman -S gst-plugins-good gst-plugins-bad gst-libav # Arch | Категория | Сайты и форматы | |---|---| -| Онлайн-курсы Онлайн-курсы | Hotmart, Udemy, Kiwify, Rocketseat и Meta-Analysis Academy через плагин Courses. Каждый урок, выбор разделов, вложения, продолжение с места остановки. | -| Видео и аудио Видео и аудио | YouTube (видео, плейлисты, каналы, трансляции с начала, главы, SponsorBlock), Instagram, TikTok, X/Twitter, Reddit, Twitch (VOD, клипы, трансляции), Vimeo, Bluesky, Threads, Pinterest, Douyin | +| Онлайн-курсы Онлайн-курсы | Hotmart, Udemy, Kiwify, Rocketseat и Meta-Analysis Academy через плагин Courses. Каждый урок, выбор разделов, вложения, продолжение с места остановки. | +| Видео и аудио Видео и аудио | YouTube (видео, плейлисты, каналы, трансляции с начала, главы, SponsorBlock), Instagram, TikTok, X/Twitter, Reddit, Twitch (VOD, клипы, трансляции), Vimeo, Bluesky, Threads, Pinterest, Douyin | | Bilibili Bilibili, с входом в аккаунт | 4K, HDR, Dolby Vision, Hi-Res без потерь и Dolby Atmos в соответствии с вашей подпиской. Комментарии данмаку в виде XML, ASS или JSON, файлы NFO для Kodi и Jellyfin, свои шаблоны имён, 11 типов URL, включая bangumi, курсы, избранное, «посмотреть позже» и историю | -| Галереи изображений Галереи изображений | Целые галереи и профили с 250+ сайтов через gallery-dl (DeviantArt, Pixiv, ArtStation, Flickr, Tumblr, Imgur, Kemono и другие) | -| Массово Массово | Вставьте много ссылок или загрузите `.txt`, скачивайте целые сабреддиты, профили Reddit и X, профили Instagram и Pinterest, альбомы Facebook | -| Файлы и передача Файлы и передача | Файлы `.torrent` и magnet-ссылки со встроенным BitTorrent-клиентом, прямые файлы по HTTP, манифесты HLS и DASH и передача от человека к человеку между двумя установками OmniGet по короткому коду-слову | +| Галереи изображений Галереи изображений | Целые галереи и профили с 250+ сайтов через gallery-dl (DeviantArt, Pixiv, ArtStation, Flickr, Tumblr, Imgur, Kemono и другие) | +| Массово Массово | Вставьте много ссылок или загрузите `.txt`, скачивайте целые сабреддиты, профили Reddit и X, профили Instagram и Pinterest, альбомы Facebook | +| Файлы и передача Файлы и передача | Файлы `.torrent` и magnet-ссылки со встроенным BitTorrent-клиентом, прямые файлы по HTTP, манифесты HLS и DASH и передача от человека к человеку между двумя установками OmniGet по короткому коду-слову | | Telegram Telegram | Фото, видео, файлы и аудио из любого канала или группы, где вы состоите, через плагин Telegram | Настройки, которые задаются один раз: качество по умолчанию, формат только аудио (MP3, M4A, Opus, FLAC или WAV), языки и формат субтитров (SRT, VTT, ASS, встроенные или отдельным файлом), встраивание обложки и метаданных, шаблон имени файла, папки по платформам, пропуск существующих файлов, разбиение по главам, ограничение скорости, число одновременных загрузок, прокси. Правила отправляют канал или хост в выбранную папку и качество, не спрашивая снова. Отслеживаемые каналы проверяются в фоне и могут скачивать новые ролики автоматически с уведомлением в трее. @@ -295,7 +295,7 @@ Firefox: **Настройки → Плагины → Расширение для - **Настоящая обложка.** Кадры на отметках 25, 50 и 75 %, которые уже есть на CDN, вместо кликбейтной обложки. - **Принудительно H.264.** Переключатель в расширении для браузера, который держит YouTube на H.264 вместо VP9 и AV1, — для машин, которые тормозят на новых кодеках. -### Речь и субтитры Речь и субтитры (8) +### Речь и субтитры Речь и субтитры (8) - **Распознать речь.** Аудио или видео в субтитры через whisper.cpp, офлайн. Модели скачиваются по запросу, ускорение Metal на macOS. - **Текст в речь.** Естественные голоса из Microsoft Edge, бесплатно, с синхронизированным файлом субтитров. @@ -304,7 +304,7 @@ Firefox: **Настройки → Плагины → Расширение для - **Клонирование голоса**, **Проектирование голоса** и **Выделение вокала** через установленный на вашей машине VoiceStudio. *бета* - **Диктовка.** Нажмите глобальную комбинацию, говорите — и whisper напечатает текст там, где стоит курсор. *бета* -### Видеомонтаж Видеомонтаж (14) +### Видеомонтаж Видеомонтаж (14) - **Вырезать клип.** Выберите видео на диске и вырежьте фрагмент. Результат попадёт в очередь загрузок. - **Конвертировать.** Смените контейнер, кодек или разрешение либо сожмите файл через плагин Convert. @@ -320,7 +320,7 @@ Firefox: **Настройки → Плагины → Расширение для - **Запись экрана.** Экран и системный звук через FFmpeg, плюс буфер повтора, сохраняющий то, что только что произошло. *бета* - **Редактор таймлайна.** *в планах* -### Аудио Аудио (2) +### Аудио Аудио (2) - **Нормализация громкости.** Двухпроходный EBU R128 — звук попадёт на уровень, которого ждут стриминг, подкасты или вещание. - **Подавление шума.** Шипение, шум вентилятора и комнаты убираются из записи — ничего скачивать не нужно. @@ -412,13 +412,13 @@ Firefox: **Настройки → Плагины → Расширение для - **Темы и цвета.** Настройте клиент Spotify темами Spicetify. *бета* - **Расширения.** Устанавливайте расширения Spicetify и пользовательские приложения из его Marketplace. *бета* -### Музыка Музыка (3) +### Музыка Музыка (3) - **Плейлист в M3U.** Сопоставьте экспортированный плейлист со своими аудиофайлами и запишите `.m3u8` и `.pls` для любого локального плеера. - **Синхронизированные тексты.** Загрузите тексты песен из LRCLIB и сохраните `.lrc` рядом с каждым треком. - **История Spotify.** Откройте полный экспорт своих данных и посмотрите всё, что Wrapped оставляет за кадром. -### LinkedIn LinkedIn (4) +### LinkedIn LinkedIn (4) Все четыре читают официальный экспорт данных, который LinkedIn даёт запросить, на вашем компьютере. Никакого входа. @@ -427,13 +427,13 @@ Firefox: **Настройки → Плагины → Расширение для - **Сообщения.** Просмотрите историю переписки и сохраните её как локальную страницу. - **Оценка профиля.** Офлайн-проверка полноты профиля со списком того, чего не хватает. -### Игры Игры (3) +### Игры Игры (3) - **Альбом Switch.** Импортируйте скриншоты и клипы с SD-карты Switch — с именами по игре и дате. - **Организатор клипов.** Разложите записи Game Bar, ShadowPlay, OBS и Steam по папкам для каждой игры. - **Запустится на Linux?** Уровень ProtonDB для одной игры или всей вашей библиотеки Steam. -### PDF PDF (13) +### PDF PDF (13) - **Объединить.** Соедините несколько PDF в один в нужном вам порядке. - **Разделить.** Извлеките страницы или разбейте PDF на части. @@ -449,7 +449,7 @@ Firefox: **Настройки → Плагины → Расширение для - **Безопасный PDF.** Пересоберите PDF из пикселей, удалив скрипты и формы. - **PDF в Markdown.** Чистый Markdown с заголовками, списками и таблицами — готовый к вставке в LLM. -### Документы Документы (5) +### Документы Документы (5) - **SlideShare в PDF.** Каждый слайд в максимальном размере, собранный в один PDF. - **Экспорт Google Docs.** Публичные Docs, Slides и Sheets в формате PDF, DOCX, PPTX или XLSX. @@ -457,7 +457,7 @@ Firefox: **Настройки → Плагины → Расширение для - **Галереи изображений.** Целые галереи и профили с 250+ сайтов с помощью gallery-dl. - **Scribd.** Сохраняйте читаемые книги как PDF через вашу сессию. *в планах* -### Изображения Изображения (9) +### Изображения Изображения (9) - **Увеличение.** Real-ESRGAN на любом GPU с поддержкой Vulkan, 2x, 3x или 4x. *бета* - **Изменение размера.** Пакетно по ширине, высоте, вписыванию или процентам, при желании со сменой формата. @@ -469,7 +469,7 @@ Firefox: **Настройки → Плагины → Расширение для - **Спрайт-лист.** Нарежьте лист на кадры, соберите кадры обратно вместе с атласом или измените размер папки по правилу. - **OCR.** Скопируйте текст из изображений и слайдов. *бета* -### Система Система (10, пункты только для Windows отмечены) +### Система Система (10, пункты только для Windows отмечены) - **Очистка кэшей.** Временные файлы, логи и кэши приложений по правилам для каждой операционной системы. Вы просматриваете список, прежде чем что-то удалится. - **Анализ диска.** Что занимает место: карта-дерево и самые большие файлы, с кнопкой отправки в корзину. @@ -482,7 +482,7 @@ Firefox: **Настройки → Плагины → Расширение для - **Очистка реестра.** Осиротевшие записи, с резервной копией `.reg` перед удалением. Windows. *бета* - **Обновление ПО.** Обновляйте программы пакетно через winget, Chocolatey и Scoop. Windows. *бета* -### Файлы Файлы (5) +### Файлы Файлы (5) - **Дубликаты.** Найдите одинаковые файлы по хешу и безопасно освободите место. - **Массовое переименование.** Регулярные выражения, счётчики и смена регистра с предпросмотром перед применением. @@ -490,20 +490,20 @@ Firefox: **Настройки → Плагины → Расширение для - **Поиск файлов.** Мгновенный поиск через Everything на Windows, Spotlight на macOS или fd на Linux. - **Предотвращение сна.** Не давайте компьютеру уснуть во время долгих задач. -### Загрузки Загрузки (2) +### Загрузки Загрузки (2) - **Ускоренная загрузка.** Большие файлы в 16 соединений, докачка и контрольная сумма через aria2. - **Манифест HLS / DASH.** Вставьте `.m3u8` или `.mpd` с Referer и cookie. FFmpeg сохранит MP4. -### Автоматизация Автоматизация (1) +### Автоматизация Автоматизация (1) - **Авто-кликер.** Кликайте с точно заданной скоростью, с глобальной горячей клавишей, лимитами и случайными диапазонами. Windows, macOS и Linux. *бета* -### Телефон Телефон (1) +### Телефон Телефон (1) - **Отправить на телефон.** Файлы, ссылки и текст на сопряжённое устройство KDE Connect. -### ИИ ИИ (6) +### ИИ ИИ (6) - **Сравнение цен.** Стоимость одной и той же модели у разных провайдеров, с ценами из LiteLLM и models.dev. - **Расходы на ИИ.** Сколько OmniGet потратил на ИИ — по дням, моделям и задачам, из локального журнала. @@ -512,7 +512,7 @@ Firefox: **Настройки → Плагины → Расширение для - **API-ключи.** Локальное хранилище ключей и аккаунтов с проверкой соединения, балансом для OpenRouter, DeepSeek, SiliconFlow и New API и экспортом в Claude Code, Codex, Cherry Studio, opencode или файл `.env`. - **MCP-сервер.** Инструменты OmniGet, открытые по Model Context Protocol через локальный мост: 37 инструментов за тем же токеном, что использует расширение, с готовыми фрагментами конфигурации для Claude Code, Claude Desktop, Cursor, VS Code, Goose и Codex. Смотрите [OmniGet для ИИ-агентов](#omniget-для-ии-агентов-mcp-сервер-и-плагин-для-claude-code). *бета* -### CTF и анализ CTF и анализ (6) +### CTF и анализ CTF и анализ (6) Шесть небольших офлайн-утилит для задач capture-the-flag, домашних работ по форензике и моментов «что это за файл». @@ -561,7 +561,7 @@ Firefox: **Настройки → Плагины → Расширение для Marketplace OmniGet со списком плагинов Courses, Telegram и Convert: версия, автор, разрешения и переключатели

-### Courses Courses +### Courses Courses Войдите в **Hotmart**, **Udemy**, **Kiwify**, **Rocketseat** или **Meta-Analysis Academy** через окно браузера внутри приложения, с cookies, сохранёнными расширением, или по email и паролю там, где платформа это позволяет. OmniGet покажет ваши покупки, откроет оглавление курса, чтобы отметить нужные разделы (с подсказкой, сколько уроков защищено DRM и будет пропущено), и скачает все уроки и вложения, при желании со сквозной нумерацией. Hotmart использует актуальный вход через OIDC, так что всё работает после смены авторизации в 2026 году; бесплатные курсы и курсы, выдаваемые вне Hotmart Club, тоже показываются в списке. @@ -569,7 +569,7 @@ Firefox: **Настройки → Плагины → Расширение для Войдите по QR-коду или номеру телефона. Просматривайте все каналы и группы, где вы состоите, фильтруйте по фото, видео, документам или аудио, ищите файлы и скачивайте один элемент или весь чат со списком прогресса. -### Convert Convert +### Convert Convert Конвертация через FFmpeg с GPU-ускорением, если оно есть: контейнер, кодек, разрешение, битрейт и сжатие видео и аудио, без интернета. diff --git a/README_pt_br.md b/README_pt_br.md index 6fbb7a31..72162786 100644 --- a/README_pt_br.md +++ b/README_pt_br.md @@ -175,12 +175,12 @@ O OmniGet tem extratores nativos para as plataformas que as pessoas mais usam e | Categoria | Sites e formatos | |---|---| -| Cursos online Cursos online | Hotmart, Udemy, Kiwify, Rocketseat e Meta-Analysis Academy pelo plugin Courses. Todas as aulas, escolha de seções, anexos, continuar de onde parou. | -| Vídeo e áudio Vídeo e áudio | YouTube (vídeos, playlists, canais, live desde o início, capítulos, SponsorBlock), Instagram, TikTok, X/Twitter, Reddit, Twitch (VODs, clipes, ao vivo), Vimeo, Bluesky, Threads, Pinterest, Douyin | +| Cursos online Cursos online | Hotmart, Udemy, Kiwify, Rocketseat e Meta-Analysis Academy pelo plugin Courses. Todas as aulas, escolha de seções, anexos, continuar de onde parou. | +| Vídeo e áudio Vídeo e áudio | YouTube (vídeos, playlists, canais, live desde o início, capítulos, SponsorBlock), Instagram, TikTok, X/Twitter, Reddit, Twitch (VODs, clipes, ao vivo), Vimeo, Bluesky, Threads, Pinterest, Douyin | | Bilibili Bilibili, logado | 4K, HDR, Dolby Vision, Hi-Res sem perdas e Dolby Atmos conforme sua assinatura. Danmaku em XML, ASS ou JSON, arquivos NFO para Kodi e Jellyfin, modelos de nome, 11 tipos de URL incluindo bangumi, cursos, favoritos, assistir depois e histórico | -| Galerias de imagens Galerias de imagens | Galerias e perfis inteiros de mais de 250 sites via gallery-dl (DeviantArt, Pixiv, ArtStation, Flickr, Tumblr, Imgur, Kemono e outros) | -| Em lote Em lote | Cole vários links ou carregue um `.txt`, baixe subreddits inteiros, perfis do Reddit e do X, perfis do Instagram e do Pinterest | -| Arquivos e transferência Arquivos e transferência | Arquivos `.torrent` e magnets com cliente BitTorrent embutido, arquivos HTTP diretos, manifestos HLS e DASH, e transferência direta entre duas instalações do OmniGet com um código curto de palavras | +| Galerias de imagens Galerias de imagens | Galerias e perfis inteiros de mais de 250 sites via gallery-dl (DeviantArt, Pixiv, ArtStation, Flickr, Tumblr, Imgur, Kemono e outros) | +| Em lote Em lote | Cole vários links ou carregue um `.txt`, baixe subreddits inteiros, perfis do Reddit e do X, perfis do Instagram e do Pinterest | +| Arquivos e transferência Arquivos e transferência | Arquivos `.torrent` e magnets com cliente BitTorrent embutido, arquivos HTTP diretos, manifestos HLS e DASH, e transferência direta entre duas instalações do OmniGet com um código curto de palavras | | Telegram Telegram | Fotos, vídeos, arquivos e áudios de qualquer canal ou grupo em que você esteja, pelo plugin Telegram | Opções que você define uma vez e esquece: qualidade padrão, formato de áudio (MP3, M4A, Opus, FLAC ou WAV), idiomas e formato de legenda (SRT, VTT, ASS, embutida ou ao lado), thumbnail e metadados embutidos, modelo de nome de arquivo, organizar por plataforma, pular arquivos existentes, dividir por capítulos, limite de velocidade, downloads simultâneos, proxy. Regras mandam um canal ou host para a pasta e a qualidade que você escolher sem perguntar de novo. Canais seguidos são verificados em segundo plano e podem baixar novos vídeos automaticamente, com notificação na bandeja. @@ -262,7 +262,7 @@ Legenda de status: sem marca significa pronta, **beta** significa que funciona m - **Thumbnail real.** Os frames que a CDN já tem em 25, 50 e 75 por cento, em vez da capa clickbait. - **Forçar H.264.** Um interruptor na extensão do navegador que mantém o YouTube em H.264 em vez de VP9 e AV1, para máquinas que engasgam com codecs novos. -### Fala e legendas Fala e legendas (8) +### Fala e legendas Fala e legendas (8) - **Transcrever.** Áudio ou vídeo para legendas com whisper.cpp, offline. Modelos baixam sob demanda, aceleração Metal no macOS. - **Texto para fala.** Vozes naturais do Microsoft Edge, grátis, com arquivo de legenda sincronizado. @@ -271,7 +271,7 @@ Legenda de status: sem marca significa pronta, **beta** significa que funciona m - **Clonar voz**, **Criar voz** e **Isolar vocais** por uma instalação do VoiceStudio na sua máquina. *beta* - **Ditado.** Aperte um atalho global, fale, e o whisper digita o texto onde o cursor está. *beta* -### Edição de vídeo Edição de vídeo (6) +### Edição de vídeo Edição de vídeo (6) - **Cortar trecho.** Escolha um vídeo no disco e corte um pedaço. O resultado cai na fila de downloads. - **Converter.** Troque contêiner, codec ou resolução, ou comprima, pelo plugin Convert. @@ -343,7 +343,7 @@ Funciona sem login para tudo que é público. Cookies só são necessários para - **Temas e cores.** Personalize o cliente do Spotify com temas do Spicetify. *beta* - **Extensões.** Instale extensões e apps do Marketplace do Spicetify. *beta* -### PDF PDF (6) +### PDF PDF (6) - **Juntar.** Una vários PDFs em um, na ordem que quiser. - **Dividir.** Extraia páginas ou quebre um PDF em partes. @@ -352,7 +352,7 @@ Funciona sem login para tudo que é público. Cookies só são necessários para - **OCR.** Torne PDFs escaneados pesquisáveis. *beta* - **PDF seguro.** Reconstrua um PDF a partir de pixels para remover scripts e formulários. -### Documentos Documentos (5) +### Documentos Documentos (5) - **SlideShare para PDF.** Todos os slides no maior tamanho, montados em um PDF. - **Exportar Google Docs.** Docs, Slides e Sheets públicos em PDF, DOCX, PPTX ou XLSX. @@ -360,29 +360,29 @@ Funciona sem login para tudo que é público. Cookies só são necessários para - **Galerias de imagens.** Galerias e perfis inteiros de mais de 250 sites com gallery-dl. - **Scribd.** Salve livros legíveis em PDF usando a sua própria sessão. *planejada* -### Imagens Imagens (3) +### Imagens Imagens (3) - **Upscale.** Real-ESRGAN em qualquer GPU Vulkan, 2x, 3x ou 4x. *beta* - **Redimensionar imagens.** Em lote por largura, altura, encaixe ou porcentagem, convertendo o formato se quiser. - **OCR.** Copie o texto de imagens e slides. *beta* -### Arquivos Arquivos (4) +### Arquivos Arquivos (4) - **Duplicados.** Encontre arquivos idênticos por hash e libere espaço com segurança. - **Renomear em lote.** Regex, contadores e troca de caixa com prévia antes de aplicar. - **Encontrar arquivos.** Busca instantânea com Everything no Windows, Spotlight no macOS ou fd no Linux. - **Manter acordado.** Impeça o computador de dormir durante trabalhos longos. -### Downloads Downloads (2) +### Downloads Downloads (2) - **Download acelerado.** Arquivos grandes com 16 conexões, retomada e checksum via aria2. - **Manifesto HLS / DASH.** Cole um `.m3u8` ou `.mpd` com Referer e cookie. O FFmpeg salva um MP4. -### Celular Celular (1) +### Celular Celular (1) - **Enviar para o celular.** Arquivos, links e texto para um dispositivo KDE Connect pareado. -### Sistema Sistema (9, itens só para Windows marcados) +### Sistema Sistema (9, itens só para Windows marcados) - **Limpar caches.** Temporários, logs e caches de apps com regras por sistema. Você revisa a lista antes de qualquer coisa ser apagada. - **Analisador de disco.** O que ocupa espaço, em treemap e na lista dos maiores arquivos, com botão de mandar para a lixeira. @@ -394,11 +394,11 @@ Funciona sem login para tudo que é público. Cookies só são necessários para - **Limpador de registro.** Entradas órfãs, com backup `.reg` antes de remover. Windows. *beta* - **Atualizador de programas.** Atualize programas em lote via winget, Chocolatey e Scoop. Windows. *beta* -### Automação Automação (1) +### Automação Automação (1) - **Auto clicker.** Clique na velocidade exata que você definir, com atalho global, limites e intervalos aleatórios. Windows, macOS e Linux. *beta* -### IA IA (6) +### IA IA (6) - **Comparar preços.** O custo do mesmo modelo em vários provedores, com preços do LiteLLM e do models.dev. - **Gastos com IA.** Quanto o OmniGet gastou com IA, por dia, modelo e tarefa, a partir de um registro local. @@ -419,7 +419,7 @@ Plugins são bibliotecas Rust separadas, carregadas na inicialização. O OmniGe Marketplace do OmniGet listando os plugins Courses, Telegram e Convert com versão, autor, permissões e interruptores

-### Courses Courses +### Courses Courses Entre na **Hotmart**, **Udemy**, **Kiwify**, **Rocketseat** ou **Meta-Analysis Academy** por uma janela de navegador dentro do app, com cookies salvos pela extensão, ou com e-mail e senha onde a plataforma permite. O OmniGet lista suas compras, abre o sumário do curso para você marcar as seções que quer (avisando quantas aulas têm DRM e serão puladas) e baixa todas as aulas e anexos, com numeração contínua se quiser. A Hotmart usa o fluxo de login OIDC atual, então continua funcionando depois da mudança de autenticação de 2026, e cursos gratuitos e cursos entregues fora do Hotmart Club também aparecem na lista. @@ -427,7 +427,7 @@ Entre na **Hotmart**, **Udemy**, **Kiwify**, **Rocketseat** ou **Meta-Analysis A Entre com QR code ou número de telefone. Navegue por todos os canais e grupos em que está, filtre por foto, vídeo, documento ou áudio, busque arquivos e baixe um item ou o chat inteiro com lista de progresso. -### Convert Convert +### Convert Convert Conversões com FFmpeg e aceleração por GPU quando a máquina tem: contêiner, codec, resolução, bitrate e compressão de vídeo e áudio, sem internet. diff --git a/README_zh_CN.md b/README_zh_CN.md index 75bb2f82..42da3d00 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -175,12 +175,12 @@ OmniGet 为最常用的平台写了原生提取器,其余的交给 [yt-dlp](ht | 类别 | 网站与格式 | |---|---| -| 在线课程 在线课程 | 通过 Courses 插件支持 Hotmart、Udemy、Kiwify、Rocketseat 和 Meta-Analysis Academy。全部课时、章节选择、附件、从上次位置继续。 | -| 视频与音频 视频与音频 | YouTube(视频、播放列表、频道、从头录直播、章节、SponsorBlock)、Instagram、TikTok、X/Twitter、Reddit、Twitch(录像、剪辑、直播)、Vimeo、Bluesky、Threads、Pinterest、抖音 | +| 在线课程 在线课程 | 通过 Courses 插件支持 Hotmart、Udemy、Kiwify、Rocketseat 和 Meta-Analysis Academy。全部课时、章节选择、附件、从上次位置继续。 | +| 视频与音频 视频与音频 | YouTube(视频、播放列表、频道、从头录直播、章节、SponsorBlock)、Instagram、TikTok、X/Twitter、Reddit、Twitch(录像、剪辑、直播)、Vimeo、Bluesky、Threads、Pinterest、抖音 | | 哔哩哔哩 哔哩哔哩,登录后 | 按你的会员等级提供 4K、HDR、杜比视界、Hi-Res 无损和杜比全景声。弹幕导出为 XML、ASS 或 JSON,为 Kodi 和 Jellyfin 生成 NFO,自定义命名模板,支持 11 种链接类型,包括番剧、课程、收藏夹、稍后再看和历史记录 | -| 图片画廊 图片画廊 | 通过 gallery-dl 下载 250+ 网站的整个画廊和主页(DeviantArt、Pixiv、ArtStation、Flickr、Tumblr、Imgur、Kemono 等) | -| 批量 批量 | 粘贴多条链接或载入 `.txt`,下载整个 subreddit、Reddit 和 X 的主页、Instagram 和 Pinterest 的主页 | -| 文件与传输 文件与传输 | 用内置 BitTorrent 客户端下载 `.torrent` 和磁力链接,HTTP 直链,HLS 和 DASH 清单,以及两台装了 OmniGet 的电脑之间用一串短口令互传文件 | +| 图片画廊 图片画廊 | 通过 gallery-dl 下载 250+ 网站的整个画廊和主页(DeviantArt、Pixiv、ArtStation、Flickr、Tumblr、Imgur、Kemono 等) | +| 批量 批量 | 粘贴多条链接或载入 `.txt`,下载整个 subreddit、Reddit 和 X 的主页、Instagram 和 Pinterest 的主页 | +| 文件与传输 文件与传输 | 用内置 BitTorrent 客户端下载 `.torrent` 和磁力链接,HTTP 直链,HLS 和 DASH 清单,以及两台装了 OmniGet 的电脑之间用一串短口令互传文件 | | Telegram Telegram | 通过 Telegram 插件下载你所在的任何频道或群组里的照片、视频、文件和音频 | 设置一次就不用再管的选项:默认清晰度、纯音频格式(MP3、M4A、Opus、FLAC 或 WAV)、字幕语言和格式(SRT、VTT、ASS,内嵌或外挂)、封面和元数据嵌入、文件名模板、按平台分文件夹、跳过已有文件、按章节切分、限速、并发数、代理。规则可以把某个频道或域名固定送到指定文件夹和清晰度,不再每次询问。关注的频道会在后台检查,可以自动下载新视频并在托盘通知。 @@ -262,7 +262,7 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 - **真实截图。** CDN 已有的 25%、50%、75% 位置画面帖,而不是标题党封面。 - **强制 H.264。** 浏览器扩展里的一个开关,让 YouTube 保持使用 H.264 而不是 VP9 和 AV1,给新编码播放卡顿的机器用。 -### 语音与字幕 语音与字幕(8) +### 语音与字幕 语音与字幕(8) - **转写。** 用 whisper.cpp 离线把音频或视频转成字幕。模型按需下载,macOS 上用 Metal 加速。 - **文字转语音。** 微软 Edge 的自然语音,免费,附带同步字幕文件。 @@ -271,7 +271,7 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 - **声音克隆**、**声音设计** 和 **人声分离**,通过本机安装的 VoiceStudio 完成。*beta* - **听写。** 按下全局快捷键说话,whisper 把文字直接输入到光标所在处。*beta* -### 视频编辑 视频编辑(6) +### 视频编辑 视频编辑(6) - **剪片段。** 选一个本地视频,剪出一段。结果进入下载队列。 - **转换。** 通过 Convert 插件更换容器、编码、分辨率或压缩。 @@ -343,7 +343,7 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 - **主题与配色。** 用 Spicetify 主题定制 Spotify 客户端。*beta* - **扩展。** 从 Spicetify Marketplace 安装扩展和自定义应用。*beta* -### PDF PDF(6) +### PDF PDF(6) - **合并。** 按你选的顺序把多个 PDF 合成一个。 - **拆分。** 提取页面,或把 PDF 拆成几份。 @@ -352,7 +352,7 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 - **OCR。** 让扫描版 PDF 可以搜索。*beta* - **安全 PDF。** 从像素重建 PDF,去掉脚本和表单。 -### 文档 文档(5) +### 文档 文档(5) - **SlideShare 转 PDF。** 每一页以最大尺寸抓取,合成一个 PDF。 - **Google 文档导出。** 公开的 Docs、Slides、Sheets 导出为 PDF、DOCX、PPTX 或 XLSX。 @@ -360,29 +360,29 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 - **图片画廊。** 通过 gallery-dl 下载 250+ 网站的整个画廊和主页。 - **Scribd。** 用你自己的会话把可阅读的书存成 PDF。*计划中* -### 图片 图片(3) +### 图片 图片(3) - **超分放大。** 在任何 Vulkan GPU 上用 Real-ESRGAN 放大 2 倍、3 倍或 4 倍。*beta* - **批量缩放。** 按宽、高、适配或百分比批量缩放,可顺带转换格式。 - **OCR。** 从图片和幻灯片里把文字复制出来。*beta* -### 文件 文件(4) +### 文件 文件(4) - **重复文件。** 按哈希找出完全相同的文件,安全释放空间。 - **批量重命名。** 正则、计数器和大小写转换,应用前有预览。 - **查找文件。** 即时搜索:Windows 上用 Everything,macOS 上用 Spotlight,Linux 上用 fd。 - **保持唤醒。** 长任务期间阻止电脑休眠。 -### 下载 下载(2) +### 下载 下载(2) - **加速下载。** 用 aria2 以 16 个连接下载大文件,支持续传和校验。 - **HLS / DASH 清单。** 粘贴 `.m3u8` 或 `.mpd`,附上 Referer 和 Cookie,FFmpeg 保存为 MP4。 -### 手机 手机(1) +### 手机 手机(1) - **发送到手机。** 把文件、链接和文字发到已配对的 KDE Connect 设备。 -### 系统 系统(9,仅 Windows 的项目已标注) +### 系统 系统(9,仅 Windows 的项目已标注) - **清理缓存。** 按各系统的规则清理临时文件、日志和应用缓存。删除前先给你看清单。 - **磁盘分析。** 用树状图和最大文件列表看清空间去哪了,一键移到废纸篓。 @@ -394,11 +394,11 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 - **注册表清理。** 清理孤立项,删除前先备份 `.reg`。Windows。*beta* - **软件更新器。** 通过 winget、Chocolatey 和 Scoop 批量更新程序。Windows。*beta* -### 自动化 自动化(1) +### 自动化 自动化(1) - **自动点击器。** 按你设定的速度点击,支持全局快捷键、次数上限和随机间隔。Windows、macOS 和 Linux。*beta* -### AI AI(6) +### AI AI(6) - **比较价格。** 同一模型在不同服务商的价格,数据来自 LiteLLM 和 models.dev。 - **AI 花费。** OmniGet 在 AI 上花了多少,按天、模型和任务统计,来自本地账本。 @@ -419,7 +419,7 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 OmniGet 的 Marketplace,列出 Courses、Telegram 和 Convert 插件,显示版本、作者、权限和启用开关

-### Courses Courses +### Courses Courses 通过应用内的浏览器窗口登录 **Hotmart**、**Udemy**、**Kiwify**、**Rocketseat** 或 **Meta-Analysis Academy**,也可以使用扩展保存的 Cookie,或在平台允许时直接用邮箱和密码。OmniGet 列出你购买的课程,打开课程大纲让你勾选想要的章节(并告诉你有多少课时受 DRM 保护、会被跳过),然后下载全部课时和附件,需要的话可以连续编号。Hotmart 使用当前的 OIDC 登录流程,所以在 Hotmart 2026 年更换认证方式之后仍然可用,免费课程和在 Hotmart Club 之外交付的课程也会列出来。 @@ -427,7 +427,7 @@ Tools 是 OmniGet 里长到下载之外的那部分。每个方块是一项工 用二维码或手机号登录。浏览你所在的所有频道和群组,按照片、视频、文档或音频筛选,搜索文件,下载单个条目或整个聊天并显示进度列表。 -### Convert Convert +### Convert Convert FFmpeg 转换,机器支持时使用 GPU 加速:视频和音频的容器、编码、分辨率、码率和压缩,无需联网。