oxvif 0.12.0

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
// ── Recording Service ─────────────────────────────────────────────────────────────

use super::OnvifClient;
use crate::error::OnvifError;
use crate::soap::{find_response, parse_soap_body};
use crate::types::{
    FindRecordingResults, RecordingConfiguration, RecordingInformation, RecordingItem,
    RecordingJob, RecordingJobConfiguration, RecordingJobState, xml_escape,
};

impl OnvifClient {
    /// List all recordings stored on the device.
    ///
    /// `recording_url` is obtained from `GetServices` — look for the service
    /// with namespace `http://www.onvif.org/ver10/recording/wsdl`.
    pub async fn get_recordings(
        &self,
        recording_url: &str,
    ) -> Result<Vec<RecordingItem>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/GetRecordings";
        const BODY: &str = "<trc:GetRecordings/>";

        let xml = self.call(recording_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetRecordingsResponse")?;
        RecordingItem::vec_from_xml(resp)
    }

    /// Create a new recording configuration on the device.
    ///
    /// Returns the opaque recording token assigned by the device.
    pub async fn create_recording(
        &self,
        recording_url: &str,
        config: &RecordingConfiguration,
    ) -> Result<String, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/CreateRecording";
        let retention = if config.maximum_retention_time.is_empty() {
            std::borrow::Cow::Borrowed("PT0S")
        } else {
            xml_escape(&config.maximum_retention_time)
        };
        let body = format!(
            "<trc:CreateRecording>\
               <trc:RecordingConfiguration>\
                 <tt:Source>\
                   <tt:SourceId>{source_id}</tt:SourceId>\
                   <tt:Name>{source_name}</tt:Name>\
                   <tt:Location>{location}</tt:Location>\
                   <tt:Description>{description}</tt:Description>\
                 </tt:Source>\
                 <tt:Content>{content}</tt:Content>\
                 <tt:MaximumRetentionTime>{retention}</tt:MaximumRetentionTime>\
               </trc:RecordingConfiguration>\
             </trc:CreateRecording>",
            source_id = xml_escape(&config.source_id),
            source_name = xml_escape(&config.source_name),
            location = xml_escape(&config.location),
            description = xml_escape(&config.description),
            content = xml_escape(&config.content),
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "CreateRecordingResponse")?;
        resp.child("RecordingToken")
            .map(|n| n.text().to_string())
            .ok_or_else(|| crate::soap::SoapError::missing("RecordingToken").into())
    }

    /// Delete a recording and all its tracks from the device.
    pub async fn delete_recording(
        &self,
        recording_url: &str,
        recording_token: &str,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/DeleteRecording";
        let body = format!(
            "<trc:DeleteRecording>\
               <trc:RecordingToken>{}</trc:RecordingToken>\
             </trc:DeleteRecording>",
            xml_escape(recording_token)
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "DeleteRecordingResponse")?;
        Ok(())
    }

    /// Add a new track to an existing recording.
    ///
    /// Returns the track token assigned by the device.
    ///
    /// - `track_type` — `"Video"`, `"Audio"`, or `"Metadata"`.
    /// - `description` — free-text description of the track.
    pub async fn create_track(
        &self,
        recording_url: &str,
        recording_token: &str,
        track_type: &str,
        description: &str,
    ) -> Result<String, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/CreateTrack";
        let body = format!(
            "<trc:CreateTrack>\
               <trc:RecordingToken>{rt}</trc:RecordingToken>\
               <trc:TrackConfiguration>\
                 <tt:TrackType>{tt}</tt:TrackType>\
                 <tt:Description>{desc}</tt:Description>\
               </trc:TrackConfiguration>\
             </trc:CreateTrack>",
            rt = xml_escape(recording_token),
            tt = xml_escape(track_type),
            desc = xml_escape(description),
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "CreateTrackResponse")?;
        resp.child("TrackToken")
            .map(|n| n.text().to_string())
            .ok_or_else(|| crate::soap::SoapError::missing("TrackToken").into())
    }

    /// Remove a track from a recording.
    pub async fn delete_track(
        &self,
        recording_url: &str,
        recording_token: &str,
        track_token: &str,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/DeleteTrack";
        let body = format!(
            "<trc:DeleteTrack>\
               <trc:RecordingToken>{rt}</trc:RecordingToken>\
               <trc:TrackToken>{tt}</trc:TrackToken>\
             </trc:DeleteTrack>",
            rt = xml_escape(recording_token),
            tt = xml_escape(track_token),
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "DeleteTrackResponse")?;
        Ok(())
    }

    /// List all recording jobs on the device.
    pub async fn get_recording_jobs(
        &self,
        recording_url: &str,
    ) -> Result<Vec<RecordingJob>, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/GetRecordingJobs";
        const BODY: &str = "<trc:GetRecordingJobs/>";
        let xml = self.call(recording_url, ACTION, BODY).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetRecordingJobsResponse")?;
        RecordingJob::vec_from_xml(resp)
    }

    /// Create a new recording job that feeds a live stream into a recording.
    ///
    /// Returns the job token assigned by the device.
    pub async fn create_recording_job(
        &self,
        recording_url: &str,
        config: &RecordingJobConfiguration,
    ) -> Result<String, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/CreateRecordingJob";
        let body = format!(
            "<trc:CreateRecordingJob>{}</trc:CreateRecordingJob>",
            config.to_xml_body()
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "CreateRecordingJobResponse")?;
        resp.child("JobToken")
            .map(|n| n.text().to_string())
            .ok_or_else(|| crate::soap::SoapError::missing("JobToken").into())
    }

    /// Enable or disable a recording job.
    ///
    /// `mode` must be `"Active"` or `"Idle"`.
    pub async fn set_recording_job_mode(
        &self,
        recording_url: &str,
        job_token: &str,
        mode: &str,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/SetRecordingJobMode";
        let body = format!(
            "<trc:SetRecordingJobMode>\
               <trc:JobToken>{jt}</trc:JobToken>\
               <trc:Mode>{mode}</trc:Mode>\
             </trc:SetRecordingJobMode>",
            jt = xml_escape(job_token),
            mode = xml_escape(mode),
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "SetRecordingJobModeResponse")?;
        Ok(())
    }

    /// Delete a recording job from the device.
    pub async fn delete_recording_job(
        &self,
        recording_url: &str,
        job_token: &str,
    ) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/DeleteRecordingJob";
        let body = format!(
            "<trc:DeleteRecordingJob>\
               <trc:JobToken>{}</trc:JobToken>\
             </trc:DeleteRecordingJob>",
            xml_escape(job_token)
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "DeleteRecordingJobResponse")?;
        Ok(())
    }

    /// Get the current operational state of a recording job.
    pub async fn get_recording_job_state(
        &self,
        recording_url: &str,
        job_token: &str,
    ) -> Result<RecordingJobState, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/recording/wsdl/GetRecordingJobState";
        let body = format!(
            "<trc:GetRecordingJobState>\
               <trc:JobToken>{}</trc:JobToken>\
             </trc:GetRecordingJobState>",
            xml_escape(job_token)
        );
        let xml = self.call(recording_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetRecordingJobStateResponse")?;
        RecordingJobState::from_xml(resp)
    }

    // ── Search Service ────────────────────────────────────────────────────────────

    /// Start an asynchronous search for recordings.
    ///
    /// Returns a search token string; pass it to
    /// [`get_recording_search_results`](Self::get_recording_search_results).
    ///
    /// - `max_matches` — upper bound on results (`None` = device default).
    /// - `keep_alive_timeout` — how long the search is kept open on the device
    ///   (ISO 8601 duration, e.g. `"PT60S"`).
    pub async fn find_recordings(
        &self,
        search_url: &str,
        max_matches: Option<u32>,
        keep_alive_timeout: &str,
    ) -> Result<String, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/search/wsdl/FindRecordings";
        let max_el = max_matches
            .map(|m| format!("<tse:MaxMatches>{m}</tse:MaxMatches>"))
            .unwrap_or_default();
        let keep_alive_timeout = xml_escape(keep_alive_timeout);
        // `Scope` (type tt:SearchScope) is a *required* first child per the
        // search WSDL sequence (Scope → MaxMatches? → KeepAliveTime). An empty
        // element means "all sources/recordings" — SearchScope's own children
        // are all optional. Strict devices (e.g. Hanwha) reject the body with an
        // "occurrence constraint violation" fault if Scope is omitted.
        let body = format!(
            "<tse:FindRecordings>\
               <tse:Scope></tse:Scope>\
               {max_el}\
               <tse:KeepAliveTime>{keep_alive_timeout}</tse:KeepAliveTime>\
             </tse:FindRecordings>"
        );

        let xml = self.call(search_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "FindRecordingsResponse")?;
        resp.child("SearchToken")
            .map(|n| n.text().to_string())
            .ok_or_else(|| crate::soap::SoapError::missing("SearchToken").into())
    }

    /// Retrieve search results for a recording search started by
    /// [`find_recordings`](Self::find_recordings).
    ///
    /// Call repeatedly until `results.search_state == "Completed"`.
    /// Then call [`end_search`](Self::end_search) to release server resources.
    pub async fn get_recording_search_results(
        &self,
        search_url: &str,
        search_token: &str,
        max_results: u32,
        wait_time: &str,
    ) -> Result<FindRecordingResults, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/search/wsdl/GetRecordingSearchResults";
        let search_token = xml_escape(search_token);
        let wait_time = xml_escape(wait_time);
        let body = format!(
            "<tse:GetRecordingSearchResults>\
               <tse:SearchToken>{search_token}</tse:SearchToken>\
               <tse:MaxResults>{max_results}</tse:MaxResults>\
               <tse:WaitTime>{wait_time}</tse:WaitTime>\
             </tse:GetRecordingSearchResults>"
        );

        let xml = self.call(search_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetRecordingSearchResultsResponse")?;
        FindRecordingResults::from_xml(resp)
    }

    /// Release a search session on the device.
    ///
    /// Always call this after you have finished reading results from
    /// [`get_recording_search_results`](Self::get_recording_search_results).
    pub async fn end_search(&self, search_url: &str, search_token: &str) -> Result<(), OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/search/wsdl/EndSearch";
        let search_token = xml_escape(search_token);
        let body = format!(
            "<tse:EndSearch>\
               <tse:SearchToken>{search_token}</tse:SearchToken>\
             </tse:EndSearch>"
        );

        let xml = self.call(search_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        find_response(&body_node, "EndSearchResponse")?;
        Ok(())
    }

    /// Search all recordings and return results in a single call.
    ///
    /// Combines [`find_recordings`](Self::find_recordings),
    /// repeated [`get_recording_search_results`](Self::get_recording_search_results)
    /// polling, and [`end_search`](Self::end_search) into one convenient method.
    ///
    /// - `max_matches` — upper bound on results (`None` = device default).
    ///
    /// Returns a flat `Vec<RecordingInformation>` with all matched recordings.
    pub async fn search_recordings(
        &self,
        search_url: &str,
        max_matches: Option<u32>,
    ) -> Result<Vec<RecordingInformation>, OnvifError> {
        let token = self
            .find_recordings(search_url, max_matches, "PT60S")
            .await?;

        let mut all = Vec::new();
        // Cap polling iterations to prevent unbounded loops when a device
        // never reports `Completed`.  20 rounds × 100 results × PT5S wait
        // covers up to 2 000 recordings with a ~100 s worst-case wall time.
        for _ in 0..20 {
            let results = self
                .get_recording_search_results(search_url, &token, 100, "PT5S")
                .await?;
            all.extend(results.recording_information);
            if results.search_state == "Completed" {
                break;
            }
        }

        let _ = self.end_search(search_url, &token).await;
        Ok(all)
    }

    // ── Replay Service ────────────────────────────────────────────────────────────

    /// Retrieve an RTSP URI for replaying a stored recording.
    ///
    /// - `recording_token` — from [`get_recordings`](Self::get_recordings) or
    ///   [`get_recording_search_results`](Self::get_recording_search_results).
    /// - `stream_type` — `"RTP-Unicast"` or `"RTP-Multicast"`.
    /// - `protocol` — `"RTSP"` or `"RtspOverHttp"`.
    pub async fn get_replay_uri(
        &self,
        replay_url: &str,
        recording_token: &str,
        stream_type: &str,
        protocol: &str,
    ) -> Result<String, OnvifError> {
        const ACTION: &str = "http://www.onvif.org/ver10/replay/wsdl/GetReplayUri";
        let recording_token = xml_escape(recording_token);
        let stream_type = xml_escape(stream_type);
        let protocol = xml_escape(protocol);
        let body = format!(
            "<trp:GetReplayUri>\
               <trp:StreamSetup>\
                 <tt:Stream>{stream_type}</tt:Stream>\
                 <tt:Transport><tt:Protocol>{protocol}</tt:Protocol></tt:Transport>\
               </trp:StreamSetup>\
               <trp:RecordingToken>{recording_token}</trp:RecordingToken>\
             </trp:GetReplayUri>"
        );

        let xml = self.call(replay_url, ACTION, &body).await?;
        let body_node = parse_soap_body(&xml)?;
        let resp = find_response(&body_node, "GetReplayUriResponse")?;
        resp.child("Uri")
            .map(|n| n.text().to_string())
            .ok_or_else(|| crate::soap::SoapError::missing("Uri").into())
    }
}