Skip to main content

wechat_protocol/calls/
conference.rs

1//! Voice conference creation and additional invitation codecs.
2//! These builders perform no I/O, allocate no task/intent IDs and never retry.
3use super::{
4    personal::{HostOperation, HostRequest, VoiceInputs, VoiceRoom},
5    signaling,
6};
7use crate::protobuf::{self as p, Field, Value};
8use anyhow::{bail, ensure, Context, Result};
9
10const MAX_BODY: usize = 64 * 1024;
11const MAX_INVITEES: usize = 100;
12
13/// Voice-only microphone state, distinct from membership and local playback.
14/// Video fields remain absent. Timestamp is caller-owned and must increase for
15/// each actual change; a response retry hint never permits automatic resending.
16pub fn switch_microphone(
17    inputs: &VoiceInputs<'_>,
18    room: VoiceRoom,
19    enabled: bool,
20    timestamp: u64,
21    sdk_task: u32,
22) -> Result<signaling::CloudRequest> {
23    inputs.validate_conference_context()?;
24    ensure!(
25        room.room != 0 && room.room_key != 0 && timestamp != 0 && sdk_task != 0,
26        "Invalid conference microphone context"
27    );
28    let body = p::message(&[
29        p::bytes(1, inputs.sdk),
30        p::bytes(2, inputs.group),
31        p::uint(3, room.room),
32        p::uint(4, room.room_key),
33        p::uint(5, u64::from(room.own_member)),
34        p::uint(6, u64::from(enabled)),
35        p::uint(7, timestamp),
36        p::bytes(8, &[]),
37    ])?;
38    Ok(signaling::CloudRequest::for_operation(
39        sdk_task,
40        signaling::CallOperation::SwitchAv,
41        body,
42    ))
43}
44
45/// Prepare one voice conference creation request. Application metadata must
46/// select conference mode and the same group; direct-call inputs stay invalid.
47/// Absent custom authorization remains absent on the wire.
48pub fn create_voice(
49    inputs: &VoiceInputs<'_>,
50    group_id: &str,
51    invitees: &[String],
52    invite_id: u64,
53    sdk_task: u32,
54    custom_auth: Option<&[u8]>,
55) -> Result<HostRequest> {
56    group(group_id)?;
57    contacts(invitees)?;
58    ensure!(
59        invite_id != 0 && sdk_task != 0,
60        "Missing conference intent or task"
61    );
62    let client = inputs.conference_client_info(group_id)?;
63    let mut fields = invitees
64        .iter()
65        .map(|name| p::bytes(1, name.as_bytes()))
66        .collect::<Vec<_>>();
67    fields.extend([
68        p::uint(2, 1),
69        p::bytes(3, group_id.as_bytes()),
70        p::bytes(4, &client),
71        p::uint(5, invite_id),
72    ]);
73    if let Some(auth) = custom_auth {
74        ensure!(
75            !auth.is_empty() && auth.len() <= 8192,
76            "Invalid conference custom authorization"
77        );
78        fields.push(p::bytes(6, auth));
79    }
80    fields.push(p::bytes(7, b"voip-mt"));
81    request(HostOperation::Invite, sdk_task, fields)
82}
83
84/// Submit additional invitations for a known conference. Invitation submission
85/// does not add membership or audio tracks. The runtime must check current room
86/// authority and record the original intent before submitting this request.
87pub fn add_members(
88    room: VoiceRoom,
89    group_id: &str,
90    invitees: &[String],
91    invite_id: u64,
92    sdk_task: u32,
93) -> Result<HostRequest> {
94    group(group_id)?;
95    contacts(invitees)?;
96    ensure!(
97        room.room != 0 && room.room_key != 0 && invite_id != 0 && sdk_task != 0,
98        "Missing conference room, intent or task"
99    );
100    let mut fields = vec![
101        p::uint(1, room.room),
102        p::uint(2, room.room_key),
103        p::uint(3, u64::from(room.own_member)),
104        p::uint(4, invite_id),
105        p::bytes(5, group_id.as_bytes()),
106    ];
107    fields.extend(invitees.iter().map(|name| p::bytes(6, name.as_bytes())));
108    fields.extend([p::bytes(7, b"voip-mt"), p::uint(8, 1)]);
109    request(HostOperation::ConferenceAddMembers, sdk_task, fields)
110}
111
112/// Cancel the creator's original unanswered invitation. The runtime must first
113/// verify that its invitation timer is still active. Pending recipients are
114/// supplied in source traversal order, including duplicates; an empty list does
115/// not by itself prove the invitation timer has stopped.
116pub fn cancel_creation(
117    inputs: &VoiceInputs<'_>,
118    room: VoiceRoom,
119    invite_id: u64,
120    pending_recipients: &[String],
121    reason: super::personal::CancelReason,
122    sdk_task: u32,
123) -> Result<HostRequest> {
124    inputs.validate_conference_context()?;
125    ensure!(
126        invite_id != 0
127            && sdk_task != 0
128            && (room.room == 0) == (room.room_key == 0)
129            && pending_recipients.len() <= 228,
130        "Invalid conference cancellation context"
131    );
132    for name in pending_recipients {
133        text(name.as_bytes(), 128, true)?;
134    }
135    let reason = match reason {
136        super::personal::CancelReason::Local => 1,
137        super::personal::CancelReason::Timeout => 4,
138        super::personal::CancelReason::Other => 0,
139        super::personal::CancelReason::NoResponse => {
140            bail!("Direct no-response cancellation is not a conference operation")
141        }
142    };
143    let inner = p::message(&[
144        p::bytes(1, inputs.sdk),
145        p::bytes(2, inputs.group),
146        p::uint(3, room.room),
147        p::uint(4, room.room_key),
148        p::uint(5, invite_id),
149        p::uint(6, reason),
150    ])?;
151    let mut outer = vec![
152        p::bytes(1, &inner),
153        p::uint(2, invite_id),
154        p::uint(3, room.room),
155    ];
156    outer.extend(
157        pending_recipients
158            .iter()
159            .map(|name| p::bytes(4, name.as_bytes())),
160    );
161    outer.push(p::bytes(5, b"voip-mt"));
162    request(HostOperation::Cancel, sdk_task, outer)
163}
164
165fn request(operation: HostOperation, sdk_task: u32, fields: Vec<Vec<u8>>) -> Result<HostRequest> {
166    let body = p::message(&fields)?;
167    ensure!(body.len() <= MAX_BODY, "Conference request too large");
168    Ok(HostRequest {
169        operation,
170        sdk_task,
171        body,
172        longpoll_seconds: None,
173    })
174}
175
176fn contacts(invitees: &[String]) -> Result<()> {
177    ensure!(
178        !invitees.is_empty() && invitees.len() <= MAX_INVITEES,
179        "Invalid conference invitation count"
180    );
181    for contact in invitees {
182        text(contact.as_bytes(), 128, true)?;
183    }
184    Ok(())
185}
186
187fn group(group_id: &str) -> Result<()> {
188    text(group_id.as_bytes(), 256, true)?;
189    ensure!(group_id.ends_with("@chatroom"), "Invalid conference group");
190    Ok(())
191}
192
193fn text(value: &[u8], maximum: usize, nonempty: bool) -> Result<()> {
194    let text = std::str::from_utf8(value)?;
195    ensure!(
196        value.len() <= maximum
197            && (!nonempty || !value.is_empty())
198            && !text.chars().any(char::is_control),
199        "Invalid conference text"
200    );
201    Ok(())
202}
203
204fn fields(raw: &[u8]) -> Result<Vec<Field>> {
205    ensure!(raw.len() <= MAX_BODY, "Conference response too large");
206    signaling::decode_fields(raw)
207}
208fn optional_u64(fields: &[Field], number: u32) -> Result<Option<u64>> {
209    match p::optional(fields, number)? {
210        Some(Value::Varint(value)) => Ok(Some(*value)),
211        None => Ok(None),
212        _ => bail!("Invalid conference integer field {number}"),
213    }
214}
215fn bytes(fields: &[Field], number: u32) -> Result<&[u8]> {
216    p::optional_data(fields, number)?.context("Missing conference bytes field")
217}
218fn optional_text(fields: &[Field], number: u32, maximum: usize) -> Result<Option<String>> {
219    p::optional_data(fields, number)?
220        .map(|raw| {
221            text(raw, maximum, false)?;
222            Ok(std::str::from_utf8(raw)?.to_owned())
223        })
224        .transpose()
225}
226
227/// One server invitation outcome. On a successful outer response, code zero
228/// means submission, not acceptance by a participant. Missing and present-zero codes retain distinct presence.
229pub struct InvitationResult {
230    pub contact_id: String,
231    pub service_code: Option<u32>,
232    pub unknown_fields: Vec<Field>,
233}
234fn invitation_results(values: &[Field], number: u32) -> Result<Vec<InvitationResult>> {
235    let mut results = Vec::new();
236    for field in values.iter().filter(|field| field.number == number) {
237        ensure!(
238            results.len() < MAX_INVITEES,
239            "Too many conference invitation outcomes"
240        );
241        let Value::Bytes(raw) = &field.value else {
242            bail!("Invalid conference invitation outcome");
243        };
244        let fields = fields(raw)?;
245        let contact = bytes(&fields, 1)?;
246        text(contact, 128, true)?;
247        results.push(InvitationResult {
248            contact_id: std::str::from_utf8(contact)?.to_owned(),
249            service_code: signaling::optional_u32(&fields, 2)?,
250            unknown_fields: fields
251                .into_iter()
252                .filter(|field| ![1, 2].contains(&field.number))
253                .collect(),
254        });
255    }
256    Ok(results)
257}
258
259/// Raw authenticated creation result. Allocation, invitation outcomes and the
260/// nested client response remain separate. This type never invents participants
261/// from invitees and deliberately does not implement Debug or serialization.
262pub struct CreateResponse {
263    pub room_id: Option<u64>,
264    pub room_key: Option<u64>,
265    pub own_member: Option<u32>,
266    pub cloud_group_id: Option<String>,
267    pub client_response: Option<Vec<u8>>,
268    pub user_mappings: Vec<Vec<u8>>,
269    pub custom_auth: Option<Vec<u8>>,
270    pub invite_results: Vec<InvitationResult>,
271    pub verification_url: Option<String>,
272    pub ui_flags: Option<u32>,
273    pub original: Vec<u8>,
274    pub unknown_fields: Vec<Field>,
275}
276impl CreateResponse {
277    pub fn decode(raw: &[u8]) -> Result<Self> {
278        let values = fields(raw)?;
279        let room_id = optional_u64(&values, 1)?;
280        let room_key = optional_u64(&values, 2)?;
281        let own_member = signaling::optional_u32(&values, 3)?;
282        let cloud_group_id = optional_text(&values, 4, 1024)?;
283        let client_response = p::optional_data(&values, 5)?.map(Vec::from);
284        if let Some(client) = &client_response {
285            fields(client)?;
286        }
287        let mut users = Vec::new();
288        for entry in values.iter().filter(|field| field.number == 6) {
289            ensure!(users.len() < 128, "Too many conference user mappings");
290            let Value::Bytes(raw) = &entry.value else {
291                bail!("Invalid conference user mapping");
292            };
293            fields(raw)?;
294            users.push(raw.clone());
295        }
296        Ok(Self {
297            room_id,
298            room_key,
299            own_member,
300            cloud_group_id,
301            client_response,
302            user_mappings: users,
303            custom_auth: p::optional_data(&values, 7)?.map(Vec::from),
304            invite_results: invitation_results(&values, 8)?,
305            verification_url: optional_text(&values, 9, 8192)?,
306            ui_flags: signaling::optional_u32(&values, 10)?,
307            original: raw.to_vec(),
308            unknown_fields: values
309                .into_iter()
310                .filter(|field| !(1..=10).contains(&field.number))
311                .collect(),
312        })
313    }
314    /// Identify a complete allocation without claiming membership or media.
315    /// Missing/zero room identifiers can belong to a rejection; partial nonzero
316    /// identity needs review and is never filled from a previous call.
317    pub fn allocated_room(&self) -> Result<Option<VoiceRoom>> {
318        if self.room_id.unwrap_or(0) == 0 && self.room_key.unwrap_or(0) == 0 {
319            return Ok(None);
320        }
321        match (self.room_id, self.room_key, self.own_member) {
322            (Some(room), Some(room_key), Some(own_member)) if room != 0 && room_key != 0 => {
323                Ok(Some(VoiceRoom {
324                    room,
325                    room_key,
326                    own_member,
327                }))
328            }
329            _ => bail!("Incomplete conference allocation"),
330        }
331    }
332}
333
334/// Adding contacts cannot allocate or replace the current room. Optional reply
335/// identity fields are retained and checked when present; omitted fields are
336/// not silently replaced with zero-valued identities.
337pub struct AddMembersResponse {
338    pub room_id: Option<u64>,
339    pub room_key: Option<u64>,
340    pub own_member: Option<u32>,
341    pub invite_results: Vec<InvitationResult>,
342    pub verification_url: Option<String>,
343    pub original: Vec<u8>,
344    pub unknown_fields: Vec<Field>,
345}
346impl AddMembersResponse {
347    pub fn decode(raw: &[u8]) -> Result<Self> {
348        let values = fields(raw)?;
349        let room_id = optional_u64(&values, 1)?;
350        Ok(Self {
351            room_id,
352            room_key: optional_u64(&values, 2)?,
353            own_member: signaling::optional_u32(&values, 3)?,
354            invite_results: invitation_results(&values, 4)?,
355            verification_url: optional_text(&values, 5, 8192)?,
356            original: raw.to_vec(),
357            unknown_fields: values
358                .into_iter()
359                .filter(|field| !(1..=5).contains(&field.number))
360                .collect(),
361        })
362    }
363    pub fn check_room(&self, expected: VoiceRoom) -> Result<()> {
364        ensure!(
365            expected.room != 0
366                && expected.room_key != 0
367                && self.room_id == Some(expected.room)
368                && self.room_key.is_none_or(|key| key == expected.room_key)
369                && self
370                    .own_member
371                    .is_none_or(|member| member == expected.own_member),
372            "Conference invitation response context mismatch"
373        );
374        Ok(())
375    }
376}
377
378#[cfg(test)]
379mod tests;