Skip to content

Commit

Permalink
feat: add HTTP Proxy setting
Browse files Browse the repository at this point in the history
  • Loading branch information
Kosette committed Apr 6, 2024
1 parent 020bf4d commit d1dd4ee
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 52 deletions.
File renamed without changes.
4 changes: 4 additions & 0 deletions moe.tsuna.tsukimi.gschema.xml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
<default>true</default>
<summary>Default switch state</summary>
</key>
<key name="http-proxy" type="s">
<default>""</default>
<summary>Default http proxy state</summary>
</key>
<key name="background-height" type="i">
<default>700</default>
<summary>Default background height</summary>
Expand Down
5 changes: 5 additions & 0 deletions resources/ui/settings.ui
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@
<property name="title" translatable="yes">Show Playing Window Immediately</property>
</object>
</child>
<child>
<object class="AdwEntryRow" id="httpproxycontrol">
<property name="title" translatable="yes">HTTP Proxy</property>
</object>
</child>
<style>
<class name="boxed-list" />
</style>
Expand Down
17 changes: 7 additions & 10 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ use uuid::Uuid;

pub const VERSION: &str = "0.3.0";

#[derive(Serialize, Debug, Deserialize, Default)]
#[derive(Serialize, Debug, Deserialize)]
pub struct Config {
pub domain: String,
pub username: String,
pub password: String,
pub port: String,
pub user_id: String,
pub access_token: String,
pub proxy: String,
}

fn generate_uuid() -> String {
Expand All @@ -40,31 +39,30 @@ pub fn load_cfg() {
env::set_var("EMBY_PORT", &config.port);
env::set_var("EMBY_USER_ID", &config.user_id);
env::set_var("EMBY_ACCESS_TOKEN", &config.access_token);
env::set_var("EMBY_PROXY", &config.proxy);

let uuid = generate_uuid();
env::set_var("UUID", &uuid);

let mpv_config_file = env::current_dir().unwrap().parent().unwrap().join("mpv");
let mpv_config = if mpv_config_file.exists() {
let mpv_config_dir = env::current_dir().unwrap().parent().unwrap().join("mpv");
let mpv_config = if mpv_config_dir.join("mpv.conf").exists() {
"true"
} else {
"false"
};
env::set_var("MPV_CONFIG", mpv_config);
env::set_var("MPV_CONFIG_DIR", mpv_config_file.display().to_string());
env::set_var("MPV_CONFIG_DIR", mpv_config_dir.display().to_string());
} else {
let uuid = generate_uuid();
env::set_var("UUID", &uuid);

let mpv_config_file = env::current_dir().unwrap().parent().unwrap().join("mpv");
let mpv_config = if mpv_config_file.exists() {
let mpv_config_dir = env::current_dir().unwrap().parent().unwrap().join("mpv");
let mpv_config = if mpv_config_dir.join("mpv.conf").exists() {
"true"
} else {
"false"
};
env::set_var("MPV_CONFIG", mpv_config);
env::set_var("MPV_CONFIG_DIR", mpv_config_file.display().to_string());
env::set_var("MPV_CONFIG_DIR", mpv_config_dir.display().to_string());
};
}

Expand All @@ -76,7 +74,6 @@ pub fn set_config() -> Config {
port: env::var("EMBY_PORT").unwrap(),
user_id: env::var("EMBY_USER_ID").unwrap(),
access_token: env::var("EMBY_ACCESS_TOKEN").unwrap(),
proxy: env::var("EMBY_PROXY").unwrap(),
};
config
}
Expand Down
14 changes: 8 additions & 6 deletions src/ui/mpv/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,24 @@ pub fn play(url: String, suburl: Option<String>, name: Option<String>, back: &Ba
init.set_property("force-window", "immediate")?;
}

let proxy = settings.string("http-proxy");
if settings.string("http-proxy").is_empty() {
()
} else {
init.set_property("http-proxy", proxy.as_str())?;
}

let config_path = env::var("MPV_CONFIG_DIR").unwrap();
if env::var("MPV_CONFIG").unwrap() == "true" {
init.set_property("config-dir", config_path)?;
} else {
()
}
if env::var("EMBY_PROXY").unwrap().is_empty() {
()
} else {
init.set_property("http-proxy", env::var("EMBY_PROXY").unwrap())?;
}

Ok(())
})
.unwrap();
mpv.set_property("volume", 75)?;
mpv.set_property("volume", 85)?;

let mut ev_ctx = mpv.create_event_context();
ev_ctx.disable_deprecated_events()?;
Expand Down
79 changes: 43 additions & 36 deletions src/ui/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,14 @@ use std::time::Duration;
use tokio::runtime::{self, Runtime};
use toml::to_string;

#[derive(Serialize, Debug, Deserialize, Default)]
#[derive(Serialize, Debug, Deserialize)]
pub struct Config {
pub domain: String,
pub username: String,
pub password: String,
pub port: String,
pub user_id: String,
pub access_token: String,
pub proxy: String,
}

pub fn runtime() -> &'static Runtime {
Expand Down Expand Up @@ -90,7 +89,6 @@ pub async fn login(
port,
user_id: user_id.to_string(),
access_token: access_token.to_string(),
..Default::default()
};
let data = to_string(&config).unwrap();
let path = env::current_dir()
Expand Down Expand Up @@ -427,7 +425,7 @@ pub(crate) async fn resume() -> Result<Vec<Resume>, Error> {
("EnableImageTypes", "Primary,Backdrop,Thumb"),
("ImageTypeLimit", "1"),
("MediaTypes", "Video"),
("Limit", "16"),
("Limit", "18"),
("X-Emby-Client", "Tsukimi"),
("X-Emby-Device-Name", device_name),
("X-Emby-Device-Id", device_id),
Expand Down Expand Up @@ -774,7 +772,7 @@ pub async fn get_latest(
let device_name = &get_device_name();
let device_id = &env::var("UUID").unwrap();
let params = Box::new([
("Limit", "16"),
("Limit", "18"),
(
"Fields",
"BasicSyncInfo,CanDelete,PrimaryImageAspectRatio,ProductionYear",
Expand Down Expand Up @@ -923,58 +921,67 @@ pub async fn positionstop(back: Back) {
.unwrap();
}

pub async fn playstart(back: Back) {
let tick = back.tick.to_string();
let server_info = config::set_config();
let client = ReqClient::add_proxy();
let url = format!(
"{}:{}/emby/Sessions/Playing",
server_info.domain, server_info.port
);

let device_name = &get_device_name();
let device_id = &env::var("UUID").unwrap();
let params = Box::new([
("X-Emby-Client-Version", "0.3.0"),
("X-Emby-Device-Name", device_name),
("X-Emby-Device-Id", device_id),
("X-Emby-Token", &server_info.access_token),
("X-Emby-Language", "zh-cn"),
("reqformat", "json"),
]);
let profile = serde_json::json!({"VolumeLevel":100,"IsMuted":false,"IsPaused":false,"RepeatMode":"RepeatNone","SubtitleOffset":0,"PlaybackRate":1,"MaxStreamingBitrate":4000000,"PositionTicks":tick,"PlaybackStartTimeTicks":0,"SubtitleStreamIndex":1,"AudioStreamIndex":1,"BufferedRanges":[],"PlayMethod":"DirectStream","PlaySessionId":back.playsessionid,"MediaSourceId":back.mediasourceid,"CanSeek":true,"ItemId":back.id,"PlaylistIndex":0,"PlaylistLength":23,"NextMediaType":"Video"});
client
.post(&url)
.query(&params)
.json(&profile)
.send()
.await
.unwrap();
}

fn get_cache_dir() -> PathBuf {
let path = env::current_dir().unwrap().parent().unwrap().join("cache");
return path;
}

pub struct ReqClient;

use crate::APP_ID;
use gtk::prelude::SettingsExt;

impl ReqClient {
pub fn new() -> reqwest::Client {
return reqwest::Client::new();
}

pub fn add_proxy() -> reqwest::Client {
let proxy_setting = env::var("EMBY_PROXY").unwrap();
if proxy_setting.is_empty() {
let settings = gtk::gio::Settings::new(APP_ID);

let proxy_setting = settings.string("http-proxy");
// let proxy_setting = env::var("EMBY_PROXY").unwrap();
let proxy_str = proxy_setting.as_str();
if proxy_str.is_empty() {
// println!("no proxy set");
return reqwest::Client::new();
} else {
let proxy = reqwest::Proxy::all(&proxy_setting).expect("failed to find proxy");
let proxy = reqwest::Proxy::all(proxy_str).expect("failed to find proxy");

// println!("now using proxy: {}", proxy_setting);
// println!("now using proxy: {}", proxy_str);
return reqwest::Client::builder()
.proxy(proxy)
.build()
.expect("failed to initialize client");
}
}
}

pub async fn playstart(back: Back) {
let tick = back.tick.to_string();
let server_info = config::set_config();
let client = ReqClient::add_proxy();
let url = format!(
"{}:{}/emby/Sessions/Playing",
server_info.domain, server_info.port
);

let params = [
("X-Emby-Client-Version", "0.3.0"),
("X-Emby-Device-Name", &get_device_name()),
("X-Emby-Device-Id", &env::var("UUID").unwrap()),
("X-Emby-Token", &server_info.access_token),
("X-Emby-Language", "zh-cn"),
("reqformat", "json"),
];
let profile = serde_json::json!({"VolumeLevel":100,"IsMuted":false,"IsPaused":false,"RepeatMode":"RepeatNone","SubtitleOffset":0,"PlaybackRate":1,"MaxStreamingBitrate":4000000,"PositionTicks":tick,"PlaybackStartTimeTicks":0,"SubtitleStreamIndex":1,"AudioStreamIndex":1,"BufferedRanges":[],"PlayMethod":"DirectStream","PlaySessionId":back.playsessionid,"MediaSourceId":back.mediasourceid,"CanSeek":true,"ItemId":back.id,"PlaylistIndex":0,"PlaylistLength":23,"NextMediaType":"Video"});
client
.post(&url)
.query(&params)
.json(&profile)
.send()
.await
.unwrap();
}
14 changes: 14 additions & 0 deletions src/ui/widgets/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ mod imp {
pub spinrow: TemplateChild<adw::SpinRow>,
#[template_child]
pub forcewindowcontrol: TemplateChild<adw::SwitchRow>,
#[template_child]
pub httpproxycontrol: TemplateChild<adw::EntryRow>,
}

// The central trait for subclassing a GObject
Expand Down Expand Up @@ -54,6 +56,7 @@ mod imp {
obj.set_spin();
obj.set_fullscreen();
obj.set_forcewindow();
obj.set_httpproxy();
}
}

Expand Down Expand Up @@ -145,4 +148,15 @@ impl SettingsPage {
}),
);
}

pub fn set_httpproxy(&self) {
let imp = imp::SettingsPage::from_obj(self);
let settings = gio::Settings::new(APP_ID);
imp.httpproxycontrol
.set_text(settings.string("http-proxy").as_str());
imp.httpproxycontrol
.connect_text_notify(glib::clone!(@weak self as obj => move |entry| {
settings.set_string("http-proxy", entry.text().as_str()).unwrap();
}));
}
}

0 comments on commit d1dd4ee

Please sign in to comment.