소스 검색

Allow to open or save download links

Johannes Zellner 4 달 전
부모
커밋
7c598ba5e1
2개의 변경된 파일과 218개의 추가작업 그리고 4개의 파일을 삭제
  1. 1 1
      Cargo.toml
  2. 217 3
      src/main.rs

+ 1 - 1
Cargo.toml

@@ -5,7 +5,7 @@ edition = "2024"
 
 [dependencies]
 clap = { version = "4.5", features = ["derive"] }
-gtk4 = "0.11.1"
+gtk4 = { version = "0.11.1", features = ["v4_10"] }
 libadwaita = { version = "0.9.1", features = ["v1_9"] }
 scraper = "0.22"
 sha2 = "0.10"

+ 217 - 3
src/main.rs

@@ -5,6 +5,7 @@
 mod desktop_install;
 
 use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
 
 use desktop_install::LauncherIcon;
 
@@ -26,9 +27,10 @@ use gtk4::gdk::prelude::{DeviceExt, SeatExt, ToplevelExt};
 use gtk4::gdk;
 use webkit6::prelude::*;
 use webkit6::{
-    CookieAcceptPolicy, CookiePersistentStorage, NavigationAction, NavigationPolicyDecision,
-    NavigationType, NetworkSession, PolicyDecisionType, UserContentInjectedFrames,
-    UserContentManager, UserScript, UserScriptInjectionTime, WebView,
+    CookieAcceptPolicy, CookiePersistentStorage, NavigationAction,
+    NavigationPolicyDecision, NavigationType, NetworkSession, PolicyDecisionType,
+    ResponsePolicyDecision, UserContentInjectedFrames, UserContentManager, UserScript,
+    UserScriptInjectionTime, WebView,
 };
 
 /// JavaScript `window.webkit.messageHandlers.<name>` must match this identifier.
@@ -162,6 +164,10 @@ fn navigation_targets_blank_frame(action: &NavigationAction) -> bool {
 /// Extract the origin (scheme + host + port) from a URL.
 fn url_origin(url: &str) -> Option<String> {
     let parsed = url::Url::parse(url).ok()?;
+    if parsed.scheme() == "blob" {
+        let inner = url.strip_prefix("blob:")?;
+        return url_origin(inner);
+    }
     let scheme = parsed.scheme();
     let host = parsed.host_str()?;
     let port = parsed.port_or_known_default()?;
@@ -178,6 +184,10 @@ fn is_same_origin(url_a: &str, url_b: &str) -> bool {
 
 /// Open a URI in the system's default browser.
 fn open_in_system_browser(uri: &str) {
+    let scheme = uri.split(':').next().unwrap_or("");
+    if !matches!(scheme, "http" | "https" | "ftp") {
+        return;
+    }
     if let Err(e) = gtk4::gio::AppInfo::launch_default_for_uri(uri, Option::<&gtk4::gio::AppLaunchContext>::None) {
         eprintln!("appiphany: failed to open URI in system browser: {}", e);
     }
@@ -199,6 +209,16 @@ fn wire_webview_window_policy(
     let initial_url_for_create_2 = initial_url.clone();
 
     webview.connect_decide_policy(move |w, decision, decision_type| {
+        if decision_type == PolicyDecisionType::Response {
+            if let Some(rpd) = decision.dynamic_cast_ref::<ResponsePolicyDecision>() {
+                if !rpd.is_mime_type_supported() && rpd.is_main_frame_main_resource() {
+                    decision.download();
+                    return true;
+                }
+            }
+            return false;
+        }
+
         let Some(nav_decision) = decision.dynamic_cast_ref::<NavigationPolicyDecision>() else {
             return false;
         };
@@ -354,6 +374,200 @@ fn network_session_for_app(app: &impl IsA<glib::Object>) -> NetworkSession {
             return p.as_ref().clone();
         }
         let session = build_persistent_network_session();
+
+        session.connect_download_started(|_session, download| {
+            let ctx: Arc<
+                Mutex<
+                    Option<(
+                        PathBuf,
+                        String,
+                    )>,
+                >,
+            > = Arc::new(Mutex::new(None));
+
+            let ctx_dd = ctx.clone();
+            download.connect_decide_destination(
+                move |dl, suggested_filename| {
+                    let filename = suggested_filename.to_string();
+                    let temp_dir = std::env::temp_dir().join("appiphany-downloads");
+                    std::fs::create_dir_all(&temp_dir).ok();
+                    let dest_path = temp_dir.join(&filename);
+
+                    if let Some(dest) = dest_path.to_str() {
+                        dl.set_destination(dest);
+                        dl.set_allow_overwrite(true);
+                    }
+
+                    *ctx_dd.lock().unwrap() = Some((
+                        dest_path.clone(),
+                        filename.clone(),
+                    ));
+
+                    let action_arc: Arc<Mutex<Option<String>>> =
+                        Arc::new(Mutex::new(None));
+
+                    {
+                        let ctx_fin = ctx_dd.clone();
+                        let action_fin = action_arc.clone();
+                        dl.connect_finished(move |_| {
+                            let state = ctx_fin.lock().unwrap();
+                            if let Some((ref path, ref name)) = *state {
+                                eprintln!("appiphany: download finished \"{name}\" -> {:?}", path);
+                                let act = action_fin.lock().unwrap().clone();
+                                if act.as_deref() == Some("open") {
+                                    let file = gtk4::gio::File::for_path(path);
+                                    match gtk4::gio::AppInfo::launch_default_for_uri(
+                                        &file.uri(),
+                                        Option::<&gtk4::gio::AppLaunchContext>::None,
+                                    ) {
+                                        Ok(_) => eprintln!("appiphany: opened {:?}", path),
+                                        Err(e) => eprintln!(
+                                            "appiphany: failed to open {:?}: {}",
+                                            path, e
+                                        ),
+                                    }
+                                } else if act.as_deref() == Some("cancel") {
+                                    let _ = std::fs::remove_file(path);
+                                }
+                            }
+                        });
+                    }
+
+                    {
+                        let ctx_fail = ctx_dd.clone();
+                        let name = filename.clone();
+                        dl.connect_failed(move |_, err| {
+                            eprintln!(
+                                "appiphany: download \"{}\" failed: {}",
+                                name, err
+                            );
+                            if let Some((ref path, _)) = *ctx_fail.lock().unwrap() {
+                                let _ = std::fs::remove_file(path);
+                            }
+                        });
+                    }
+
+                    let parent_win = dl
+                        .web_view()
+                        .and_then(|wv| wv.root())
+                        .and_then(|r| r.dynamic_cast::<gtk4::Window>().ok());
+
+                    let ctx_dialog = ctx_dd.clone();
+                    let action_dialog = action_arc.clone();
+                    glib::idle_add_local(move || {
+                        let (dest_path_d, filename_d) = {
+                            let state = ctx_dialog.lock().unwrap();
+                            state
+                                .clone()
+                                .unwrap_or_else(|| {
+                                    (
+                                        PathBuf::from("/tmp/appiphany-downloads/download"),
+                                        String::from("download"),
+                                    )
+                                })
+                        };
+
+                        eprintln!(
+                            "appiphany: download dialog \"{}\"",
+                            filename_d
+                        );
+
+                        let dialog = adw::AlertDialog::new(
+                            Some("Download"),
+                            Some(&format!(
+                                "What would you like to do with \"{}\"?",
+                                filename_d
+                            )),
+                        );
+                        dialog.add_response("open", "Open");
+                        dialog.add_response("save", "Save As...");
+                        dialog.add_response("cancel", "Cancel");
+                        dialog.set_default_response(Some("open"));
+                        dialog.set_close_response("cancel");
+
+                        {
+                            let action = action_dialog.clone();
+                            let path = dest_path_d.clone();
+                            dialog.connect_response(Some("open"), move |_, _| {
+                                *action.lock().unwrap() = Some("open".into());
+                                if path.exists() {
+                                    let file = gtk4::gio::File::for_path(&path);
+                                    match gtk4::gio::AppInfo::launch_default_for_uri(
+                                        &file.uri(),
+                                        Option::<&gtk4::gio::AppLaunchContext>::None,
+                                    ) {
+                                        Ok(_) => eprintln!("appiphany: opened {:?}", path),
+                                        Err(e) => {
+                                            eprintln!(
+                                                "appiphany: failed to open {:?}: {}",
+                                                path, e
+                                            )
+                                        }
+                                    }
+                                }
+                            });
+                        }
+
+                        {
+                            let action = action_dialog.clone();
+                            let path = dest_path_d.clone();
+                            let name = filename_d.clone();
+                            dialog.connect_response(Some("save"), move |_, _| {
+                                *action.lock().unwrap() = Some("save".into());
+                                let file_dialog = gtk4::FileDialog::builder()
+                                    .title("Save File")
+                                    .initial_name(&name)
+                                    .build();
+                                let path2 = path.clone();
+                                let name2 = name.clone();
+                                let action2 = action.clone();
+                                file_dialog.save(
+                                    None::<&gtk4::Window>,
+                                    None::<&gtk4::gio::Cancellable>,
+                                    move |result| match result {
+                                        Ok(file) => {
+                                            let uri = file.uri();
+                                            eprintln!(
+                                                "appiphany: save \"{name2}\" -> \"{}\"",
+                                                uri
+                                            );
+                                            if let Some(chosen) = file.path() {
+                                                let _ = std::fs::copy(&path2, &chosen);
+                                                eprintln!(
+                                                    "appiphany: saved {:?}",
+                                                    chosen
+                                                );
+                                            }
+                                            let _ = std::fs::remove_file(&path2);
+                                        }
+                                        Err(_) => {
+                                            eprintln!("appiphany: save cancelled");
+                                            *action2.lock().unwrap() = Some("cancel".into());
+                                            let _ = std::fs::remove_file(&path2);
+                                        }
+                                    },
+                                );
+                            });
+                        }
+
+                        {
+                            let action = action_dialog.clone();
+                            let path = dest_path_d.clone();
+                            dialog.connect_response(Some("cancel"), move |_, _| {
+                                *action.lock().unwrap() = Some("cancel".into());
+                                eprintln!("appiphany: download cancelled");
+                                let _ = std::fs::remove_file(&path);
+                            });
+                        }
+
+                        dialog.present(parent_win.as_ref());
+                        glib::ControlFlow::Break
+                    });
+                    true
+                },
+            );
+        });
+
         obj.set_data(APP_NETWORK_SESSION_KEY, session.clone());
         session
     }