Compare commits

...
21 Commits
Author SHA1 Message Date
Andrew King 6e05e7844b Merge pull request #345 from ecksun/feature/users
Add support for managing users
2025-01-30 14:00:08 +07:00
Andrew King 43b62090c8 Rust fmt 2025-01-30 11:24:17 +07:00
Andrew King 7a66473ab9 Skip seser on the pass field
Skip deser the pass field for camera's that try to sent it in the user list
2025-01-30 11:21:08 +07:00
Linus a30f403dc4 Add support for managing users
Support includes:
- Listing users
- Creating users
- Deleting users
- Changing the password of users
2025-01-29 22:31:22 +01:00
Linus 76833e6242 dissector: Document Message ID 59 <UserList>
It is used to manage users
2025-01-29 22:31:22 +01:00
Linus 1518ab24bb dissector: Deindent ConfigFileInfo
It seemed to be a child of AbilitySupport, which is not the case
2025-01-27 23:12:47 +01:00
Andrew King c3353591ae Merge pull request #312 from QuantumEntangledAndy/fix/windowsBuild 2024-10-26 17:17:41 +07:00
QuantumEntangledAndy 18c4d56826 Don't forget the two includes 2024-10-26 16:53:28 +07:00
QuantumEntangledAndy e9e66b1a44 Rustc 1.82.0 2024-10-26 16:41:58 +07:00
QuantumEntangledAndy 1499503789 Single point of control on rust version 2024-10-26 15:16:07 +07:00
QuantumEntangledAndy fb9df1d586 Use explicit rust version for proper control in scripts 2024-10-26 15:14:15 +07:00
QuantumEntangledAndy 1517077564 More fixes to features 2024-10-26 15:13:48 +07:00
QuantumEntangledAndy e6c6f5ca62 Try and fix the gstreamer only cfg 2024-10-26 14:39:30 +07:00
QuantumEntangledAndy ed4a5ea001 Style fixes 2024-10-26 14:33:19 +07:00
QuantumEntangledAndy 4f8fb6c7b5 Remove the extra path var in windows build 2024-10-25 15:30:46 +07:00
QuantumEntangledAndy fb956c399e Bump gstreamer for windows build 2024-10-25 15:29:44 +07:00
QuantumEntangledAndy 81f77f461c Fix quotes 2024-10-25 13:59:46 +07:00
QuantumEntangledAndy 5279a34bcb More investigation of windows build error on the runner 2024-10-25 13:57:36 +07:00
QuantumEntangledAndy d09874eca5 Test the windows path on the runner 2024-10-25 13:45:18 +07:00
QuantumEntangledAndy 13081f745f Remove push notifications for now 2024-10-24 11:49:17 +07:00
QuantumEntangledAndy a14336fe3c Restore lost extra setting 2024-10-21 07:29:06 +07:00
26 changed files with 934 additions and 375 deletions

No files matched your search

+13 -11
View File
@@ -5,6 +5,9 @@ on:
pull_request:
workflow_dispatch:
env:
rust_version: "1.82.0"
jobs:
pre_job:
# continue-on-error: true # Uncomment once integration is finished
@@ -33,17 +36,17 @@ jobs:
- uses: actions/checkout@v4
name: Checkout onto ${{ runner.os }}
- if: runner.os == 'Linux'
name: apt install gstreamer
name: apt install linux deps
run: |
sudo apt update
sudo apt install -y aptitude
sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev protobuf-compiler libssl-dev
- if: runner.os == 'Windows'
name: Install Gstreamer
name: Install Windows deps
run: |
# Gstreamer
choco install -y --no-progress gstreamer --version=1.20.0
choco install -y --no-progress gstreamer-devel --version=1.20.0
choco install -y --no-progress gstreamer --version=1.24.2
choco install -y --no-progress gstreamer-devel --version=1.24.2
$env:GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:SYSTEMDRIVE + '\gstreamer\1.0\msvc_x86_64\'
# Github runners work on both C or D drive and figuring out which was used is difficult
if (-not (Test-Path -Path "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64" -PathType Container)) {
@@ -71,21 +74,17 @@ jobs:
$env:OPENSSL_DIR='D:\\Program Files\OpenSSL\'
}
# Set up pkgconfig for gstreamer
$env:PKG_CONFIG_PATH += ';' + $env:GSTREAMER_1_0_ROOT_MSVC_X86_64 + '\lib\pkgconfig'
# Set github vars
Add-Content -Path $env:GITHUB_ENV -Value "GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
Add-Content -Path $env:GITHUB_PATH -Value "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64\bin"
Add-Content -Path $env:GITHUB_PATH -Value "%GSTREAMER_1_0_ROOT_MSVC_X86_64%\bin"
Add-Content -Path $env:GITHUB_ENV -Value "OPENSSL_DIR=$env:OPENSSL_DIR"
Add-Content -Path $env:GITHUB_ENV -Value "PKG_CONFIG_PATH=$env:PKG_CONFIG_PATH"
# One last check on directories
dir "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
dir "$env:OPENSSL_DIR"
- if: runner.os == 'macOS'
name: Install Gstreamer on macOS
name: Install macOS deps
run: |
curl -L 'https://gstreamer.freedesktop.org/data/pkg/osx/1.20.4/gstreamer-1.0-devel-1.20.4-universal.pkg' -o "$(pwd)/gstreamer-devel.pkg"
sudo installer -verbose -pkg "$(pwd)/gstreamer-devel.pkg" -target /
@@ -182,6 +181,7 @@ jobs:
echo "${HOME}/.cargo/bin" >> "${GITHUB_PATH}"
- name: Install ${{ matrix.arch }} Rust toolchain
run: |
rustup default "${{ env.rust_version }}"
rustup target add ${TARGET}
env:
TARGET: ${{ matrix.target }}
@@ -286,8 +286,9 @@ jobs:
echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}"
env:
REPO_NAME: ${{ steps.docker_repo.outputs.DOCKER_NWO }}
- name: Install latest rust
- name: Install rust
run: |
rustup default "${{ env.rust_version }}"
rustup toolchain install stable
- name: Install toml-cli
run: |
@@ -345,8 +346,9 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install latest rust
- name: Install rust
run: |
rustup default "${{ env.rust_version }}"
rustup toolchain install stable
- name: Install toml-cli
run: |
+4
View File
@@ -35,9 +35,13 @@ jobs:
rustup override set nightly
- name: Run clippy manually
run: |
echo "All Features"
cargo +nightly clippy --workspace --all-targets --all-features || exit 1
echo "No Features"
cargo +nightly clippy --workspace --all-targets --no-default-features || exit 1
echo "Gstreamer Only"
cargo +nightly clippy --workspace --all-targets --no-default-features --features=gstreamer || exit 1
echo "Pushnoti Only"
cargo +nightly clippy --workspace --all-targets --no-default-features --features=pushnoti || exit 1
check_fmt:
+1 -1
View File
@@ -27,4 +27,4 @@
token.toml
# Debug FCM build
./crates/fcm-push-listener/
crates/fcm-push-listener
Generated
+3 -22
View File
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
version = 4
[[package]]
name = "addr2line"
@@ -839,25 +839,6 @@ dependencies = [
"webpki-roots",
]
[[package]]
name = "fcm-push-listener"
version = "3.0.0"
dependencies = [
"base64 0.21.7",
"ece",
"log",
"prost",
"prost-build",
"rand",
"reqwest",
"serde",
"serde_with",
"tokio",
"tokio-rustls 0.23.4",
"uuid",
"webpki-roots",
]
[[package]]
name = "fixedbitset"
version = "0.4.2"
@@ -1895,7 +1876,7 @@ dependencies = [
"crossbeam-channel",
"dirs",
"env_logger 0.11.3",
"fcm-push-listener 2.0.3",
"fcm-push-listener",
"futures",
"gstreamer",
"gstreamer-app",
@@ -2339,7 +2320,7 @@ dependencies = [
"anyhow",
"clap",
"env_logger 0.10.2",
"fcm-push-listener 2.0.3",
"fcm-push-listener",
"lazy_static",
"log",
"neolink_core",
+1 -1
View File
@@ -47,7 +47,7 @@ validator = {version="0.18.1", features = ["derive"] }
tikv-jemallocator = "0.5"
[features]
default = ["gstreamer", "pushnoti"]
default = ["gstreamer"]
gstreamer = [
"dep:gstreamer",
"dep:gstreamer-app",
+38 -2
View File
@@ -374,6 +374,36 @@ Available features are:
- `battery`: This adds a battery level sensor to home assistant
- `siren`: Adds a siren button to home assistant
### Extra Camera Settings
Listed below are extra camera settings:
```toml
[[cameras]]
name = "Camera01"
username = "admin"
password = "password"
uid = "ABCDEF0123456789"
debug = false # Displays Debug XML messages from camera
enabled = true # Enable or Disable the camera
update_time = false # When camera connects, force the setting of the camera date/time to now. The default is false
print_format = "None" # Type of format that logs are displayed in (None, Human, Xml). The default is None
```
- **Debug:** Will dump the various XMLs from the camera as they are recieved
and decrypted. Leave this off unless asked for it to fix an issue.
- **Enabled:** Useful if you want to remove a camera from rtsp without deleting
it from the config
- **update_time:** Used to FORCE an update on the camera time. Usually it checks
if it is needed but this
will force it regardless. (Mostly this was introduced to address a specific
ssue a user had)
- **print_format:** Used for adjusting printing of some values mostly, battery
messages
### Pause
To use the pause feature you will need to adjust your config file as such:
@@ -425,6 +455,10 @@ after it stops being used.
Neolink considers it as being used if there is an active stream running, or
if there is motion being detected or an mqtt command being run
[Because google remove the api for the push notifications we cannot
reliably use push notifications to wake up, so motion won't wake
up neolink anymore]
You can make neolink stop active streams when there are no rtsp clients using
```toml
@@ -435,9 +469,11 @@ You can make neolink stop active streams when there are no rtsp clients using
Once in the disconnected state. Neolink will stay disconnected until there is a
new requested activation such as a client connecting or an mqtt command
Neolink will also wake up on push notifications from the camera. These are usually
~Neolink will also wake up on push notifications from the camera. These are usually
sent by the camera on motion or PIR alarms. To disable this you can set
`push_notifications = false` in the `[[cameras]]` config
`push_notifications = false` in the `[[cameras]]` config~
[Google removed the apis we were using for push notifications]
### Docker
+2 -4
View File
@@ -90,10 +90,8 @@ fn bc_modern_msg<'a>(
E::add_context(input, ctx, E::from_error_kind(input, kind))
}
let ext_len = match header.payload_offset {
Some(off) => off,
_ => 0, // If missing payload_offset treat all as payload
};
// If missing payload_offset treat all as payload
let ext_len = header.payload_offset.unwrap_or_default();
let (buf, ext_buf) = take(ext_len)(buf)?;
let payload_len = header.body_len - ext_len;
+7 -8
View File
@@ -40,6 +40,10 @@ pub const MSG_ID_GET_SERVICE_PORTS: u32 = 37;
pub const MSG_ID_GET_EMAIL: u32 = 42;
/// Set email settings
pub const MSG_ID_SET_EMAIL: u32 = 43;
/// Get users and general system info
pub const MSG_ID_GET_ABILITY_SUPPORT: u32 = 58;
/// Update, create and remove users
pub const MSG_ID_UPDATE_USER_LIST: u32 = 59;
/// Version messages have this ID
pub const MSG_ID_VERSION: u32 = 80;
/// Ping messages have this ID
@@ -192,8 +196,11 @@ pub struct BcMeta {
pub stream_type: u8,
/// On modern messages this is the response code
/// When sending a command it is set to `0`. The reply from the camera can be
///
/// - `200` for OK
///
/// - `400` for bad request
///
/// A malformed packet will return a `400` code
pub response_code: u16,
/// A message ID is used to match replies with requests. The camera will parrot back
@@ -213,14 +220,6 @@ pub struct BcMeta {
pub class: u16,
}
/// The components of the Baichuan header that must be filled out after the body is serialized, or
/// is needed for the deserialization of the body (strictly part of the wire format of the message)
#[derive(Debug, PartialEq, Eq)]
pub(super) struct BcSendInfo {
pub body_len: u32,
pub payload_offset: Option<u32>,
}
#[derive(Debug)]
pub(crate) struct BcContext {
pub(crate) credentials: Credentials,
+49
View File
@@ -138,6 +138,9 @@ pub struct BcXml {
/// EmailTask for turning the email notifications on/off
#[serde(rename = "EmailTask", skip_serializing_if = "Option::is_none")]
pub email_task: Option<EmailTask>,
/// Read and write users
#[serde(rename = "UserList", skip_serializing_if = "Option::is_none")]
pub user_list: Option<UserList>,
}
impl BcXml {
@@ -1566,6 +1569,52 @@ pub struct Schedule {
pub time_block_list: TimeBlockList,
}
/// List of users
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)]
pub struct UserList {
/// XML Version
#[serde(rename = "@version")]
pub version: String,
/// The actual user-list
#[serde(rename = "User", skip_serializing_if = "Option::is_none")]
pub user_list: Option<Vec<User>>,
}
/// A struct for reading and writing camera user records
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)]
pub struct User {
/// The user_name is used to identify the user in the API
#[serde(rename = "userName")]
pub user_name: String,
/// The password seems to only be included when creating or modifying a user
#[serde(
rename = "password",
skip_serializing_if = "Option::is_none",
skip_deserializing
)]
pub password: Option<String>,
/// The user_id does not seem to have a purpose. It is not included when creating a user.
#[serde(rename = "userId", skip_serializing_if = "Option::is_none")]
pub user_id: Option<u32>,
/// User type, 0 is User and 1 is Administrator
#[serde(rename = "userLevel")]
pub user_level: u8,
/// Unknown, seems to be 1 for the current API user
#[serde(rename = "loginState", skip_serializing_if = "Option::is_none")]
pub login_state: Option<u8>,
/// The user_set_state states what will happen with a user-record. 4 different values have been
/// observed: none | add | delete | modify
///
/// | Value | Description |
/// | --- | --- |
/// | none | This is the state set when reading Users. When writing this seems to indicate that the user should not be modified |
/// | add | Indicates that a new User should be created |
/// | delete | Indicates that the user should be removed |
/// | modify | Indicates that the user should be modified. It seems like only the password can be changed. |
#[serde(rename = "userSetState")]
pub user_set_state: String,
}
/// Convience function to return the xml version used throughout the library
pub fn xml_ver() -> String {
"1.1".to_string()
+1
View File
@@ -40,6 +40,7 @@ mod support;
mod talk;
mod time;
mod uid;
mod users;
mod version;
pub(crate) use connection::*;
@@ -20,9 +20,9 @@ pub struct BcStream<'a> {
rx: &'a mut ReceiverStream<Result<Bc>>,
}
impl<'a> Unpin for BcStream<'a> {}
impl Unpin for BcStream<'_> {}
impl<'a> Stream for BcStream<'a> {
impl Stream for BcStream<'_> {
type Item = Result<Bc>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Bc>>> {
+1 -1
View File
@@ -214,7 +214,7 @@ impl ToSocketAddrsOrUid for SocketAddrV6 {
}
}
impl<'a> ToSocketAddrsOrUid for &'a [SocketAddr] {
impl ToSocketAddrsOrUid for &'_ [SocketAddr] {
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
+179
View File
@@ -0,0 +1,179 @@
use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Returns all users configured in the camera
pub async fn get_users(&self) -> Result<UserList> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection
.subscribe(MSG_ID_GET_ABILITY_SUPPORT, msg_num)
.await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_GET_ABILITY_SUPPORT,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: Some(Extension {
user_name: Some("admin".to_owned()),
..Default::default()
}),
payload: None,
}),
};
sub_get.send(get).await?;
let msg = sub_get.recv().await?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavailable {
id: msg.meta.msg_id,
code: msg.meta.response_code,
});
}
// Valid message with response_code == 200
if let BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
user_list: Some(user_list),
..
})),
..
}) = msg.body
{
Ok(user_list)
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected ModernMsg payload with a user_list but it was not recieved",
})
}
}
/// Add a new user
///
/// This function does not check if the user exist and the API will likely throw an error if
/// that is the case
pub async fn add_user(
&self,
user_name: String,
password: String,
user_level: u8,
) -> Result<()> {
let users = self.get_users().await;
let mut users = users?.user_list.unwrap_or(Vec::new());
if users.iter().any(|user| user.user_name == user_name) {
return Err(Error::Other("User already exists"));
}
users.push(User {
user_set_state: "add".to_owned(),
user_name,
password: Some(password),
user_level,
user_id: None,
login_state: None,
});
self.set_users(users).await
}
/// Modify a user. It seems the only property of a user that is modifiable is the password.
pub async fn modify_user(&self, user_name: String, password: String) -> Result<()> {
let users = self.get_users().await;
let mut users = users?.user_list.unwrap_or(Vec::new());
if let Some(user) = users.iter_mut().find(|user| user.user_name == user_name) {
user.user_set_state = "modify".to_owned();
user.password = Some(password.clone());
} else {
return Err(Error::Other("User not found"));
}
self.set_users(users).await
}
/// Remove a user. This does not check for the existence of that user and will likely return an
/// error if the user doesn't exist.
pub async fn delete_user(&self, user_name: String) -> Result<()> {
let users = self.get_users().await;
let mut users = users?.user_list.unwrap_or(Vec::new());
if let Some(user) = users.iter_mut().find(|user| user.user_name == user_name) {
user.user_set_state = "delete".to_owned();
} else {
return Err(Error::Other("User not found"));
}
self.set_users(users).await
}
/// Helper method to send a UserList and wait for its success/failure.
async fn set_users(&self, users: Vec<User>) -> Result<()> {
let bcxml = BcXml {
user_list: Some(UserList {
version: "1.1".to_owned(),
user_list: Some(users),
}),
..Default::default()
};
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection
.subscribe(MSG_ID_UPDATE_USER_LIST, msg_num)
.await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_UPDATE_USER_LIST,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: None,
payload: Some(BcPayloads::BcXml(bcxml)),
}),
};
sub_set.send(get).await?;
if let Ok(reply) =
tokio::time::timeout(tokio::time::Duration::from_millis(500), sub_set.recv()).await
{
let msg = reply?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavailable {
id: msg.meta.msg_id,
code: msg.meta.response_code,
});
}
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not except the BcXmp with service data",
})
}
} else {
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
Ok(())
}
}
}
-9
View File
@@ -34,15 +34,6 @@ impl Decoder for BcUdpCodex {
type Item = BcUdp;
type Error = Error;
/// Since frames can cross EOF boundaries we overload this so it doesn't error if
/// there are bytes left on the stream
// fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
// match self.decode(buf)? {
// Some(frame) => Ok(Some(frame)),
// None => Ok(None),
// }
// }
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
log::trace!("Decoding:");
if src.is_empty() {
-8
View File
@@ -53,14 +53,6 @@ async fn main() -> Result<()> {
Ok(())
}
fn get_local_ip() -> Result<std::net::IpAddr> {
get_if_addrs::get_if_addrs()?
.iter()
.find(|i| !i.is_loopback() && matches!(i.addr, get_if_addrs::IfAddr::V4(_)))
.map(|iface| Ok(iface.ip()))
.unwrap_or_else(|| Err(anyhow!("No Local Ip Address Found")))
}
async fn cam_tasks(name: &str, camera: BcCamera, addr: SocketAddr) -> Result<()> {
let support = camera.get_support().await?;
if support.email.is_some_and(|v| v > 0) {
-1
View File
@@ -9,7 +9,6 @@ edition = "2021"
anyhow = "1.0.71"
clap = { version = "4.2.2", features = ["derive", "cargo"] }
env_logger = "0.10.0"
# fcm-push-listener = { path = "../fcm-push-listener" }
fcm-push-listener = { version = "2.0.3" }
lazy_static = "1.4.0"
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
+146 -50
View File
@@ -1267,77 +1267,173 @@ Message have zero to two payloads.
```
- **Notes:** The passwords are not sent in some models of cameras namely
RLC-410 4mp, RLC-410 5mp, RLC-520 (fw 200710) in these cases the passwords
are blank. In some older cameras that do not use encryption at all these
passwords are completely visible to any network sniffers. Even the "encrypted"
cameras only have weak encryption that is easily broken since the
decryption key is fixed and well-known.
RLC-410 4mp, RLC-410 5mp, RLC-520 (fw 200710), RLC-811A in these cases the
passwords are blank. In some older cameras that do not use encryption at
all these passwords are completely visible to any network sniffers. Even
the "encrypted" cameras only have weak encryption that is easily broken
since the decryption key is fixed and well-known.
- 67: `<ConfigFileInfo> (FW Upgrade)`
- 59: `<UserList>`
- Client
- Client
- Header
- Header: Standard header
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 01 00 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 00 |
- Extension
- Extension
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<Extension version="1.1">
<userName>admin</userName>
</Extension>
```
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<ConfigFileInfo version="1.1">
<fileName>FIRMWAREFILE.pak</fileName>
<fileSize>SIZE_IN_BYTES</fileSize>
<updateParameter>0</updateParameter>
</ConfigFileInfo>
</body>
```
- Camera
- **Notes:** updateParameter refers to updating the settings. If 1 it will restore factory settings. If 0 it will keep current.
- Header: Standard header
- Camera
- Payload — Changing the password of testUser
- Header
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<UserList version="1.1">
<User>
<userName>admin</userName>
<password>password12</password>
<userLevel>1</userLevel>
<userSetState>none</userSetState>
</User>
<User>
<userName>testUser</userName>
<password>newPass</password>
<userLevel>0</userLevel>
<userSetState>modify</userSetState>
</User>
</UserList>
</body>
```
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
- Payload — creating a user
- Client
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<UserList version="1.1">
<User>
<userName>admin</userName>
<password>password12</password>
<userLevel>1</userLevel>
<userSetState>none</userSetState>
</User>
<User>
<userName>testUser</userName>
<password>testPass</password>
<userLevel>0</userLevel>
<userSetState>add</userSetState>
</User>
</UserList>
</body>
```
- Header
- Payload — deleting a user
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 94 58 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 6a |
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<UserList version="1.1">
<User>
<userName>admin</userName>
<password>password12</password>
<userLevel>1</userLevel>
<userSetState>none</userSetState>
</User>
<User>
<userName>testUser</userName>
<password>newPass</password>
<userLevel>0</userLevel>
<userSetState>delete</userSetState>
</User>
</UserList>
</body>
```
- Extension
- **Notes:** The passwords are not sent in some models of cameras namely
RLC-410 4mp, RLC-410 5mp, RLC-520 (fw 200710), RLC-811A in these cases the
passwords are blank. In some older cameras that do not use encryption at
all these passwords are completely visible to any network sniffers. Even
the "encrypted" cameras only have weak encryption that is easily broken
since the decryption key is fixed and well-known.
- **Notes:** The password field seems to only be needed when creating a user
or changing a users password.
- **Notes:** It does not appear like userLevel is modifiable (at least on
RLC-811A)
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<Extension version="1.1">
<binaryData>1</binaryData>
</Extension>
```
- 67: `<ConfigFileInfo> (FW Upgrade)`
- Payload
- Client
This contains binary data of the file but stops once the message size reaches
38000 bytes and continues in another packet. There does not appear to
be a checksum or hash and this part contains only the raw bytes of the file.
- Header
- Camera
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 01 00 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 00 |
- Header
- Extension
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<ConfigFileInfo version="1.1">
<fileName>FIRMWAREFILE.pak</fileName>
<fileSize>SIZE_IN_BYTES</fileSize>
<updateParameter>0</updateParameter>
</ConfigFileInfo>
</body>
```
- **Notes:** Last two messages repeat until all data is sent
- **Notes:** updateParameter refers to updating the settings. If 1 it will restore factory settings. If 0 it will keep current.
- Camera
- Header
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
- Client
- Header
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 94 58 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 6a |
- Extension
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<Extension version="1.1">
<binaryData>1</binaryData>
</Extension>
```
- Payload
This contains binary data of the file but stops once the message size reaches
38000 bytes and continues in another packet. There does not appear to
be a checksum or hash and this part contains only the raw bytes of the file.
- Camera
- Header
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
- **Notes:** Last two messages repeat until all data is sent
- 76: `<Ip>`
+1
View File
@@ -32,4 +32,5 @@ pub enum Command {
Image(super::image::Opt),
Battery(super::battery::Opt),
Services(super::services::Opt),
Users(super::users::Opt),
}
+9 -252
View File
@@ -5,28 +5,25 @@
//! The camera watch is used as an event to be triggered
//! whenever the camera is lost/updated
use anyhow::{anyhow, Context};
use futures::{stream::FuturesUnordered, FutureExt, StreamExt, TryFutureExt};
use futures::TryFutureExt;
use std::sync::{Arc, Weak};
#[cfg(feature = "pushnoti")]
use tokio::sync::watch::channel as watch;
use tokio::{
sync::{
mpsc::Receiver as MpscReceiver, mpsc::Sender as MpscSender, oneshot::channel as oneshot,
watch::Receiver as WatchReceiver,
mpsc::Sender as MpscSender, oneshot::channel as oneshot, watch::Receiver as WatchReceiver,
},
time::{sleep, Duration},
};
use tokio_util::sync::CancellationToken;
#[cfg(feature = "pushnoti")]
use super::PushNoti;
use super::{MdState, NeoCamCommand, NeoCamThreadState, Permit, UseCounter};
use super::{MdState, NeoCamCommand, NeoCamThreadState, Permit};
use crate::{config::CameraConfig, AnyResult, Result};
use neolink_core::{
bc_protocol::{BcCamera, StreamKind},
bcmedia::model::BcMedia,
};
use neolink_core::bc_protocol::BcCamera;
#[cfg(feature = "gstreamer")]
mod gst;
#[cfg(feature = "pushnoti")]
mod pushnoti;
/// This instance is the primary interface used throughout the app
///
@@ -233,50 +230,6 @@ impl NeoInstance {
}
}
#[cfg(feature = "pushnoti")]
pub(crate) async fn uid(&self) -> Result<String> {
let (reply_tx, reply_rx) = oneshot();
self.camera_control
.send(NeoCamCommand::GetUid(reply_tx))
.await?;
Ok(reply_rx.await?)
}
#[cfg(feature = "pushnoti")]
pub(crate) async fn push_notifications(&self) -> Result<WatchReceiver<Option<PushNoti>>> {
let uid = self.uid().await?;
let (instance_tx, instance_rx) = oneshot();
self.camera_control
.send(NeoCamCommand::PushNoti(instance_tx))
.await?;
let mut source_watch = instance_rx.await?;
let (fwatch_tx, fwatch_rx) = watch(None);
tokio::task::spawn(async move {
loop {
match source_watch
.wait_for(|i| {
fwatch_tx.borrow().as_ref() != i.as_ref()
&& i.as_ref()
.is_some_and(|i| i.message.contains(&format!("\"{uid}\"")))
})
.await
{
Ok(pn) => {
log::trace!("Forwarding push notification about {}", uid);
let _ = fwatch_tx.send_replace(pn.clone());
}
Err(e) => {
break Err(e);
}
}
}?;
AnyResult::Ok(())
});
Ok(fwatch_rx)
}
pub(crate) async fn motion(&self) -> Result<WatchReceiver<MdState>> {
let (instance_tx, instance_rx) = oneshot();
self.camera_control
@@ -346,202 +299,6 @@ impl NeoInstance {
timeout,
}
}
/// Streams a camera source while not paused
pub(crate) async fn stream_while_live(
&self,
stream: StreamKind,
) -> AnyResult<MpscReceiver<BcMedia>> {
let config = self.config().await?.borrow().clone();
let name = config.name.clone();
let media_rx = if config.pause.on_motion {
let (media_tx, media_rx) = tokio::sync::mpsc::channel(100);
let counter = UseCounter::new().await;
let mut md = self.motion().await?;
let mut tasks = FuturesUnordered::new();
// Stream for 5s on a new client always
// This lets us negotiate the camera stream type
let init_permit = counter.create_activated().await?;
tokio::spawn(
async {
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
drop(init_permit);
}
.map(|e| {
log::debug!("Init permit thread stopped {e:?}");
e
}),
);
// Create the permit for controlling the motion
let mut md_permit = {
let md_state = md.borrow_and_update().clone();
match md_state {
MdState::Start(_) => {
log::info!("{name}::{stream:?}: Starting with Motion");
counter.create_activated().await?
}
MdState::Stop(_) | MdState::Unknown => {
log::info!("{name}::{stream:?}: Waiting with Motion");
counter.create_deactivated().await?
}
}
};
// Now listen to the motion
let thread_name = name.clone();
tasks.push(tokio::spawn(
async move {
loop {
match md.changed().await {
Ok(_) => {
let md_state: MdState = md.borrow_and_update().clone();
match md_state {
MdState::Start(_) => {
log::info!("{thread_name}::{stream:?}: Motion Started");
md_permit.activate().await?;
}
MdState::Stop(_) => {
log::info!("{thread_name}::{stream:?}: Motion Stopped");
md_permit.deactivate().await?;
}
MdState::Unknown => {}
}
}
Err(e) => {
// Use break here so we can define the full type on the async closure
break AnyResult::Err(e.into());
}
}
}?;
AnyResult::Ok(())
}
.map(|e| {
log::debug!("Motion thread stopped {e:?}");
e
}),
));
#[cfg(pushnoti)]
{
// Creates a permit for controlling based on the PN
let pn_permit = counter.create_deactivated().await?;
let mut pn = self.push_notifications().await?;
pn.borrow_and_update(); // Ignore any PNs that have already been sent before this
let thread_name = name.clone();
tasks.push(tokio::spawn(
async move {
loop {
let noti: Option<PushNoti> = pn.borrow_and_update().clone();
if let Some(noti) = noti {
if noti.message.contains("Motion Alert from") {
log::info!(
"{thread_name}::{stream:?}: Push Notification Recieved"
);
let mut new_pn_permit = pn_permit.subscribe();
new_pn_permit.activate().await?;
tokio::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_secs(30))
.await;
drop(new_pn_permit);
});
}
}
if let Err(e) = pn.changed().await {
break Err(e);
}
}?;
AnyResult::Ok(())
}
.map(|e| {
log::debug!("PN thread stopped {e:?}");
e
}),
));
}
// Send the camera when the pemit is active
let camera_permit = counter.create_deactivated().await?;
let thread_camera = self.clone();
tokio::spawn(
async move {
loop {
if let Err(e) = camera_permit.aquired_users().await {
break AnyResult::Err(e);
}
log::debug!("Starting stream");
tokio::select! {
v = camera_permit.dropped_users() => {
log::debug!("Dropped users: {v:?}");
v
},
v = async {
log::debug!("Getting stream");
let mut stream = thread_camera.stream(stream).await?;
log::debug!("Got stream");
while let Some(media) = stream.recv().await {
media_tx.send(media).await?;
}
AnyResult::Ok(())
} => {
log::debug!("Stopped stream: {v:?}");
v
},
v = tasks.next() => {
log::debug!("Task failed: {v:?}");
Err(anyhow!("Task ended prematurly: {v:?}"))
}
}?;
log::debug!("Pausing stream");
}?;
drop(counter); // Make sure counter is owned by this thread
AnyResult::Ok(())
}
.map(|e| {
log::debug!("Stream thread stopped {e:?}");
e
}),
);
Ok(media_rx)
} else {
self.stream(stream).await
}?;
Ok(media_rx)
}
/// Streams a camera source
pub(crate) async fn stream(&self, stream: StreamKind) -> AnyResult<MpscReceiver<BcMedia>> {
let (media_tx, media_rx) = tokio::sync::mpsc::channel(100);
let config = self.config().await?.borrow().clone();
let strict = config.strict;
let thread_camera = self.clone();
tokio::task::spawn(
tokio::task::spawn(async move {
thread_camera
.run_task(move |cam| {
let media_tx = media_tx.clone();
Box::pin(async move {
let mut media_stream = cam.start_video(stream, 0, strict).await?;
log::trace!("Camera started");
while let Ok(media) = media_stream.get_data().await? {
media_tx.send(media).await?;
}
AnyResult::Ok(())
})
})
.await
})
.and_then(|res| async move {
log::debug!("Camera finished streaming: {res:?}");
Ok(())
}),
);
Ok(media_rx)
}
}
// A task that is run on a camera when the structure is dropped
+207
View File
@@ -0,0 +1,207 @@
use super::*;
use crate::common::UseCounter;
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use neolink_core::{bc_protocol::StreamKind, bcmedia::model::BcMedia};
use tokio::sync::mpsc::Receiver as MpscReceiver;
#[cfg(feature = "pushnoti")]
use crate::common::PushNoti;
impl NeoInstance {
/// Streams a camera source while not paused
pub(crate) async fn stream_while_live(
&self,
stream: StreamKind,
) -> AnyResult<MpscReceiver<BcMedia>> {
let config = self.config().await?.borrow().clone();
let name = config.name.clone();
let media_rx = if config.pause.on_motion {
let (media_tx, media_rx) = tokio::sync::mpsc::channel(100);
let counter = UseCounter::new().await;
let mut md = self.motion().await?;
let mut tasks = FuturesUnordered::new();
// Stream for 5s on a new client always
// This lets us negotiate the camera stream type
let init_permit = counter.create_activated().await?;
tokio::spawn(
async {
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
drop(init_permit);
}
.map(|e| {
log::debug!("Init permit thread stopped {e:?}");
e
}),
);
// Create the permit for controlling the motion
let mut md_permit = {
let md_state = md.borrow_and_update().clone();
match md_state {
MdState::Start(_) => {
log::info!("{name}::{stream:?}: Starting with Motion");
counter.create_activated().await?
}
MdState::Stop(_) | MdState::Unknown => {
log::info!("{name}::{stream:?}: Waiting with Motion");
counter.create_deactivated().await?
}
}
};
// Now listen to the motion
let thread_name = name.clone();
tasks.push(tokio::spawn(
async move {
loop {
match md.changed().await {
Ok(_) => {
let md_state: MdState = md.borrow_and_update().clone();
match md_state {
MdState::Start(_) => {
log::info!("{thread_name}::{stream:?}: Motion Started");
md_permit.activate().await?;
}
MdState::Stop(_) => {
log::info!("{thread_name}::{stream:?}: Motion Stopped");
md_permit.deactivate().await?;
}
MdState::Unknown => {}
}
}
Err(e) => {
// Use break here so we can define the full type on the async closure
break AnyResult::Err(e.into());
}
}
}?;
AnyResult::Ok(())
}
.map(|e| {
log::debug!("Motion thread stopped {e:?}");
e
}),
));
#[cfg(feature = "pushnoti")]
{
// Creates a permit for controlling based on the PN
let pn_permit = counter.create_deactivated().await?;
let mut pn = self.push_notifications().await?;
pn.borrow_and_update(); // Ignore any PNs that have already been sent before this
let thread_name = name.clone();
tasks.push(tokio::spawn(
async move {
loop {
let noti: Option<PushNoti> = pn.borrow_and_update().clone();
if let Some(noti) = noti {
if noti.message.contains("Motion Alert from") {
log::info!(
"{thread_name}::{stream:?}: Push Notification Recieved"
);
let mut new_pn_permit = pn_permit.subscribe();
new_pn_permit.activate().await?;
tokio::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_secs(30))
.await;
drop(new_pn_permit);
});
}
}
if let Err(e) = pn.changed().await {
break Err(e);
}
}?;
AnyResult::Ok(())
}
.map(|e| {
log::debug!("PN thread stopped {e:?}");
e
}),
));
}
// Send the camera when the pemit is active
let camera_permit = counter.create_deactivated().await?;
let thread_camera = self.clone();
tokio::spawn(
async move {
loop {
if let Err(e) = camera_permit.aquired_users().await {
break AnyResult::Err(e);
}
log::debug!("Starting stream");
tokio::select! {
v = camera_permit.dropped_users() => {
log::debug!("Dropped users: {v:?}");
v
},
v = async {
log::debug!("Getting stream");
let mut stream = thread_camera.stream(stream).await?;
log::debug!("Got stream");
while let Some(media) = stream.recv().await {
media_tx.send(media).await?;
}
AnyResult::Ok(())
} => {
log::debug!("Stopped stream: {v:?}");
v
},
v = tasks.next() => {
log::debug!("Task failed: {v:?}");
Err(anyhow!("Task ended prematurly: {v:?}"))
}
}?;
log::debug!("Pausing stream");
}?;
drop(counter); // Make sure counter is owned by this thread
AnyResult::Ok(())
}
.map(|e| {
log::debug!("Stream thread stopped {e:?}");
e
}),
);
Ok(media_rx)
} else {
self.stream(stream).await
}?;
Ok(media_rx)
}
/// Streams a camera source
pub(crate) async fn stream(&self, stream: StreamKind) -> AnyResult<MpscReceiver<BcMedia>> {
let (media_tx, media_rx) = tokio::sync::mpsc::channel(100);
let config = self.config().await?.borrow().clone();
let strict = config.strict;
let thread_camera = self.clone();
tokio::task::spawn(
tokio::task::spawn(async move {
thread_camera
.run_task(move |cam| {
let media_tx = media_tx.clone();
Box::pin(async move {
let mut media_stream = cam.start_video(stream, 0, strict).await?;
log::trace!("Camera started");
while let Ok(media) = media_stream.get_data().await? {
media_tx.send(media).await?;
}
AnyResult::Ok(())
})
})
.await
})
.and_then(|res| async move {
log::debug!("Camera finished streaming: {res:?}");
Ok(())
}),
);
Ok(media_rx)
}
}
+48
View File
@@ -0,0 +1,48 @@
use super::*;
use crate::common::PushNoti;
use tokio::sync::watch::channel as watch;
impl NeoInstance {
pub(crate) async fn uid(&self) -> Result<String> {
let (reply_tx, reply_rx) = oneshot();
self.camera_control
.send(NeoCamCommand::GetUid(reply_tx))
.await?;
Ok(reply_rx.await?)
}
pub(crate) async fn push_notifications(&self) -> Result<WatchReceiver<Option<PushNoti>>> {
let uid = self.uid().await?;
let (instance_tx, instance_rx) = oneshot();
self.camera_control
.send(NeoCamCommand::PushNoti(instance_tx))
.await?;
let mut source_watch = instance_rx.await?;
let (fwatch_tx, fwatch_rx) = watch(None);
tokio::task::spawn(async move {
loop {
match source_watch
.wait_for(|i| {
fwatch_tx.borrow().as_ref() != i.as_ref()
&& i.as_ref()
.is_some_and(|i| i.message.contains(&format!("\"{uid}\"")))
})
.await
{
Ok(pn) => {
log::trace!("Forwarding push notification about {}", uid);
let _ = fwatch_tx.send_replace(pn.clone());
}
Err(e) => {
break Err(e);
}
}
}?;
AnyResult::Ok(())
});
Ok(fwatch_rx)
}
}
+1 -2
View File
@@ -27,7 +27,7 @@ use super::{
use super::{PnRequest, PushNoti};
use crate::{config::CameraConfig, AnyResult, Result};
use neolink_core::bc_protocol::BcCamera;
#[cfg(feature = "gstreamer")]
#[allow(dead_code)]
pub(crate) enum NeoCamCommand {
HangUp,
@@ -81,7 +81,6 @@ impl NeoCam {
// other threads
let sender_cancel = me.cancel.clone();
let mut commander_rx = ReceiverStream::new(commander_rx);
#[cfg(feature = "gstreamer")]
let thread_commander_tx = commander_tx.clone();
let thread_watch_config_rx = watch_config_rx.clone();
#[cfg(feature = "pushnoti")]
+4
View File
@@ -52,6 +52,7 @@ mod services;
mod statusled;
#[cfg(feature = "gstreamer")]
mod talk;
mod users;
mod utils;
use cmdline::{Command, Opt};
@@ -143,6 +144,9 @@ async fn main() -> Result<()> {
Some(Command::Services(opts)) => {
services::main(opts, neo_reactor.clone()).await?;
}
Some(Command::Users(opts)) => {
users::main(opts, neo_reactor.clone()).await?;
}
}
Ok(())
+1 -1
View File
@@ -339,7 +339,7 @@ impl<'a> MqttBackend<'a> {
}
}
impl<'a> Drop for MqttBackend<'a> {
impl Drop for MqttBackend<'_> {
fn drop(&mut self) {
self.cancel.cancel();
}
+43
View File
@@ -0,0 +1,43 @@
use clap::{Parser, ValueEnum};
#[derive(Parser, Debug)]
pub struct Opt {
/// The name of the camera. Must be a name in the config
pub camera: String,
/// The action to perform
#[command(subcommand)]
pub cmd: UserAction,
}
#[derive(Parser, Debug)]
pub enum UserAction {
/// List users
List,
/// Create a new user
Add {
/// The username of the new user
user_name: String,
/// The password of the new user
password: String,
/// User type
user_type: UserType,
},
Password {
/// The username of the new user
user_name: String,
/// The password of the new user
password: String,
},
Delete {
/// The username of the user to delete
user_name: String,
},
}
#[derive(Parser, Debug, Clone, ValueEnum)]
pub enum UserType {
/// user_level = 0
User,
/// user_level = 1
Administrator,
}
+173
View File
@@ -0,0 +1,173 @@
///
/// # Neolink Users
///
/// This modules handles users
///
///
/// # Usage
///
/// ```bash
/// # To list users
/// neolink --config=config.toml users CameraName list
/// # To create a a new administrator
/// neolink --config=config.toml users CameraName add newuser hunter2 administrator
/// # To delete a user
/// neolink --config=config.toml users CameraName delete newuser
/// ```
///
/// There are two types of users:
/// - administrator — Can access the device and change device settings
/// - user — Can access the device but not change device settings
///
use anyhow::{anyhow, Context, Result};
mod cmdline;
use crate::common::NeoReactor;
pub(crate) use cmdline::*;
use neolink_core::bc::xml::UserList;
/// Entry point for the users subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
let camera = reactor.get(&opt.camera).await?;
match opt.cmd {
UserAction::List => {
let user_list = camera
.run_task(|cam| {
Box::pin(
async move { cam.get_users().await.context("Unable to list camera users") },
)
})
.await?;
match user_list {
UserList {
user_list: Some(users),
..
} => {
println!("{:<12} {:>4} {:>16}", "Username", "ID", "User type");
for user in users {
println!(
"{:<12} {:>4} {:>16}",
user.user_name,
user.user_id
.expect("user_id should exist when reading users"),
match user.user_level {
0 => "User".to_owned(),
1 => "Administrator".to_owned(),
n => format!("Unknown ({})", n),
},
);
}
}
_ => {
eprintln!("No users were included in response");
std::process::exit(1);
}
}
}
UserAction::Add {
user_name,
password,
user_type,
} => {
camera
.run_task(|cam| {
Box::pin({
let user_name = user_name.clone();
let password = password.clone();
let user_type = user_type.clone();
async move {
let user_list = cam
.get_users()
.await
.context("Failed to list current users")?;
let user_exists = match user_list.user_list {
Some(users) => users.iter().any(|user| user.user_name == user_name),
_ => false,
};
if user_exists {
return Err(anyhow!("The user '{}' already exists.", user_name));
}
cam.add_user(
user_name,
password,
match user_type {
UserType::User => 0,
UserType::Administrator => 1,
},
)
.await
.context("Unable to create user")
}
})
})
.await?;
println!("Successfully created user '{}'", user_name);
}
UserAction::Password {
user_name,
password,
} => {
camera
.run_task(|cam| {
Box::pin({
let user_name = user_name.clone();
let password = password.clone();
async move {
let user_list = cam
.get_users()
.await
.context("Failed to list current users")?;
let user_exists = match user_list.user_list {
Some(users) => users.iter().any(|user| user.user_name == user_name),
_ => false,
};
if !user_exists {
return Err(anyhow!("The user '{}' does not exist.", user_name));
}
cam.modify_user(user_name, password)
.await
.context("Unable to create user")
}
})
})
.await?;
println!("Successfully changed the password of '{}'", user_name);
}
UserAction::Delete { user_name } => {
camera
.run_task(|cam| {
Box::pin({
let user_name = user_name.clone();
async move {
let user_list = cam
.get_users()
.await
.context("Failed to list current users")?;
let user_exists = match user_list.user_list {
Some(users) => users.iter().any(|user| user.user_name == user_name),
_ => false,
};
if !user_exists {
return Err(anyhow!("The user '{}' does not exist.", user_name));
}
cam.delete_user(user_name)
.await
.context("Unable to delete user")
}
})
})
.await?;
println!("Successfully removed user '{}'", user_name);
}
}
Ok(())
}