Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e05e7844b | ||
|
|
43b62090c8 | ||
|
|
7a66473ab9 | ||
|
|
a30f403dc4 | ||
|
|
76833e6242 | ||
|
|
1518ab24bb | ||
|
|
c3353591ae | ||
|
|
18c4d56826 | ||
|
|
e9e66b1a44 | ||
|
|
1499503789 | ||
|
|
fb9df1d586 | ||
|
|
1517077564 | ||
|
|
e6c6f5ca62 | ||
|
|
ed4a5ea001 | ||
|
|
4f8fb6c7b5 | ||
|
|
fb956c399e | ||
|
|
81f77f461c | ||
|
|
5279a34bcb | ||
|
|
d09874eca5 | ||
|
|
13081f745f | ||
|
|
a14336fe3c |
No files matched your search
+14
-23
@@ -4,12 +4,9 @@ on:
|
|||||||
push:
|
push:
|
||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
|
||||||
tag:
|
env:
|
||||||
description: 'Tag to force the cross build on'
|
rust_version: "1.82.0"
|
||||||
required: false
|
|
||||||
type: string
|
|
||||||
default: ''
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
pre_job:
|
pre_job:
|
||||||
@@ -39,17 +36,17 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
name: Checkout onto ${{ runner.os }}
|
name: Checkout onto ${{ runner.os }}
|
||||||
- if: runner.os == 'Linux'
|
- if: runner.os == 'Linux'
|
||||||
name: apt install gstreamer
|
name: apt install linux deps
|
||||||
run: |
|
run: |
|
||||||
sudo apt update
|
sudo apt update
|
||||||
sudo apt install -y aptitude
|
sudo apt install -y aptitude
|
||||||
sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev protobuf-compiler libssl-dev
|
sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev protobuf-compiler libssl-dev
|
||||||
- if: runner.os == 'Windows'
|
- if: runner.os == 'Windows'
|
||||||
name: Install Gstreamer
|
name: Install Windows deps
|
||||||
run: |
|
run: |
|
||||||
# Gstreamer
|
# Gstreamer
|
||||||
choco install -y --no-progress gstreamer --version=1.20.0
|
choco install -y --no-progress gstreamer --version=1.24.2
|
||||||
choco install -y --no-progress gstreamer-devel --version=1.20.0
|
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\'
|
$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
|
# 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)) {
|
if (-not (Test-Path -Path "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64" -PathType Container)) {
|
||||||
@@ -77,21 +74,17 @@ jobs:
|
|||||||
$env:OPENSSL_DIR='D:\\Program Files\OpenSSL\'
|
$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
|
# 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_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 "$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_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 "OPENSSL_DIR=$env:OPENSSL_DIR"
|
||||||
Add-Content -Path $env:GITHUB_ENV -Value "PKG_CONFIG_PATH=$env:PKG_CONFIG_PATH"
|
|
||||||
|
|
||||||
# One last check on directories
|
# One last check on directories
|
||||||
dir "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
|
dir "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
|
||||||
dir "$env:OPENSSL_DIR"
|
dir "$env:OPENSSL_DIR"
|
||||||
- if: runner.os == 'macOS'
|
- if: runner.os == 'macOS'
|
||||||
name: Install Gstreamer on macOS
|
name: Install macOS deps
|
||||||
run: |
|
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"
|
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 /
|
sudo installer -verbose -pkg "$(pwd)/gstreamer-devel.pkg" -target /
|
||||||
@@ -137,7 +130,7 @@ jobs:
|
|||||||
if: needs.pre_job.outputs.should_skip != 'true'
|
if: needs.pre_job.outputs.should_skip != 'true'
|
||||||
name: cross
|
name: cross
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container: "node:current-bullseye-slim"
|
container: "node:current-bookworm-slim"
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@@ -164,8 +157,6 @@ jobs:
|
|||||||
pkgconfig: i386-linux-gnu
|
pkgconfig: i386-linux-gnu
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
|
||||||
ref: ${{ github.event.inputs.tag }}
|
|
||||||
- name: Install basic tools
|
- name: Install basic tools
|
||||||
run: |
|
run: |
|
||||||
apt-get update
|
apt-get update
|
||||||
@@ -190,7 +181,7 @@ jobs:
|
|||||||
echo "${HOME}/.cargo/bin" >> "${GITHUB_PATH}"
|
echo "${HOME}/.cargo/bin" >> "${GITHUB_PATH}"
|
||||||
- name: Install ${{ matrix.arch }} Rust toolchain
|
- name: Install ${{ matrix.arch }} Rust toolchain
|
||||||
run: |
|
run: |
|
||||||
rustup default 1.79.0
|
rustup default "${{ env.rust_version }}"
|
||||||
rustup target add ${TARGET}
|
rustup target add ${TARGET}
|
||||||
env:
|
env:
|
||||||
TARGET: ${{ matrix.target }}
|
TARGET: ${{ matrix.target }}
|
||||||
@@ -226,8 +217,6 @@ jobs:
|
|||||||
SECRET: "${{ secrets.DOCKER_TOKEN }}"
|
SECRET: "${{ secrets.DOCKER_TOKEN }}"
|
||||||
- name: Check out the repo
|
- name: Check out the repo
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
|
||||||
ref: ${{ github.event.inputs.tag }}
|
|
||||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||||
- name: Convert username to lower case for docker
|
- name: Convert username to lower case for docker
|
||||||
id: string_user
|
id: string_user
|
||||||
@@ -297,8 +286,9 @@ jobs:
|
|||||||
echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}"
|
echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}"
|
||||||
env:
|
env:
|
||||||
REPO_NAME: ${{ steps.docker_repo.outputs.DOCKER_NWO }}
|
REPO_NAME: ${{ steps.docker_repo.outputs.DOCKER_NWO }}
|
||||||
- name: Install latest rust
|
- name: Install rust
|
||||||
run: |
|
run: |
|
||||||
|
rustup default "${{ env.rust_version }}"
|
||||||
rustup toolchain install stable
|
rustup toolchain install stable
|
||||||
- name: Install toml-cli
|
- name: Install toml-cli
|
||||||
run: |
|
run: |
|
||||||
@@ -356,8 +346,9 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Install latest rust
|
- name: Install rust
|
||||||
run: |
|
run: |
|
||||||
|
rustup default "${{ env.rust_version }}"
|
||||||
rustup toolchain install stable
|
rustup toolchain install stable
|
||||||
- name: Install toml-cli
|
- name: Install toml-cli
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -35,9 +35,13 @@ jobs:
|
|||||||
rustup override set nightly
|
rustup override set nightly
|
||||||
- name: Run clippy manually
|
- name: Run clippy manually
|
||||||
run: |
|
run: |
|
||||||
|
echo "All Features"
|
||||||
cargo +nightly clippy --workspace --all-targets --all-features || exit 1
|
cargo +nightly clippy --workspace --all-targets --all-features || exit 1
|
||||||
|
echo "No Features"
|
||||||
cargo +nightly clippy --workspace --all-targets --no-default-features || exit 1
|
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
|
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
|
cargo +nightly clippy --workspace --all-targets --no-default-features --features=pushnoti || exit 1
|
||||||
|
|
||||||
check_fmt:
|
check_fmt:
|
||||||
|
|||||||
+1
-1
@@ -27,4 +27,4 @@
|
|||||||
token.toml
|
token.toml
|
||||||
|
|
||||||
# Debug FCM build
|
# Debug FCM build
|
||||||
./crates/fcm-push-listener/
|
crates/fcm-push-listener
|
||||||
Generated
+3
-22
@@ -1,6 +1,6 @@
|
|||||||
# This file is automatically @generated by Cargo.
|
# This file is automatically @generated by Cargo.
|
||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 3
|
version = 4
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "addr2line"
|
name = "addr2line"
|
||||||
@@ -839,25 +839,6 @@ dependencies = [
|
|||||||
"webpki-roots",
|
"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]]
|
[[package]]
|
||||||
name = "fixedbitset"
|
name = "fixedbitset"
|
||||||
version = "0.4.2"
|
version = "0.4.2"
|
||||||
@@ -1895,7 +1876,7 @@ dependencies = [
|
|||||||
"crossbeam-channel",
|
"crossbeam-channel",
|
||||||
"dirs",
|
"dirs",
|
||||||
"env_logger 0.11.3",
|
"env_logger 0.11.3",
|
||||||
"fcm-push-listener 2.0.3",
|
"fcm-push-listener",
|
||||||
"futures",
|
"futures",
|
||||||
"gstreamer",
|
"gstreamer",
|
||||||
"gstreamer-app",
|
"gstreamer-app",
|
||||||
@@ -2339,7 +2320,7 @@ dependencies = [
|
|||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
"env_logger 0.10.2",
|
"env_logger 0.10.2",
|
||||||
"fcm-push-listener 2.0.3",
|
"fcm-push-listener",
|
||||||
"lazy_static",
|
"lazy_static",
|
||||||
"log",
|
"log",
|
||||||
"neolink_core",
|
"neolink_core",
|
||||||
|
|||||||
+1
-1
@@ -47,7 +47,7 @@ validator = {version="0.18.1", features = ["derive"] }
|
|||||||
tikv-jemallocator = "0.5"
|
tikv-jemallocator = "0.5"
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = ["gstreamer", "pushnoti"]
|
default = ["gstreamer"]
|
||||||
gstreamer = [
|
gstreamer = [
|
||||||
"dep:gstreamer",
|
"dep:gstreamer",
|
||||||
"dep:gstreamer-app",
|
"dep:gstreamer-app",
|
||||||
|
|||||||
@@ -374,6 +374,36 @@ Available features are:
|
|||||||
- `battery`: This adds a battery level sensor to home assistant
|
- `battery`: This adds a battery level sensor to home assistant
|
||||||
- `siren`: Adds a siren button 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
|
### Pause
|
||||||
|
|
||||||
To use the pause feature you will need to adjust your config file as such:
|
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
|
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
|
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
|
You can make neolink stop active streams when there are no rtsp clients using
|
||||||
|
|
||||||
```toml
|
```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
|
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
|
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
|
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
|
### Docker
|
||||||
|
|
||||||
|
|||||||
@@ -90,10 +90,8 @@ fn bc_modern_msg<'a>(
|
|||||||
E::add_context(input, ctx, E::from_error_kind(input, kind))
|
E::add_context(input, ctx, E::from_error_kind(input, kind))
|
||||||
}
|
}
|
||||||
|
|
||||||
let ext_len = match header.payload_offset {
|
// If missing payload_offset treat all as payload
|
||||||
Some(off) => off,
|
let ext_len = header.payload_offset.unwrap_or_default();
|
||||||
_ => 0, // If missing payload_offset treat all as payload
|
|
||||||
};
|
|
||||||
|
|
||||||
let (buf, ext_buf) = take(ext_len)(buf)?;
|
let (buf, ext_buf) = take(ext_len)(buf)?;
|
||||||
let payload_len = header.body_len - ext_len;
|
let payload_len = header.body_len - ext_len;
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ pub const MSG_ID_GET_SERVICE_PORTS: u32 = 37;
|
|||||||
pub const MSG_ID_GET_EMAIL: u32 = 42;
|
pub const MSG_ID_GET_EMAIL: u32 = 42;
|
||||||
/// Set email settings
|
/// Set email settings
|
||||||
pub const MSG_ID_SET_EMAIL: u32 = 43;
|
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
|
/// Version messages have this ID
|
||||||
pub const MSG_ID_VERSION: u32 = 80;
|
pub const MSG_ID_VERSION: u32 = 80;
|
||||||
/// Ping messages have this ID
|
/// Ping messages have this ID
|
||||||
@@ -192,8 +196,11 @@ pub struct BcMeta {
|
|||||||
pub stream_type: u8,
|
pub stream_type: u8,
|
||||||
/// On modern messages this is the response code
|
/// On modern messages this is the response code
|
||||||
/// When sending a command it is set to `0`. The reply from the camera can be
|
/// When sending a command it is set to `0`. The reply from the camera can be
|
||||||
|
///
|
||||||
/// - `200` for OK
|
/// - `200` for OK
|
||||||
|
///
|
||||||
/// - `400` for bad request
|
/// - `400` for bad request
|
||||||
|
///
|
||||||
/// A malformed packet will return a `400` code
|
/// A malformed packet will return a `400` code
|
||||||
pub response_code: u16,
|
pub response_code: u16,
|
||||||
/// A message ID is used to match replies with requests. The camera will parrot back
|
/// 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,
|
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)]
|
#[derive(Debug)]
|
||||||
pub(crate) struct BcContext {
|
pub(crate) struct BcContext {
|
||||||
pub(crate) credentials: Credentials,
|
pub(crate) credentials: Credentials,
|
||||||
|
|||||||
@@ -138,6 +138,9 @@ pub struct BcXml {
|
|||||||
/// EmailTask for turning the email notifications on/off
|
/// EmailTask for turning the email notifications on/off
|
||||||
#[serde(rename = "EmailTask", skip_serializing_if = "Option::is_none")]
|
#[serde(rename = "EmailTask", skip_serializing_if = "Option::is_none")]
|
||||||
pub email_task: Option<EmailTask>,
|
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 {
|
impl BcXml {
|
||||||
@@ -1566,6 +1569,52 @@ pub struct Schedule {
|
|||||||
pub time_block_list: TimeBlockList,
|
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
|
/// Convience function to return the xml version used throughout the library
|
||||||
pub fn xml_ver() -> String {
|
pub fn xml_ver() -> String {
|
||||||
"1.1".to_string()
|
"1.1".to_string()
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ mod support;
|
|||||||
mod talk;
|
mod talk;
|
||||||
mod time;
|
mod time;
|
||||||
mod uid;
|
mod uid;
|
||||||
|
mod users;
|
||||||
mod version;
|
mod version;
|
||||||
|
|
||||||
pub(crate) use connection::*;
|
pub(crate) use connection::*;
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ pub struct BcStream<'a> {
|
|||||||
rx: &'a mut ReceiverStream<Result<Bc>>,
|
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>;
|
type Item = Result<Bc>;
|
||||||
|
|
||||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Bc>>> {
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Bc>>> {
|
||||||
|
|||||||
@@ -214,7 +214,7 @@ impl ToSocketAddrsOrUid for SocketAddrV6 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> ToSocketAddrsOrUid for &'a [SocketAddr] {
|
impl ToSocketAddrsOrUid for &'_ [SocketAddr] {
|
||||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||||
|
|
||||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||||
|
|||||||
@@ -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(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -34,15 +34,6 @@ impl Decoder for BcUdpCodex {
|
|||||||
type Item = BcUdp;
|
type Item = BcUdp;
|
||||||
type Error = Error;
|
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>> {
|
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||||
log::trace!("Decoding:");
|
log::trace!("Decoding:");
|
||||||
if src.is_empty() {
|
if src.is_empty() {
|
||||||
|
|||||||
@@ -53,14 +53,6 @@ async fn main() -> Result<()> {
|
|||||||
Ok(())
|
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<()> {
|
async fn cam_tasks(name: &str, camera: BcCamera, addr: SocketAddr) -> Result<()> {
|
||||||
let support = camera.get_support().await?;
|
let support = camera.get_support().await?;
|
||||||
if support.email.is_some_and(|v| v > 0) {
|
if support.email.is_some_and(|v| v > 0) {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ edition = "2021"
|
|||||||
anyhow = "1.0.71"
|
anyhow = "1.0.71"
|
||||||
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
||||||
env_logger = "0.10.0"
|
env_logger = "0.10.0"
|
||||||
# fcm-push-listener = { path = "../fcm-push-listener" }
|
|
||||||
fcm-push-listener = { version = "2.0.3" }
|
fcm-push-listener = { version = "2.0.3" }
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||||
|
|||||||
+102
-6
@@ -1267,13 +1267,109 @@ Message have zero to two payloads.
|
|||||||
```
|
```
|
||||||
|
|
||||||
- **Notes:** The passwords are not sent in some models of cameras namely
|
- **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
|
RLC-410 4mp, RLC-410 5mp, RLC-520 (fw 200710), RLC-811A in these cases the
|
||||||
are blank. In some older cameras that do not use encryption at all these
|
passwords are blank. In some older cameras that do not use encryption at
|
||||||
passwords are completely visible to any network sniffers. Even the "encrypted"
|
all these passwords are completely visible to any network sniffers. Even
|
||||||
cameras only have weak encryption that is easily broken since the
|
the "encrypted" cameras only have weak encryption that is easily broken
|
||||||
decryption key is fixed and well-known.
|
since the decryption key is fixed and well-known.
|
||||||
|
|
||||||
- 67: `<ConfigFileInfo> (FW Upgrade)`
|
- 59: `<UserList>`
|
||||||
|
|
||||||
|
- Client
|
||||||
|
|
||||||
|
- Header: Standard header
|
||||||
|
|
||||||
|
- Extension
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<?xml version="1.0" encoding="UTF-8" ?>
|
||||||
|
<Extension version="1.1">
|
||||||
|
<userName>admin</userName>
|
||||||
|
</Extension>
|
||||||
|
```
|
||||||
|
|
||||||
|
- Camera
|
||||||
|
|
||||||
|
- Header: Standard header
|
||||||
|
|
||||||
|
- Payload — Changing the password of testUser
|
||||||
|
|
||||||
|
```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>
|
||||||
|
```
|
||||||
|
|
||||||
|
- Payload — creating a user
|
||||||
|
|
||||||
|
```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>
|
||||||
|
```
|
||||||
|
|
||||||
|
- Payload — deleting a user
|
||||||
|
|
||||||
|
```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>
|
||||||
|
```
|
||||||
|
|
||||||
|
- **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)
|
||||||
|
|
||||||
|
- 67: `<ConfigFileInfo> (FW Upgrade)`
|
||||||
|
|
||||||
- Client
|
- Client
|
||||||
|
|
||||||
|
|||||||
@@ -32,4 +32,5 @@ pub enum Command {
|
|||||||
Image(super::image::Opt),
|
Image(super::image::Opt),
|
||||||
Battery(super::battery::Opt),
|
Battery(super::battery::Opt),
|
||||||
Services(super::services::Opt),
|
Services(super::services::Opt),
|
||||||
|
Users(super::users::Opt),
|
||||||
}
|
}
|
||||||
+9
-252
@@ -5,28 +5,25 @@
|
|||||||
//! The camera watch is used as an event to be triggered
|
//! The camera watch is used as an event to be triggered
|
||||||
//! whenever the camera is lost/updated
|
//! whenever the camera is lost/updated
|
||||||
use anyhow::{anyhow, Context};
|
use anyhow::{anyhow, Context};
|
||||||
use futures::{stream::FuturesUnordered, FutureExt, StreamExt, TryFutureExt};
|
use futures::TryFutureExt;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
#[cfg(feature = "pushnoti")]
|
|
||||||
use tokio::sync::watch::channel as watch;
|
|
||||||
use tokio::{
|
use tokio::{
|
||||||
sync::{
|
sync::{
|
||||||
mpsc::Receiver as MpscReceiver, mpsc::Sender as MpscSender, oneshot::channel as oneshot,
|
mpsc::Sender as MpscSender, oneshot::channel as oneshot, watch::Receiver as WatchReceiver,
|
||||||
watch::Receiver as WatchReceiver,
|
|
||||||
},
|
},
|
||||||
time::{sleep, Duration},
|
time::{sleep, Duration},
|
||||||
};
|
};
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
#[cfg(feature = "pushnoti")]
|
use super::{MdState, NeoCamCommand, NeoCamThreadState, Permit};
|
||||||
use super::PushNoti;
|
|
||||||
use super::{MdState, NeoCamCommand, NeoCamThreadState, Permit, UseCounter};
|
|
||||||
use crate::{config::CameraConfig, AnyResult, Result};
|
use crate::{config::CameraConfig, AnyResult, Result};
|
||||||
use neolink_core::{
|
use neolink_core::bc_protocol::BcCamera;
|
||||||
bc_protocol::{BcCamera, StreamKind},
|
|
||||||
bcmedia::model::BcMedia,
|
|
||||||
};
|
|
||||||
#[cfg(feature = "gstreamer")]
|
#[cfg(feature = "gstreamer")]
|
||||||
|
mod gst;
|
||||||
|
|
||||||
|
#[cfg(feature = "pushnoti")]
|
||||||
|
mod pushnoti;
|
||||||
|
|
||||||
/// This instance is the primary interface used throughout the app
|
/// 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>> {
|
pub(crate) async fn motion(&self) -> Result<WatchReceiver<MdState>> {
|
||||||
let (instance_tx, instance_rx) = oneshot();
|
let (instance_tx, instance_rx) = oneshot();
|
||||||
self.camera_control
|
self.camera_control
|
||||||
@@ -346,202 +299,6 @@ impl NeoInstance {
|
|||||||
timeout,
|
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
|
// A task that is run on a camera when the structure is dropped
|
||||||
|
|||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ use super::{
|
|||||||
use super::{PnRequest, PushNoti};
|
use super::{PnRequest, PushNoti};
|
||||||
use crate::{config::CameraConfig, AnyResult, Result};
|
use crate::{config::CameraConfig, AnyResult, Result};
|
||||||
use neolink_core::bc_protocol::BcCamera;
|
use neolink_core::bc_protocol::BcCamera;
|
||||||
#[cfg(feature = "gstreamer")]
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub(crate) enum NeoCamCommand {
|
pub(crate) enum NeoCamCommand {
|
||||||
HangUp,
|
HangUp,
|
||||||
@@ -81,7 +81,6 @@ impl NeoCam {
|
|||||||
// other threads
|
// other threads
|
||||||
let sender_cancel = me.cancel.clone();
|
let sender_cancel = me.cancel.clone();
|
||||||
let mut commander_rx = ReceiverStream::new(commander_rx);
|
let mut commander_rx = ReceiverStream::new(commander_rx);
|
||||||
#[cfg(feature = "gstreamer")]
|
|
||||||
let thread_commander_tx = commander_tx.clone();
|
let thread_commander_tx = commander_tx.clone();
|
||||||
let thread_watch_config_rx = watch_config_rx.clone();
|
let thread_watch_config_rx = watch_config_rx.clone();
|
||||||
#[cfg(feature = "pushnoti")]
|
#[cfg(feature = "pushnoti")]
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ mod services;
|
|||||||
mod statusled;
|
mod statusled;
|
||||||
#[cfg(feature = "gstreamer")]
|
#[cfg(feature = "gstreamer")]
|
||||||
mod talk;
|
mod talk;
|
||||||
|
mod users;
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
use cmdline::{Command, Opt};
|
use cmdline::{Command, Opt};
|
||||||
@@ -143,6 +144,9 @@ async fn main() -> Result<()> {
|
|||||||
Some(Command::Services(opts)) => {
|
Some(Command::Services(opts)) => {
|
||||||
services::main(opts, neo_reactor.clone()).await?;
|
services::main(opts, neo_reactor.clone()).await?;
|
||||||
}
|
}
|
||||||
|
Some(Command::Users(opts)) => {
|
||||||
|
users::main(opts, neo_reactor.clone()).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
+1
-1
@@ -339,7 +339,7 @@ impl<'a> MqttBackend<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Drop for MqttBackend<'a> {
|
impl Drop for MqttBackend<'_> {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.cancel.cancel();
|
self.cancel.cancel();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,
|
||||||
|
}
|
||||||
@@ -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(())
|
||||||
|
}
|
||||||
Reference in new issue
Block a user