oxvif 0.7.3

Async Rust client library for the ONVIF IP camera protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use super::*;
use async_trait::async_trait;
use std::sync::{Arc, Mutex};

use crate::transport::TransportError;

// ── SequenceTransport: returns responses in order ─────────────────────────

struct SequenceTransport {
    responses: Mutex<Vec<String>>,
}

impl SequenceTransport {
    fn new(responses: &[&str]) -> Arc<Self> {
        Arc::new(Self {
            responses: Mutex::new(responses.iter().map(|s| s.to_string()).rev().collect()),
        })
    }
}

#[async_trait]
impl Transport for SequenceTransport {
    async fn soap_post(
        &self,
        _url: &str,
        _action: &str,
        _body: String,
    ) -> Result<String, TransportError> {
        let mut stack = self.responses.lock().unwrap();
        stack.pop().map(Ok).unwrap_or_else(|| {
            Err(TransportError::HttpStatus {
                status: 503,
                body: "no more responses".into(),
            })
        })
    }
}

// ── ErrorTransport: always fails ─────────────────────────────────────────

struct ErrorTransport {
    status: u16,
}

#[async_trait]
impl Transport for ErrorTransport {
    async fn soap_post(
        &self,
        _url: &str,
        _action: &str,
        _body: String,
    ) -> Result<String, TransportError> {
        Err(TransportError::HttpStatus {
            status: self.status,
            body: format!("HTTP {}", self.status),
        })
    }
}

// ── XML fixtures ──────────────────────────────────────────────────────────

/// Full capabilities response including all service URLs (Media, PTZ, Imaging,
/// Events, Recording, Search, Replay, Media2).
fn caps_full_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:tds="http://www.onvif.org/ver10/device/wsdl"
                  xmlns:tt="http://www.onvif.org/ver10/schema">
      <s:Body>
        <tds:GetCapabilitiesResponse>
          <tds:Capabilities>
            <tt:Device>   <tt:XAddr>http://cam/onvif/device</tt:XAddr>    </tt:Device>
            <tt:Media>    <tt:XAddr>http://cam/onvif/media</tt:XAddr>     </tt:Media>
            <tt:PTZ>      <tt:XAddr>http://cam/onvif/ptz</tt:XAddr>       </tt:PTZ>
            <tt:Imaging>  <tt:XAddr>http://cam/onvif/imaging</tt:XAddr>   </tt:Imaging>
            <tt:Events>   <tt:XAddr>http://cam/onvif/events</tt:XAddr>    </tt:Events>
            <tt:Extension>
              <tt:Recording> <tt:XAddr>http://cam/onvif/recording</tt:XAddr> </tt:Recording>
              <tt:Search>    <tt:XAddr>http://cam/onvif/search</tt:XAddr>    </tt:Search>
              <tt:Replay>    <tt:XAddr>http://cam/onvif/replay</tt:XAddr>    </tt:Replay>
              <tt:Media2>    <tt:XAddr>http://cam/onvif/media2</tt:XAddr>    </tt:Media2>
            </tt:Extension>
          </tds:Capabilities>
        </tds:GetCapabilitiesResponse>
      </s:Body>
    </s:Envelope>"#
}

/// Minimal capabilities response — only a Device URL, no service URLs.
fn caps_device_only_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:tds="http://www.onvif.org/ver10/device/wsdl"
                  xmlns:tt="http://www.onvif.org/ver10/schema">
      <s:Body>
        <tds:GetCapabilitiesResponse>
          <tds:Capabilities>
            <tt:Device><tt:XAddr>http://cam/onvif/device</tt:XAddr></tt:Device>
          </tds:Capabilities>
        </tds:GetCapabilitiesResponse>
      </s:Body>
    </s:Envelope>"#
}

fn system_date_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:tds="http://www.onvif.org/ver10/device/wsdl"
                  xmlns:tt="http://www.onvif.org/ver10/schema">
      <s:Body>
        <tds:GetSystemDateAndTimeResponse>
          <tds:SystemDateAndTime>
            <tt:DateTimeType>NTP</tt:DateTimeType>
            <tt:DaylightSavings>false</tt:DaylightSavings>
            <tt:TimeZone><tt:TZ>UTC</tt:TZ></tt:TimeZone>
            <tt:UTCDateTime>
              <tt:Time><tt:Hour>12</tt:Hour><tt:Minute>0</tt:Minute><tt:Second>0</tt:Second></tt:Time>
              <tt:Date><tt:Year>2026</tt:Year><tt:Month>4</tt:Month><tt:Day>2</tt:Day></tt:Date>
            </tt:UTCDateTime>
          </tds:SystemDateAndTime>
        </tds:GetSystemDateAndTimeResponse>
      </s:Body>
    </s:Envelope>"#
}

fn profiles_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:trt="http://www.onvif.org/ver10/media/wsdl"
                  xmlns:tt="http://www.onvif.org/ver10/schema">
      <s:Body>
        <trt:GetProfilesResponse>
          <trt:Profiles token="Profile_1" fixed="true">
            <tt:Name>mainStream</tt:Name>
          </trt:Profiles>
        </trt:GetProfilesResponse>
      </s:Body>
    </s:Envelope>"#
}

fn stream_uri_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:trt="http://www.onvif.org/ver10/media/wsdl"
                  xmlns:tt="http://www.onvif.org/ver10/schema">
      <s:Body>
        <trt:GetStreamUriResponse>
          <trt:MediaUri>
            <tt:Uri>rtsp://cam:554/stream1</tt:Uri>
            <tt:InvalidAfterConnect>false</tt:InvalidAfterConnect>
            <tt:InvalidAfterReboot>false</tt:InvalidAfterReboot>
            <tt:Timeout>PT0S</tt:Timeout>
          </trt:MediaUri>
        </trt:GetStreamUriResponse>
      </s:Body>
    </s:Envelope>"#
}

fn ptz_stop_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:tptz="http://www.onvif.org/ver20/ptz/wsdl">
      <s:Body><tptz:StopResponse/></s:Body>
    </s:Envelope>"#
}

fn imaging_settings_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:timg="http://www.onvif.org/ver20/imaging/wsdl"
                  xmlns:tt="http://www.onvif.org/ver10/schema">
      <s:Body>
        <timg:GetImagingSettingsResponse>
          <timg:ImagingSettings>
            <tt:Brightness>50</tt:Brightness>
            <tt:Contrast>50</tt:Contrast>
          </timg:ImagingSettings>
        </timg:GetImagingSettingsResponse>
      </s:Body>
    </s:Envelope>"#
}

fn recordings_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:trc="http://www.onvif.org/ver10/recording/wsdl"
                  xmlns:tt="http://www.onvif.org/ver10/schema">
      <s:Body>
        <trc:GetRecordingsResponse>
          <trc:RecordingItems Token="rec1">
            <trc:RecordingInformation>
              <tt:RecordingStatus>Recording</tt:RecordingStatus>
            </trc:RecordingInformation>
          </trc:RecordingItems>
        </trc:GetRecordingsResponse>
      </s:Body>
    </s:Envelope>"#
}

fn soap_fault_xml() -> &'static str {
    r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
      <s:Body>
        <s:Fault>
          <s:Code><s:Value>s:Sender</s:Value></s:Code>
          <s:Reason><s:Text xml:lang="en">Not Authorized</s:Text></s:Reason>
        </s:Fault>
      </s:Body>
    </s:Envelope>"#
}

// ── Helper: build a session from a sequence of SOAP responses ─────────────
// The first response is always for GetCapabilities (caps_full_xml).

async fn session_with(method_responses: &[&str]) -> OnvifSession {
    let mut responses = vec![caps_full_xml()];
    responses.extend_from_slice(method_responses);
    OnvifSession::builder("http://cam/onvif/device")
        .with_transport(SequenceTransport::new(&responses))
        .build()
        .await
        .expect("session build failed")
}

// ── Builder tests ─────────────────────────────────────────────────────────

#[tokio::test]
async fn test_builder_stores_capabilities() {
    let session = session_with(&[]).await;
    let caps = session.capabilities();
    assert_eq!(caps.media.url.as_deref(), Some("http://cam/onvif/media"));
    assert_eq!(caps.ptz_url.as_deref(), Some("http://cam/onvif/ptz"));
    assert_eq!(
        caps.imaging_url.as_deref(),
        Some("http://cam/onvif/imaging")
    );
    assert_eq!(caps.events.url.as_deref(), Some("http://cam/onvif/events"));
    assert_eq!(
        caps.recording_url.as_deref(),
        Some("http://cam/onvif/recording")
    );
    assert_eq!(caps.search_url.as_deref(), Some("http://cam/onvif/search"));
    assert_eq!(caps.replay_url.as_deref(), Some("http://cam/onvif/replay"));
    assert_eq!(caps.media2_url.as_deref(), Some("http://cam/onvif/media2"));
}

#[tokio::test]
async fn test_builder_with_clock_sync_calls_date_time_first() {
    // clock sync → GetCapabilities: two responses required, in that order
    let transport = SequenceTransport::new(&[system_date_xml(), caps_full_xml()]);
    let session = OnvifSession::builder("http://cam/onvif/device")
        .with_clock_sync()
        .with_transport(transport)
        .build()
        .await
        .expect("session with clock sync failed");

    // Session must be functional after the two-call init sequence
    assert!(session.capabilities().media.url.is_some());
}

#[tokio::test]
async fn test_builder_without_clock_sync_uses_one_call() {
    // Without clock sync only GetCapabilities is called
    let transport = SequenceTransport::new(&[caps_full_xml()]);
    OnvifSession::builder("http://cam/onvif/device")
        .with_transport(transport)
        .build()
        .await
        .expect("build without clock sync failed");
}

#[tokio::test]
async fn test_builder_transport_error_propagates() {
    let result = OnvifSession::builder("http://cam/onvif/device")
        .with_transport(Arc::new(ErrorTransport { status: 503 }))
        .build()
        .await;

    assert!(matches!(result, Err(OnvifError::Transport(_))));
}

#[tokio::test]
async fn test_builder_soap_fault_propagates() {
    let transport = SequenceTransport::new(&[soap_fault_xml()]);
    let result = OnvifSession::builder("http://cam/onvif/device")
        .with_transport(transport)
        .build()
        .await;

    assert!(matches!(
        result,
        Err(OnvifError::Soap(crate::soap::SoapError::Fault { .. }))
    ));
}

// ── client() / capabilities() accessors ──────────────────────────────────

#[tokio::test]
async fn test_client_accessor_returns_underlying_client() {
    let session = session_with(&[]).await;
    // Verify the client is callable (it will return transport error since no
    // more responses, but the accessor itself must work)
    let _client_ref = session.client();
}

#[tokio::test]
async fn test_capabilities_accessor_is_the_cached_value() {
    let session = session_with(&[]).await;
    let caps = session.capabilities();
    // Smoke check that the cached caps are the parsed full caps fixture
    assert_eq!(caps.device.url.as_deref(), Some("http://cam/onvif/device"));
}

// ── Missing URL errors ────────────────────────────────────────────────────
// Each test builds a session with only a Device URL so the relevant
// service URL resolver returns Err rather than Ok.

async fn session_device_only() -> OnvifSession {
    OnvifSession::builder("http://cam/onvif/device")
        .with_transport(SequenceTransport::new(&[caps_device_only_xml()]))
        .build()
        .await
        .expect("device-only session build failed")
}

#[tokio::test]
async fn test_missing_media_url_returns_error() {
    let session = session_device_only().await;
    let err = session.get_profiles().await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

#[tokio::test]
async fn test_missing_ptz_url_returns_error() {
    let session = session_device_only().await;
    let err = session.ptz_stop("tok").await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

#[tokio::test]
async fn test_missing_imaging_url_returns_error() {
    let session = session_device_only().await;
    let err = session.get_imaging_settings("src_tok").await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

#[tokio::test]
async fn test_missing_events_url_returns_error() {
    let session = session_device_only().await;
    let err = session.get_event_properties().await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

#[tokio::test]
async fn test_missing_recording_url_returns_error() {
    let session = session_device_only().await;
    let err = session.get_recordings().await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

#[tokio::test]
async fn test_missing_search_url_returns_error() {
    let session = session_device_only().await;
    let err = session.find_recordings(None, "PT60S").await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

#[tokio::test]
async fn test_missing_replay_url_returns_error() {
    let session = session_device_only().await;
    let err = session
        .get_replay_uri("tok", "RTP-Unicast", "RTSP")
        .await
        .unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

#[tokio::test]
async fn test_missing_media2_url_returns_error() {
    let session = session_device_only().await;
    let err = session.get_profiles_media2().await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::MissingField(_))
    ));
}

// ── Delegate method tests ─────────────────────────────────────────────────

#[tokio::test]
async fn test_get_profiles_delegates_and_returns_results() {
    let session = session_with(&[profiles_xml()]).await;
    let profiles = session.get_profiles().await.unwrap();
    assert_eq!(profiles.len(), 1);
    assert_eq!(profiles[0].token, "Profile_1");
    assert_eq!(profiles[0].name, "mainStream");
}

#[tokio::test]
async fn test_get_stream_uri_delegates_and_returns_uri() {
    let session = session_with(&[stream_uri_xml()]).await;
    let uri = session.get_stream_uri("Profile_1").await.unwrap();
    assert_eq!(uri.uri, "rtsp://cam:554/stream1");
}

#[tokio::test]
async fn test_ptz_stop_delegates_ok() {
    let session = session_with(&[ptz_stop_xml()]).await;
    session.ptz_stop("Profile_1").await.unwrap();
}

#[tokio::test]
async fn test_get_imaging_settings_delegates_ok() {
    let session = session_with(&[imaging_settings_xml()]).await;
    let settings = session.get_imaging_settings("VideoSource_1").await.unwrap();
    assert_eq!(settings.brightness, Some(50.0));
}

#[tokio::test]
async fn test_get_recordings_delegates_and_returns_items() {
    let session = session_with(&[recordings_xml()]).await;
    let recs = session.get_recordings().await.unwrap();
    assert_eq!(recs.len(), 1);
    assert_eq!(recs[0].token, "rec1");
    assert_eq!(recs[0].recording_status, "Recording");
}

#[tokio::test]
async fn test_delegate_soap_fault_propagates() {
    let session = session_with(&[soap_fault_xml()]).await;
    let err = session.get_profiles().await.unwrap_err();
    assert!(matches!(
        err,
        OnvifError::Soap(crate::soap::SoapError::Fault { .. })
    ));
}

#[tokio::test]
async fn test_get_device_info_uses_device_url() {
    // Device methods bypass service URL caching and go directly to device_url
    let device_info_xml = r#"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
                  xmlns:tds="http://www.onvif.org/ver10/device/wsdl">
      <s:Body>
        <tds:GetDeviceInformationResponse>
          <tds:Manufacturer>TestCorp</tds:Manufacturer>
          <tds:Model>Cam-X</tds:Model>
          <tds:FirmwareVersion>1.0</tds:FirmwareVersion>
          <tds:SerialNumber>SN001</tds:SerialNumber>
          <tds:HardwareId>0x01</tds:HardwareId>
        </tds:GetDeviceInformationResponse>
      </s:Body>
    </s:Envelope>"#;

    let session = session_with(&[device_info_xml]).await;
    let info = session.get_device_info().await.unwrap();
    assert_eq!(info.manufacturer, "TestCorp");
    assert_eq!(info.model, "Cam-X");
}