Allow config alterations to change the avaliable rtsp streams

This commit is contained in:
QuantumEntangledAndy committed 2023-09-03 23:49:57 +07:00
1 parent 71e9830643
commit cf6d266508
11 files changed
+288 -180

No files matched your search

+2 -4
View File
@@ -16,15 +16,13 @@ mod cmdline;
use crate::common::NeoReactor;
use super::config::Config;
pub(crate) use cmdline::Opt;
/// Entry point for the battery subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, config: Config, reactor: NeoReactor) -> Result<()> {
let config = config.get_camera_config(&opt.camera)?;
let camera = reactor.get_or_insert(config.clone()).await?;
pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
let camera = reactor.get(&opt.camera).await?;
log::debug!("Battery: Instance aquired");
let state = camera
+1
View File
@@ -190,6 +190,7 @@ impl NeoCam {
)
}
#[allow(dead_code)]
pub(crate) async fn update_config(&self, config: CameraConfig) -> Result<()> {
self.config_watch.send(config)?;
Ok(())
+47 -62
View File
@@ -1,22 +1,25 @@
//! This is the highest level to a camera
//! it represents a collection of managed cameras
use anyhow::anyhow;
use std::collections::{hash_map::Entry, HashMap};
use std::{
collections::{hash_map::Entry, HashMap},
sync::Arc,
};
use tokio::sync::{
mpsc::{channel as mpsc, Sender as MpscSender},
oneshot::{channel as oneshot, Sender as OneshotSender},
watch::{channel as watch, Receiver as WatchReceiver},
};
use tokio_util::sync::CancellationToken;
use super::{NeoCam, NeoInstance};
use crate::{config::CameraConfig, Result};
use crate::{config::Config, Result};
#[allow(clippy::large_enum_variant)]
enum NeoReactorCommand {
HangUp,
Get(String, OneshotSender<Result<NeoInstance>>),
GetOrInsert(CameraConfig, OneshotSender<Result<NeoInstance>>),
UpdateOrInsert(CameraConfig, OneshotSender<Result<NeoInstance>>),
Config(OneshotSender<WatchReceiver<Config>>),
Get(String, OneshotSender<Result<Option<NeoInstance>>>),
}
/// Reactor handles the collection of cameras
@@ -24,22 +27,27 @@ enum NeoReactorCommand {
pub(crate) struct NeoReactor {
cancel: CancellationToken,
commander: MpscSender<NeoReactorCommand>,
arc: Arc<()>,
}
impl NeoReactor {
pub(crate) async fn new() -> Self {
pub(crate) async fn new(config: Config) -> Self {
let (commad_tx, mut command_rx) = mpsc(100);
let me = Self {
cancel: CancellationToken::new(),
commander: commad_tx,
arc: Arc::new(()),
};
let (config_tx, _) = watch(config);
let cancel = me.cancel.clone();
let cancel2 = me.cancel.clone();
let config_tx = Arc::new(config_tx);
tokio::task::spawn(async move {
let mut instances: HashMap<String, NeoCam> = Default::default();
tokio::select! {
let r = tokio::select! {
_ = cancel.cancelled() => {
for instance in instances.values() {
instance.shutdown().await;
@@ -47,7 +55,6 @@ impl NeoReactor {
Ok(())
},
v = async {
while let Some(command) = command_rx.recv().await {
match command {
NeoReactorCommand::HangUp => {
@@ -58,59 +65,45 @@ impl NeoReactor {
cancel2.cancel();
return Result::<(), anyhow::Error>::Ok(());
}
NeoReactorCommand::Get(name, sender) => {
let new = instances
.get(&name)
.ok_or_else(|| anyhow!("Camera not found"))
.map(|data| data.subscribe())?
.await;
let _ = sender.send(new);
NeoReactorCommand::Config(reply) => {
let _ = reply.send(config_tx.subscribe());
}
NeoReactorCommand::GetOrInsert(config, sender) => {
let name = config.name.clone();
let new = match instances.entry(name) {
Entry::Occupied(occ) => occ.get().subscribe().await,
NeoReactorCommand::Get(name, sender) => {
let new = match instances.entry(name.clone()) {
Entry::Occupied(occ) => Result::Ok(Some(occ.get().subscribe().await?)),
Entry::Vacant(vac) => {
log::debug!("Inserting new insance");
let cam = NeoCam::new(config).await?;
log::debug!("New instance created");
vac.insert(
cam,
)
.subscribe()
.await
let current_config: Config = (*config_tx.borrow()).clone();
if let Some(config) = current_config.cameras.iter().find(|cam| cam.name == name).cloned() {
let cam = NeoCam::new(config).await?;
log::debug!("New instance created");
Result::Ok(Some(
vac.insert(
cam,
)
.subscribe()
.await?
))
} else {
Result::Ok(None)
}
}
};
log::debug!("Got instance from reactor");
let _ = sender.send(new);
},
NeoReactorCommand::UpdateOrInsert(config, sender) => {
let name = config.name.clone();
let new = match instances.entry(name) {
Entry::Occupied(occ) => {
occ.get().update_config(config).await?;
occ.get().subscribe().await
},
Entry::Vacant(vac) => {
let cam = NeoCam::new(config).await?;
vac.insert(cam)
.subscribe()
.await
}
};
let _ = sender.send(new);
}
}
}
Ok(())
} => v,
}
};
log::info!("Neoreactor thread done: {r:?}");
r
});
me
}
#[allow(dead_code)]
/// Get camera by name but do not create
pub(crate) async fn get(&self, name: &str) -> Result<NeoInstance> {
let (sender_tx, sender_rx) = oneshot();
@@ -118,28 +111,18 @@ impl NeoReactor {
.send(NeoReactorCommand::Get(name.to_string(), sender_tx))
.await?;
sender_rx.await?
sender_rx
.await??
.ok_or(anyhow!("Camera `{name}` not found in config"))
}
/// Get or create a camera
pub(crate) async fn get_or_insert(&self, config: CameraConfig) -> Result<NeoInstance> {
pub(crate) async fn config(&self) -> Result<WatchReceiver<Config>> {
let (sender_tx, sender_rx) = oneshot();
self.commander
.send(NeoReactorCommand::GetOrInsert(config, sender_tx))
.send(NeoReactorCommand::Config(sender_tx))
.await?;
sender_rx.await?
}
#[allow(dead_code)]
/// Update a camera to a new config or create a camera
pub(crate) async fn update_or_insert(&self, config: CameraConfig) -> Result<NeoInstance> {
let (sender_tx, sender_rx) = oneshot();
self.commander
.send(NeoReactorCommand::UpdateOrInsert(config, sender_tx))
.await?;
sender_rx.await?
Ok(sender_rx.await?)
}
pub(crate) async fn shutdown(&self) {
@@ -150,7 +133,9 @@ impl NeoReactor {
impl Drop for NeoReactor {
fn drop(&mut self) {
log::debug!("Cancel:: NeoReactor::drop");
self.cancel.cancel();
if Arc::strong_count(&self.arc) == 1 {
log::debug!("Cancel:: NeoReactor::drop");
self.cancel.cancel();
}
}
}
-13
View File
@@ -46,19 +46,6 @@ pub(crate) struct Config {
pub(crate) users: Vec<UserConfig>,
}
impl Config {
pub(crate) fn get_camera_config(&self, name: &str) -> Result<&CameraConfig, anyhow::Error> {
self.cameras
.iter()
.filter(|c| c.enabled)
.find(|cam| cam.name == name)
.ok_or(anyhow::anyhow!(
"Camera with name `{}` not found in the config",
name
))
}
}
#[derive(Debug, Deserialize, Clone, Copy, Eq, PartialEq)]
pub(crate) enum StreamConfig {
#[serde(alias = "none")]
+2 -4
View File
@@ -27,16 +27,14 @@ use tokio_stream::wrappers::BroadcastStream;
mod cmdline;
mod gst;
use super::config::Config;
use crate::common::NeoReactor;
pub(crate) use cmdline::Opt;
/// Entry point for the image subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, config: Config, reactor: NeoReactor) -> Result<()> {
let config = config.get_camera_config(&opt.camera)?;
let camera = reactor.get_or_insert(config.clone()).await?;
pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
let camera = reactor.get(&opt.camera).await?;
if opt.use_stream {
let stream_data = camera
+8 -8
View File
@@ -87,7 +87,7 @@ async fn main() -> Result<()> {
tokio_console_enable();
}
let neo_reactor = NeoReactor::new().await;
let neo_reactor = NeoReactor::new(config.clone()).await;
match opt.cmd {
None => {
@@ -95,19 +95,19 @@ async fn main() -> Result<()> {
"Deprecated command line option. Please use: `neolink rtsp --config={:?}`",
config
);
rtsp::main(rtsp::Opt {}, config, neo_reactor.clone()).await?;
rtsp::main(rtsp::Opt {}, neo_reactor.clone()).await?;
}
Some(Command::Rtsp(opts)) => {
rtsp::main(opts, config, neo_reactor.clone()).await?;
rtsp::main(opts, neo_reactor.clone()).await?;
}
Some(Command::StatusLight(opts)) => {
statusled::main(opts, config, neo_reactor.clone()).await?;
statusled::main(opts, neo_reactor.clone()).await?;
}
Some(Command::Reboot(opts)) => {
reboot::main(opts, config, neo_reactor.clone()).await?;
reboot::main(opts, neo_reactor.clone()).await?;
}
Some(Command::Pir(opts)) => {
pir::main(opts, config, neo_reactor.clone()).await?;
pir::main(opts, neo_reactor.clone()).await?;
}
Some(Command::Ptz(opts)) => {
ptz::main(opts, config).await?;
@@ -119,10 +119,10 @@ async fn main() -> Result<()> {
mqtt::main(opts, config).await?;
}
Some(Command::Image(opts)) => {
image::main(opts, config, neo_reactor.clone()).await?;
image::main(opts, neo_reactor.clone()).await?;
}
Some(Command::Battery(opts)) => {
battery::main(opts, config, neo_reactor.clone()).await?;
battery::main(opts, neo_reactor.clone()).await?;
}
}
+2 -4
View File
@@ -17,16 +17,14 @@ use anyhow::{Context, Result};
mod cmdline;
use super::config::Config;
use crate::common::NeoReactor;
pub(crate) use cmdline::Opt;
/// Entry point for the pir subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, config: Config, reactor: NeoReactor) -> Result<()> {
let config = config.get_camera_config(&opt.camera)?;
let camera = reactor.get_or_insert(config.clone()).await?;
pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
let camera = reactor.get(&opt.camera).await?;
if let Some(on) = opt.on {
camera
+2 -4
View File
@@ -15,16 +15,14 @@ use anyhow::{Context, Result};
mod cmdline;
use super::config::Config;
use crate::common::NeoReactor;
pub(crate) use cmdline::Opt;
/// Entry point for the reboot subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, config: Config, reactor: NeoReactor) -> Result<()> {
let config = config.get_camera_config(&opt.camera)?;
let camera = reactor.get_or_insert(config.clone()).await?;
pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
let camera = reactor.get(&opt.camera).await?;
camera
.run_task(|camera| {
+69 -33
View File
@@ -16,7 +16,11 @@ use gstreamer_rtsp_server::{
RTSPAuth, RTSPServer, RTSPToken, RTSP_TOKEN_MEDIA_FACTORY_ROLE,
};
use log::*;
use std::{fs, sync::Arc};
use std::{
collections::{HashMap, HashSet},
fs,
sync::Arc,
};
use tokio::{
sync::RwLock,
task::JoinSet,
@@ -38,6 +42,17 @@ impl NeoRtspServer {
pub(crate) fn new() -> AnyResult<Self> {
gstreamer::init().context("Gstreamer failed to initialise")?;
let factory = Object::new::<NeoRtspServer>();
// Setup auth
let auth = factory.auth().unwrap_or_else(RTSPAuth::new);
auth.set_supported_methods(RTSPAuthMethod::Basic);
let mut un_authtoken = RTSPToken::new(&[
//RTSP_TOKEN_MEDIA_FACTORY_ROLE: Means look inside the media factory settings and use the same permissions this user (`"anonymous"`) has
(RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"anonymous"),
]);
auth.set_default_token(Some(&mut un_authtoken));
factory.set_auth(Some(&auth));
Ok(factory)
}
@@ -80,12 +95,20 @@ impl NeoRtspServer {
Ok(())
}
pub(crate) fn set_up_tls(&self, config: &Config) {
pub(crate) fn set_up_tls(&self, config: &Config) -> AnyResult<()> {
self.imp().set_up_tls(config)
}
pub(crate) fn set_up_users(&self, users: &[UserConfig]) {
self.imp().set_up_users(users)
pub(crate) async fn add_user(&self, username: &str, password: &str) -> AnyResult<()> {
self.imp().add_user(username, password).await
}
pub(crate) async fn remove_user(&self, username: &str) -> AnyResult<()> {
self.imp().remove_user(username).await
}
pub(crate) async fn get_users(&self) -> AnyResult<HashSet<String>> {
self.imp().get_users().await
}
}
@@ -95,6 +118,7 @@ unsafe impl Sync for NeoRtspServer {}
#[derive(Default)]
pub(crate) struct NeoRtspServerImpl {
threads: RwLock<JoinSet<AnyResult<()>>>,
users: RwLock<HashMap<String, String>>,
main_loop: RwLock<Option<Arc<MainLoop>>>,
}
@@ -109,25 +133,6 @@ impl ObjectSubclass for NeoRtspServerImpl {
}
impl NeoRtspServerImpl {
pub(crate) fn set_credentials(&self, credentials: &[(&str, &str)]) -> AnyResult<()> {
let auth = self.obj().auth().unwrap_or_else(RTSPAuth::new);
auth.set_supported_methods(RTSPAuthMethod::Basic);
let mut un_authtoken = RTSPToken::new(&[(RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"anonymous")]);
auth.set_default_token(Some(&mut un_authtoken));
for credential in credentials {
let (user, pass) = credential;
trace!("Setting credentials for user {}", user);
let token = RTSPToken::new(&[(RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]);
let basic = RTSPAuth::make_basic(user, pass);
auth.add_basic(basic.as_str(), &token);
}
self.obj().set_auth(Some(&auth));
Ok(())
}
pub(crate) fn set_tls(
&self,
cert_file: &str,
@@ -147,7 +152,7 @@ impl NeoRtspServerImpl {
Ok(())
}
pub(crate) fn set_up_tls(&self, config: &Config) {
pub(crate) fn set_up_tls(&self, config: &Config) -> AnyResult<()> {
let tls_client_auth = match &config.tls_client_auth as &str {
"request" => TlsAuthenticationMode::Requested,
"require" => TlsAuthenticationMode::Required,
@@ -156,17 +161,48 @@ impl NeoRtspServerImpl {
};
if let Some(cert_path) = &config.certificate {
self.set_tls(cert_path, tls_client_auth)
.expect("Failed to set up TLS");
.with_context(|| "Failed to set up TLS")?;
}
Ok(())
}
pub(crate) fn set_up_users(&self, users: &[UserConfig]) {
// Setting up users
let credentials: Vec<_> = users
.iter()
.map(|user| (&*user.name, &*user.pass))
.collect();
self.set_credentials(&credentials)
.expect("Failed to set up users");
pub(crate) async fn add_user(&self, username: &str, password: &str) -> AnyResult<()> {
let mut locked_users = self.users.write().await;
let auth = self.obj().auth().unwrap();
let token = RTSPToken::new(&[(RTSP_TOKEN_MEDIA_FACTORY_ROLE, &username)]);
let basic = RTSPAuth::make_basic(username, password);
if let Some(old_basic) = locked_users.get(username) {
if basic.as_str() == old_basic {
// Password is the same
return Ok(());
} else {
// Different password
auth.remove_basic(old_basic);
}
}
auth.add_basic(basic.as_str(), &token);
locked_users.insert(username.to_string(), basic.to_string());
Ok(())
}
pub(crate) async fn remove_user(&self, username: &str) -> AnyResult<()> {
let mut locked_users = self.users.write().await;
let auth = self.obj().auth().unwrap();
if let Some(old_basic) = locked_users.get(username) {
auth.remove_basic(old_basic);
}
locked_users.remove(username);
Ok(())
}
pub(crate) async fn get_users(&self) -> AnyResult<HashSet<String>> {
let locked_users = self.users.read().await;
Ok(locked_users.keys().cloned().collect())
}
}
+153 -44
View File
@@ -58,7 +58,7 @@ use gstreamer_app::{AppSrc, AppSrcCallbacks, AppStreamType};
use gstreamer_rtsp_server::prelude::*;
use log::*;
use neolink_core::{bc_protocol::StreamKind, bcmedia::model::*};
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use tokio::{
sync::{
@@ -88,60 +88,133 @@ type AnyResult<T> = anyhow::Result<T, anyhow::Error>;
/// Entry point for the rtsp subcommand
///
/// Opt is the command line options
pub(crate) async fn main(_opt: Opt, mut config: Config, reactor: NeoReactor) -> Result<()> {
pub(crate) async fn main(_opt: Opt, reactor: NeoReactor) -> Result<()> {
let rtsp = Arc::new(NeoRtspServer::new()?);
rtsp.set_up_tls(&config);
rtsp.set_up_users(&config.users);
if config.certificate.is_none() && !config.users.is_empty() {
warn!(
"Without a server certificate, usernames and passwords will be exchanged in plaintext!"
)
}
let mut cameras = vec![];
for camera_config in config.cameras.drain(..).filter(|c| c.enabled) {
cameras.push(reactor.get_or_insert(camera_config).await?);
}
let global_cancel = CancellationToken::new();
let mut set = JoinSet::new();
for camera in cameras.drain(..) {
let thread_global_cancel = global_cancel.clone();
let thread_rtsp = rtsp.clone();
set.spawn_blocking(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async move {
tokio::select!(
_ = thread_global_cancel.cancelled() => {
AnyResult::Ok(())
},
v = camera_main(camera, &thread_rtsp) => v,
)
})
});
}
// Thread for the TLS from the config
let mut thread_config = reactor.config().await?;
let thread_cancel = global_cancel.clone();
let thread_rtsp = rtsp.clone();
thread_rtsp.set_up_tls(&thread_config.borrow_and_update().clone())?;
set.spawn(async move {
tokio::select! {
_ = thread_cancel.cancelled() => AnyResult::Ok(()),
v = async {
loop {
thread_config.changed().await?;
if let Err(e) = thread_rtsp.set_up_tls(&thread_config.borrow().clone()) {
log::error!("Could not seup TLS: {e}");
}
}
} => v
}
});
// Thread for the Users from the config
let mut thread_config = reactor.config().await?;
let thread_cancel = global_cancel.clone();
let thread_rtsp = rtsp.clone();
apply_users(&thread_rtsp, &thread_config.borrow_and_update().clone()).await?;
set.spawn(async move {
tokio::select! {
_ = thread_cancel.cancelled() => AnyResult::Ok(()),
v = async {
loop {
thread_config.changed().await?;
let config = thread_config.borrow().clone();
if let Err(e) = apply_users(&thread_rtsp, &config.clone()).await {
log::error!("Could not seup TLS: {e}");
}
}
} => v
}
});
// Startup and stop cameras as they are added/removed to the config
let mut thread_config = reactor.config().await?;
let thread_cancel = global_cancel.clone();
let thread_rtsp = rtsp.clone();
let thread_reactor = reactor.clone();
set.spawn(async move {
let mut set = JoinSet::<AnyResult<()>>::new();
let thread_cancel2 = thread_cancel.clone();
tokio::select!{
_ = thread_cancel.cancelled() => AnyResult::Ok(()),
v = async {
let mut cameras: HashMap<String, CancellationToken> = Default::default();
let mut config_names = HashSet::new();
loop {
thread_config.wait_for(|config| {
let current_names = config.cameras.iter().filter(|a| a.enabled).map(|cam_config| cam_config.name.clone()).collect::<HashSet<_>>();
current_names != config_names
}).await.with_context(|| "Camera Config Watcher")?;
config_names = thread_config.borrow().clone().cameras.iter().filter(|a| a.enabled).map(|cam_config| cam_config.name.clone()).collect::<HashSet<_>>();
for name in config_names.iter().cloned() {
log::info!("{name}: Rtsp Staring");
if ! cameras.contains_key(&name) {
let local_cancel = CancellationToken::new();
cameras.insert(name.clone(),local_cancel.clone() );
let thread_global_cancel = thread_cancel2.clone();
let thread_rtsp2 = thread_rtsp.clone();
let thread_reactor2 = thread_reactor.clone();
set.spawn_blocking(|| {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
runtime.block_on(async move {
let camera = thread_reactor2.get(&name).await?;
tokio::select!(
_ = thread_global_cancel.cancelled() => {
AnyResult::Ok(())
},
_ = local_cancel.cancelled() => {
AnyResult::Ok(())
},
v = camera_main(camera, &thread_rtsp2) => v,
)
})
});
}
}
for (running_name, token) in cameras.iter() {
if ! config_names.contains(running_name) {
token.cancel();
}
}
}
} => v,
}
});
let rtsp_config = reactor.config().await?.borrow().clone();
info!(
"Starting RTSP Server at {}:{}",
&config.bind_addr, config.bind_port,
&rtsp_config.bind_addr, rtsp_config.bind_port,
);
let bind_addr = config.bind_addr.clone();
let bind_port = config.bind_port;
let bind_addr = rtsp_config.bind_addr.clone();
let bind_port = rtsp_config.bind_port;
rtsp.run(&bind_addr, bind_port).await?;
let thread_rtsp = rtsp.clone();
set.spawn(async move { thread_rtsp.join().await });
while let Some(joined) = set.join_next().await {
while let Some(joined) = set
.join_next()
.await
.map(|s| s.map_err(anyhow::Error::from))
{
match &joined {
Err(_) | Ok(Err(_)) => {
Err(e) | Ok(Err(e)) => {
// Panicked or error in task
// Cancel all and await terminate
log::error!("Error: {e}");
global_cancel.cancel();
rtsp.quit().await?;
}
@@ -154,6 +227,26 @@ pub(crate) async fn main(_opt: Opt, mut config: Config, reactor: NeoReactor) ->
Ok(())
}
async fn apply_users(rtsp: &NeoRtspServer, config: &Config) -> AnyResult<()> {
// Add those missing
for user in config.users.iter() {
rtsp.add_user(&user.name, &user.pass).await?;
}
// Remove unused
let rtsp_users = rtsp.get_users().await?;
for user in rtsp_users {
if config.users.iter().any(|a| a.name == user) {
rtsp.remove_user(&user).await?;
}
}
if config.certificate.is_none() && !config.users.is_empty() {
warn!(
"Without a server certificate, usernames and passwords will be exchanged in plaintext!"
)
}
Ok(())
}
async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
let stream_info = camera
.run_task(|cam| Box::pin(async move { Ok(cam.get_stream_info().await?) }))
@@ -179,6 +272,7 @@ async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
let mut camera_config = camera.config().await?.clone();
loop {
let prev_stream_config = camera_config.borrow_and_update().stream;
let prev_stream_users = camera_config.borrow().permitted_users.clone();
let active_streams = prev_stream_config
.as_stream_kinds()
.drain(..)
@@ -186,7 +280,7 @@ async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
// This select is for changes to camera_config.stream
break tokio::select! {
v = camera_config.wait_for(|config| config.stream != prev_stream_config) => {
v = camera_config.wait_for(|config| config.stream != prev_stream_config || config.permitted_users != prev_stream_users) => {
if let Err(e) = v {
AnyResult::Err(e.into())
} else {
@@ -196,18 +290,32 @@ async fn camera_main(camera: NeoInstance, rtsp: &NeoRtspServer) -> Result<()> {
},
v = async {
// This select handles enabling the right stream
let all_users = rtsp.get_users().await?.iter().filter(|a| *a != "anyone" && *a != "anonymous").cloned().collect::<HashSet<_>>();
let permitted_users: HashSet<String> = match &prev_stream_users {
// If in the camera config there is the user "anyone", or if none is specified but users
// are defined at all, then we add all users to the camera's allowed list.
Some(p) if p.iter().any(|u| u == "anyone") => all_users,
None if !all_users.is_empty() => all_users,
// The user specified permitted_users
Some(p) => p.iter().cloned().collect(),
// The user didn't specify permitted_users, and there are none defined anyway
None => ["anonymous".to_string()].iter().cloned().collect(),
};
tokio::select! {
v = async {
let name = camera.config().await?.borrow().name.clone();
stream_main(name, camera.stream(StreamKind::Main).await?, rtsp).await
stream_main(name, camera.stream(StreamKind::Main).await?, rtsp, &permitted_users).await
}, if active_streams.contains(&StreamKind::Main) && supported_streams.contains(&StreamKind::Main) => v,
v = async {
let name = camera.config().await?.borrow().name.clone();
stream_main(name, camera.stream(StreamKind::Sub).await?, rtsp).await
stream_main(name, camera.stream(StreamKind::Sub).await?, rtsp, &permitted_users).await
}, if active_streams.contains(&StreamKind::Sub) && supported_streams.contains(&StreamKind::Sub) => v,
v = async {
let name = camera.config().await?.borrow().name.clone();
stream_main(name, camera.stream(StreamKind::Extern).await?, rtsp).await
stream_main(name, camera.stream(StreamKind::Extern).await?, rtsp, &permitted_users).await
}, if active_streams.contains(&StreamKind::Extern) && supported_streams.contains(&StreamKind::Extern) => v,
else => {
// all disabled just wait here until config is changed
@@ -232,6 +340,7 @@ async fn stream_main(
name: String,
mut stream_instance: StreamInstance,
rtsp: &NeoRtspServer,
users: &HashSet<String>,
) -> Result<()> {
loop {
// Wait for a valid stream format to be detected
@@ -362,7 +471,7 @@ async fn stream_main(
}).await
}?;
factory.add_permitted_roles(&["anonymous"].into());
factory.add_permitted_roles(users);
mounts.add_factory(&path, factory);
// Done now sit on the receiver and push through the vid to the app sources
+2 -4
View File
@@ -19,16 +19,14 @@ use anyhow::{Context, Result};
mod cmdline;
use super::config::Config;
use crate::common::NeoReactor;
pub(crate) use cmdline::Opt;
/// Entry point for the ledstatus subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, config: Config, reactor: NeoReactor) -> Result<()> {
let config = config.get_camera_config(&opt.camera)?;
let camera = reactor.get_or_insert(config.clone()).await?;
pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
let camera = reactor.get(&opt.camera).await?;
let on = opt.on;
camera