Skip to content

Commit

Permalink
feat: Pass server url to stremio-web
Browse files Browse the repository at this point in the history
Signed-off-by: Lachezar Lechev <[email protected]>
  • Loading branch information
elpiel committed Jul 21, 2023
1 parent aa8a1dc commit 9d8c19c
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 24 deletions.
30 changes: 20 additions & 10 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,10 @@ use crate::{
app::tray_menu::ServerAction,
args::Args,
config::{DATA_DIR, STREMIO_URL, UPDATE_ENDPOINT},
server::{Info, Server},
server::{self, Info, Server, DEFAULT_SERVER_URL},
updater::Updater,
};

use crate::server;

use self::tray_menu::{
MenuEvent, TrayMenu, OPEN_MENU, QUIT_MENU, RESTART_SERVER_MENU, START_SERVER_MENU,
STOP_SERVER_MENU,
Expand Down Expand Up @@ -194,7 +192,8 @@ impl Application {
.start()
.await
.context("Failed to start Server")?;
self.server.run_logger();
let (server_url_sender, server_url_receiver) = tokio::sync::watch::channel(None);
self.server.run_logger(server_url_sender);

let (action_sender, action_receiver) = tokio::sync::watch::channel(None);
let (status_sender, status_receiver) = tokio::sync::mpsc::channel(5);
Expand All @@ -210,7 +209,7 @@ impl Application {
info: Info {
config: server_info.config.clone(),
version: server_info.version,
server_url: server_info.server_url,
base_url: server_info.base_url,
},
},
};
Expand All @@ -230,11 +229,22 @@ impl Application {

match event {
Event::MenuEvent { menu_id, .. } if menu_id == *OPEN_MENU => {
// FIXME: call with the app's server_url from the command!
StremioWeb::OpenWeb { server_url: None }.open()
// no need to pass the url to stremio-web if it's the default one.
let server_url =
server_url_receiver
.borrow()
.to_owned()
.and_then(|server_url| {
if *DEFAULT_SERVER_URL == server_url {
None
} else {
Some(server_url)
}
});

StremioWeb::OpenWeb { server_url }.open()
}
Event::MenuEvent { menu_id, .. } if menu_id == *QUIT_MENU => {
// drop(tray_menu);
*control_flow = ControlFlow::Exit;
}
Event::LoopDestroyed => {
Expand Down Expand Up @@ -284,7 +294,7 @@ impl Application {
None => ServerTrayStatus::Stopped,
};

debug!("Server status was update (every {}s)", Self::SERVER_STATUS_EVERY.as_secs());
debug!("Server status is updated (every {}s)", Self::SERVER_STATUS_EVERY.as_secs());

status
},
Expand Down Expand Up @@ -378,6 +388,7 @@ impl Application {
pub struct AddonUrl {
url: Url,
}

impl FromStr for AddonUrl {
type Err = anyhow::Error;

Expand Down Expand Up @@ -414,7 +425,6 @@ impl Debug for AddonUrl {
}

pub enum StremioWeb {
// todo: replace with url
Addon(AddonUrl),
OpenWeb { server_url: Option<Url> },
}
Expand Down
2 changes: 1 addition & 1 deletion src/app/tray_menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ impl TrayMenu {
crate::Application::SERVER_STATUS_EVERY.as_secs()
);

let server_status: String = match status.unwrap_or_default().server_js {
let server_status = match status.unwrap_or_default().server_js {
ServerTrayStatus::Stopped => format!("Server is not running{debug}"),
ServerTrayStatus::Restarting => format!("Server is restarting{debug}"),
ServerTrayStatus::Running { info } => {
Expand Down
41 changes: 30 additions & 11 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ use anyhow::{bail, Context, Error};
use futures::executor::block_on;
use futures_util::TryFutureExt;
use log::{error, info, trace};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use tokio::{
io::{AsyncBufReadExt, BufReader},
process::{Child, ChildStdout, Command},
sync::Mutex,
sync::{watch, Mutex},
time::sleep,
};
use url::Url;
Expand All @@ -22,6 +23,11 @@ const CREATE_NO_WINDOW: u32 = 0x08000000;
/// Wait 3 seconds for the server to start
const WAIT_AFTER_START: Duration = Duration::from_secs(3);

/// Waits 6 seconds for the server to fully stop
const WAIT_FOR_FULL_STOP: Duration = Duration::from_secs(6);

pub const DEFAULT_SERVER_URL: Lazy<Url> = Lazy::new(|| "http://127.0.0.1:11470".parse().unwrap());

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Info {
pub config: Config,
Expand All @@ -33,10 +39,13 @@ pub struct Info {
/// - "4.20.2"
/// - etc.
pub version: String,

/// The server base url in the local network.
///
/// # Examples:
///
/// - `http://127.0.0.1:11470`
pub server_url: Url,
/// - `http://192.168.0.215:11470`
pub base_url: Url,
}

#[derive(Debug)]
Expand Down Expand Up @@ -115,7 +124,7 @@ impl Server {
let info = Info {
config: self.inner.config.clone(),
version: settings.values.server_version,
server_url: settings.base_url,
base_url: settings.base_url,
};
// set new child process
*status_guard = ServerStatus::running(info.clone(), new_process);
Expand Down Expand Up @@ -230,20 +239,22 @@ impl Server {
}

pub async fn restart(&self) -> anyhow::Result<Info> {
if let Err(err) = self.stop().await {
error!("Restarting (stop): {err}")
match self.stop().await {
Ok(_) => {
// wait for the server to fully stop
sleep(WAIT_FOR_FULL_STOP).await;
}
// no need to wait if server stopping returned an error
Err(err) => error!("Restarting (stop): {err}"),
}

// wait for the server to fully stop
sleep(Duration::from_secs(6)).await;

self.start()
.inspect_err(|err| error!("Restarting (start): {err}"))
.await
}

/// Can be called only once to spawn a logger task for the server!
pub fn run_logger(&self) {
pub fn run_logger(&self, url_sender: watch::Sender<Option<Url>>) {
let server = self.clone();

tokio::spawn(async move {
Expand All @@ -257,7 +268,15 @@ impl Server {
if let Some(server_url) =
stdout_line.strip_prefix("EngineFS server started at ")
{
info!("Server url: {server_url}");
match server_url.parse::<Url>() {
Ok(server_url) => {
info!("Server url: {server_url}");
url_sender.send_replace(Some(server_url));
}
Err(err) => error!(
"Error when passing {server_url} as server url: {err}"
),
}
}
}
Ok(None) => {
Expand Down
4 changes: 2 additions & 2 deletions tests/copyright.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ fn copyright() {
.unwrap_or(false);

if parent_dir_included {
if let Ok(file) = fs::File::open(&path) {
if let Ok(file) = fs::File::open(path) {
let reader = io::BufReader::new(file);
if let Some(first_line) = reader.lines().next() {
let line = first_line.unwrap();
assert_eq!(copyright_regex.is_match(&line), true);
assert!(copyright_regex.is_match(&line));
}
}
}
Expand Down

0 comments on commit 9d8c19c

Please sign in to comment.