Skip to main content

script/dom/bluetooth/
bluetooth.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use script_bindings::reflector::{DomObject, reflect_dom_object};
6use servo_base::generic_channel::{GenericCallback, GenericSender};
7use servo_bluetooth_traits::{BluetoothError, BluetoothRequest, GATTType};
8use servo_bluetooth_traits::{BluetoothResponse, BluetoothResponseResult};
9use servo_bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted};
10use servo_bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence};
11use servo_bluetooth_traits::scanfilter::{RequestDeviceoptions, ServiceUUIDSequence};
12use js::realm::CurrentRealm;
13use script_bindings::cformat;
14use crate::conversions::Convert;
15use script_bindings::cell::{Ref, DomRefCell};
16use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothDataFilterInit;
17use crate::dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions};
18use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothLEScanFilterInit;
19use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor;
20use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServer_Binding::
21BluetoothRemoteGATTServerMethods;
22use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState};
23use crate::dom::bindings::codegen::UnionTypes::{ArrayBufferViewOrArrayBuffer, StringOrUnsignedLong};
24use crate::dom::bindings::error::Error::{self, Network, Security, Type};
25use crate::dom::bindings::error::Fallible;
26use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
27use crate::dom::bindings::reflector::DomGlobal;
28use crate::dom::bindings::root::{Dom, DomRoot};
29use crate::dom::bindings::str::DOMString;
30use crate::dom::bluetoothdevice::BluetoothDevice;
31use crate::dom::bluetoothpermissionresult::BluetoothPermissionResult;
32use crate::dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID, UUID};
33use crate::dom::eventtarget::EventTarget;
34use crate::dom::globalscope::GlobalScope;
35use crate::dom::permissions::{descriptor_permission_state, PermissionAlgorithm};
36use crate::dom::promise::Promise;
37use crate::script_runtime::CanGc;
38use crate::task::TaskOnce;
39use dom_struct::dom_struct;
40use js::conversions::ConversionResult;
41use js::jsapi::JSObject;
42use js::jsval::{ObjectValue, UndefinedValue};
43use profile_traits::{generic_channel};
44use std::collections::HashMap;
45use std::ffi::CStr;
46use std::rc::Rc;
47use std::sync::{Arc, Mutex};
48
49const KEY_CONVERSION_ERROR: &str =
50    "This `manufacturerData` key can not be parsed as unsigned short:";
51const FILTER_EMPTY_ERROR: &CStr =
52    c"'filters' member, if present, must be nonempty to find any devices.";
53const FILTER_ERROR: &CStr = c"A filter must restrict the devices in some way.";
54const MANUFACTURER_DATA_ERROR: &CStr =
55    c"'manufacturerData', if present, must be non-empty to filter devices.";
56const MASK_LENGTH_ERROR: &CStr = c"`mask`, if present, must have the same length as `dataPrefix`.";
57// 248 is the maximum number of UTF-8 code units in a Bluetooth Device Name.
58const MAX_DEVICE_NAME_LENGTH: usize = 248;
59const NAME_PREFIX_ERROR: &CStr = c"'namePrefix', if present, must be nonempty.";
60const NAME_TOO_LONG_ERROR: &CStr = c"A device name can't be longer than 248 bytes.";
61const SERVICE_DATA_ERROR: &CStr =
62    c"'serviceData', if present, must be non-empty to filter devices.";
63const SERVICE_ERROR: &CStr = c"'services', if present, must contain at least one service.";
64const OPTIONS_ERROR: &CStr = c"Fields of 'options' conflict with each other.
65 Either 'acceptAllDevices' member must be true, or 'filters' member must be set to a value.";
66const BT_DESC_CONVERSION_ERROR: &CStr =
67    c"Can't convert to an IDL value of type BluetoothPermissionDescriptor";
68
69#[derive(JSTraceable, MallocSizeOf)]
70#[expect(non_snake_case)]
71pub(crate) struct AllowedBluetoothDevice {
72    pub(crate) deviceId: DOMString,
73    pub(crate) mayUseGATT: bool,
74}
75
76#[derive(JSTraceable, MallocSizeOf)]
77pub(crate) struct BluetoothExtraPermissionData {
78    allowed_devices: DomRefCell<Vec<AllowedBluetoothDevice>>,
79}
80
81impl BluetoothExtraPermissionData {
82    pub(crate) fn new() -> BluetoothExtraPermissionData {
83        BluetoothExtraPermissionData {
84            allowed_devices: DomRefCell::new(Vec::new()),
85        }
86    }
87
88    pub(crate) fn add_new_allowed_device(&self, allowed_device: AllowedBluetoothDevice) {
89        self.allowed_devices.borrow_mut().push(allowed_device);
90    }
91
92    fn get_allowed_devices(&self) -> Ref<'_, Vec<AllowedBluetoothDevice>> {
93        self.allowed_devices.borrow()
94    }
95
96    pub(crate) fn allowed_devices_contains_id(&self, id: DOMString) -> bool {
97        self.allowed_devices
98            .borrow()
99            .iter()
100            .any(|d| d.deviceId == id)
101    }
102}
103
104impl Default for BluetoothExtraPermissionData {
105    fn default() -> Self {
106        Self::new()
107    }
108}
109
110struct BluetoothContext<T: AsyncBluetoothListener + DomObject> {
111    promise: Option<TrustedPromise>,
112    receiver: Trusted<T>,
113}
114
115pub(crate) trait AsyncBluetoothListener {
116    fn handle_response(
117        &self,
118        cx: &mut js::context::JSContext,
119        result: BluetoothResponse,
120        promise: &Rc<Promise>,
121    );
122}
123
124impl<T> BluetoothContext<T>
125where
126    T: AsyncBluetoothListener + DomObject,
127{
128    fn response(&mut self, cx: &mut js::context::JSContext, response: BluetoothResponseResult) {
129        let promise = self.promise.take().expect("bt promise is missing").root();
130
131        // JSAutoRealm needs to be manually made.
132        // Otherwise, Servo will crash.
133        match response {
134            Ok(response) => self.receiver.root().handle_response(cx, response, &promise),
135            // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
136            // Step 3 - 4.
137            Err(error) => promise.reject_error(error.convert(), CanGc::from_cx(cx)),
138        }
139    }
140}
141
142// https://webbluetoothcg.github.io/web-bluetooth/#bluetooth
143#[dom_struct]
144pub(crate) struct Bluetooth {
145    eventtarget: EventTarget,
146    device_instance_map: DomRefCell<HashMap<String, Dom<BluetoothDevice>>>,
147}
148
149impl Bluetooth {
150    pub(crate) fn new_inherited() -> Bluetooth {
151        Bluetooth {
152            eventtarget: EventTarget::new_inherited(),
153            device_instance_map: DomRefCell::new(HashMap::new()),
154        }
155    }
156
157    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> DomRoot<Bluetooth> {
158        reflect_dom_object(Box::new(Bluetooth::new_inherited()), global, can_gc)
159    }
160
161    fn get_bluetooth_thread(&self) -> GenericSender<BluetoothRequest> {
162        self.global().as_window().bluetooth_thread()
163    }
164
165    pub(crate) fn get_device_map(&self) -> &DomRefCell<HashMap<String, Dom<BluetoothDevice>>> {
166        &self.device_instance_map
167    }
168
169    /// <https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices>
170    fn request_bluetooth_devices(
171        &self,
172        cx: &mut js::context::JSContext,
173        p: &Rc<Promise>,
174        filters: &Option<Vec<BluetoothLEScanFilterInit>>,
175        optional_services: &[BluetoothServiceUUID],
176        sender: GenericCallback<BluetoothResponseResult>,
177    ) {
178        // TODO: Step 1: Triggered by user activation.
179
180        // Step 2.2: There are no requiredServiceUUIDS, we scan for all devices.
181        let mut uuid_filters = vec![];
182
183        if let Some(filters) = filters {
184            // Step 2.1.
185            if filters.is_empty() {
186                p.reject_error(Type(FILTER_EMPTY_ERROR.to_owned()), CanGc::from_cx(cx));
187                return;
188            }
189
190            // Step 2.3: There are no requiredServiceUUIDS, we scan for all devices.
191
192            // Step 2.4.
193            for filter in filters {
194                // Step 2.4.1.
195                match canonicalize_filter(filter) {
196                    // Step 2.4.2.
197                    Ok(f) => uuid_filters.push(f),
198                    Err(e) => {
199                        p.reject_error(e, CanGc::from_cx(cx));
200                        return;
201                    },
202                }
203                // Step 2.4.3: There are no requiredServiceUUIDS, we scan for all devices.
204            }
205        }
206
207        let mut optional_services_uuids = vec![];
208        for opt_service in optional_services {
209            // Step 2.5 - 2.6.
210            let uuid = match BluetoothUUID::service(opt_service.clone()) {
211                Ok(u) => u.to_string(),
212                Err(e) => {
213                    p.reject_error(e, CanGc::from_cx(cx));
214                    return;
215                },
216            };
217
218            // Step 2.7.
219            // Note: What we are doing here, is adding the not blocklisted UUIDs to the result vector,
220            // instead of removing them from an already filled vector.
221            if !uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
222                optional_services_uuids.push(uuid);
223            }
224        }
225
226        let option = RequestDeviceoptions::new(
227            self.global().as_window().webview_id(),
228            BluetoothScanfilterSequence::new(uuid_filters),
229            ServiceUUIDSequence::new(optional_services_uuids),
230        );
231
232        // Step 4 - 5.
233        if let PermissionState::Denied =
234            descriptor_permission_state(PermissionName::Bluetooth, None)
235        {
236            return p.reject_error(Error::NotFound(None), CanGc::from_cx(cx));
237        }
238
239        // Note: Step 3, 6 - 8 are implemented in
240        // components/net/bluetooth_thread.rs in request_device function.
241        self.get_bluetooth_thread()
242            .send(BluetoothRequest::RequestDevice(option, sender))
243            .unwrap();
244    }
245}
246
247pub(crate) fn response_async<T: AsyncBluetoothListener + DomObject + 'static>(
248    promise: &Rc<Promise>,
249    receiver: &T,
250) -> GenericCallback<BluetoothResponseResult> {
251    let task_source = receiver
252        .global()
253        .task_manager()
254        .networking_task_source()
255        .to_sendable();
256    let context = Arc::new(Mutex::new(BluetoothContext {
257        promise: Some(TrustedPromise::new(promise.clone())),
258        receiver: Trusted::new(receiver),
259    }));
260    GenericCallback::new(move |message| {
261        struct ListenerTask<T: AsyncBluetoothListener + DomObject> {
262            context: Arc<Mutex<BluetoothContext<T>>>,
263            action: BluetoothResponseResult,
264        }
265
266        impl<T> TaskOnce for ListenerTask<T>
267        where
268            T: AsyncBluetoothListener + DomObject,
269        {
270            fn run_once(self, cx: &mut js::context::JSContext) {
271                let mut context = self.context.lock().unwrap();
272                context.response(cx, self.action);
273            }
274        }
275
276        let task = ListenerTask {
277            context: context.clone(),
278            action: message.unwrap(),
279        };
280
281        task_source.queue_unconditionally(task);
282    })
283    .expect("Could not create callback")
284}
285
286// https://webbluetoothcg.github.io/web-bluetooth/#getgattchildren
287#[allow(clippy::too_many_arguments)]
288pub(crate) fn get_gatt_children<T, F>(
289    cx: &mut CurrentRealm,
290    attribute: &T,
291    single: bool,
292    uuid_canonicalizer: F,
293    uuid: Option<StringOrUnsignedLong>,
294    instance_id: String,
295    connected: bool,
296    child_type: GATTType,
297) -> Rc<Promise>
298where
299    T: AsyncBluetoothListener + DomObject + 'static,
300    F: FnOnce(StringOrUnsignedLong) -> Fallible<UUID>,
301{
302    let p = Promise::new_in_realm(cx);
303
304    let result_uuid = if let Some(u) = uuid {
305        // Step 1.
306        let canonicalized = match uuid_canonicalizer(u) {
307            Ok(canonicalized_uuid) => canonicalized_uuid.to_string(),
308            Err(e) => {
309                p.reject_error(e, CanGc::from_cx(cx));
310                return p;
311            },
312        };
313        // Step 2.
314        if uuid_is_blocklisted(canonicalized.as_ref(), Blocklist::All) {
315            p.reject_error(Security(None), CanGc::from_cx(cx));
316            return p;
317        }
318        Some(canonicalized)
319    } else {
320        None
321    };
322
323    // Step 3 - 4.
324    if !connected {
325        p.reject_error(Network(None), CanGc::from_cx(cx));
326        return p;
327    }
328
329    // TODO: Step 5: Implement representedDevice internal slot for BluetoothDevice.
330
331    // Note: Steps 6 - 7 are implemented in components/bluetooth/lib.rs in get_descriptor function
332    // and in handle_response function.
333    let sender = response_async(&p, attribute);
334    attribute
335        .global()
336        .as_window()
337        .bluetooth_thread()
338        .send(BluetoothRequest::GetGATTChildren(
339            instance_id,
340            result_uuid,
341            single,
342            child_type,
343            sender,
344        ))
345        .unwrap();
346    p
347}
348
349/// <https://webbluetoothcg.github.io/web-bluetooth/#bluetoothlescanfilterinit-canonicalizing>
350fn canonicalize_filter(filter: &BluetoothLEScanFilterInit) -> Fallible<BluetoothScanfilter> {
351    // Step 1.
352    if filter.services.is_none() &&
353        filter.name.is_none() &&
354        filter.namePrefix.is_none() &&
355        filter.manufacturerData.is_none() &&
356        filter.serviceData.is_none()
357    {
358        return Err(Type(FILTER_ERROR.to_owned()));
359    }
360
361    // Step 2: There is no empty canonicalizedFilter member,
362    // we create a BluetoothScanfilter instance at the end of the function.
363
364    // Step 3.
365    let services_vec = match filter.services {
366        Some(ref services) => {
367            // Step 3.1.
368            if services.is_empty() {
369                return Err(Type(SERVICE_ERROR.to_owned()));
370            }
371
372            let mut services_vec = vec![];
373
374            for service in services {
375                // Step 3.2 - 3.3.
376                let uuid = BluetoothUUID::service(service.clone())?.to_string();
377
378                // Step 3.4.
379                if uuid_is_blocklisted(uuid.as_ref(), Blocklist::All) {
380                    return Err(Security(None));
381                }
382
383                services_vec.push(uuid);
384            }
385            // Step 3.5.
386            services_vec
387        },
388        None => vec![],
389    };
390
391    // Step 4.
392    let name = match filter.name {
393        Some(ref name) => {
394            // Step 4.1.
395            // Note: DOMString::len() gives back the size in bytes.
396            if name.len() > MAX_DEVICE_NAME_LENGTH {
397                return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
398            }
399
400            // Step 4.2.
401            Some(name.to_string())
402        },
403        None => None,
404    };
405
406    // Step 5.
407    let name_prefix = match filter.namePrefix {
408        Some(ref name_prefix) => {
409            // Step 5.1.
410            if name_prefix.is_empty() {
411                return Err(Type(NAME_PREFIX_ERROR.to_owned()));
412            }
413            if name_prefix.len() > MAX_DEVICE_NAME_LENGTH {
414                return Err(Type(NAME_TOO_LONG_ERROR.to_owned()));
415            }
416
417            // Step 5.2.
418            name_prefix.to_string()
419        },
420        None => String::new(),
421    };
422
423    // Step 6 - 7.
424    let manufacturer_data = match filter.manufacturerData {
425        Some(ref manufacturer_data_map) => {
426            // Note: If manufacturer_data_map is empty, that means there are no key values in it.
427            if manufacturer_data_map.is_empty() {
428                return Err(Type(MANUFACTURER_DATA_ERROR.to_owned()));
429            }
430            let mut map = HashMap::new();
431            for (key, bdfi) in manufacturer_data_map.iter() {
432                // Step 7.1 - 7.2.
433                let manufacturer_id = match key.str().parse::<u16>() {
434                    Ok(id) => id,
435                    Err(err) => {
436                        return Err(Type(cformat!("{} {} {}", KEY_CONVERSION_ERROR, key, err)));
437                    },
438                };
439
440                // Step 7.3: No need to convert to IDL values since this is only used by native code.
441
442                // Step 7.4 - 7.5.
443                map.insert(
444                    manufacturer_id,
445                    canonicalize_bluetooth_data_filter_init(bdfi)?,
446                );
447            }
448            Some(map)
449        },
450        None => None,
451    };
452
453    // Step 8 - 9.
454    let service_data = match filter.serviceData {
455        Some(ref service_data_map) => {
456            // Note: If service_data_map is empty, that means there are no key values in it.
457            if service_data_map.is_empty() {
458                return Err(Type(SERVICE_DATA_ERROR.to_owned()));
459            }
460            let mut map = HashMap::new();
461            for (key, bdfi) in service_data_map.iter() {
462                let service_name = match key.str().parse::<u32>() {
463                    // Step 9.1.
464                    Ok(number) => StringOrUnsignedLong::UnsignedLong(number),
465                    // Step 9.2.
466                    _ => StringOrUnsignedLong::String(key.clone()),
467                };
468
469                // Step 9.3 - 9.4.
470                let service = BluetoothUUID::service(service_name)?.to_string();
471
472                // Step 9.5.
473                if uuid_is_blocklisted(service.as_ref(), Blocklist::All) {
474                    return Err(Security(None));
475                }
476
477                // Step 9.6: No need to convert to IDL values since this is only used by native code.
478
479                // Step 9.7 - 9.8.
480                map.insert(service, canonicalize_bluetooth_data_filter_init(bdfi)?);
481            }
482            Some(map)
483        },
484        None => None,
485    };
486
487    // Step 10.
488    Ok(BluetoothScanfilter::new(
489        name,
490        name_prefix,
491        services_vec,
492        manufacturer_data,
493        service_data,
494    ))
495}
496
497/// <https://webbluetoothcg.github.io/web-bluetooth/#bluetoothdatafilterinit-canonicalizing>
498fn canonicalize_bluetooth_data_filter_init(
499    bdfi: &BluetoothDataFilterInit,
500) -> Fallible<(Vec<u8>, Vec<u8>)> {
501    // Step 1.
502    let data_prefix = match bdfi.dataPrefix {
503        Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref avb)) => avb.to_vec(),
504        Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref ab)) => ab.to_vec(),
505        None => vec![],
506    };
507
508    // Step 2.
509    // If no mask present, mask will be a sequence of 0xFF bytes the same length as dataPrefix.
510    // Masking dataPrefix with this, leaves dataPrefix untouched.
511    let mask = match bdfi.mask {
512        Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref avb)) => avb.to_vec(),
513        Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref ab)) => ab.to_vec(),
514        None => vec![0xFF; data_prefix.len()],
515    };
516
517    // Step 3.
518    if mask.len() != data_prefix.len() {
519        return Err(Type(MASK_LENGTH_ERROR.to_owned()));
520    }
521
522    // Step 4.
523    Ok((data_prefix, mask))
524}
525
526impl Convert<Error> for BluetoothError {
527    fn convert(self) -> Error {
528        match self {
529            BluetoothError::Type(message) => Error::Type(cformat!("{message}")),
530            BluetoothError::Network => Error::Network(None),
531            BluetoothError::NotFound => Error::NotFound(None),
532            BluetoothError::NotSupported => Error::NotSupported(None),
533            BluetoothError::Security => Error::Security(None),
534            BluetoothError::InvalidState => Error::InvalidState(None),
535        }
536    }
537}
538
539impl BluetoothMethods<crate::DomTypeHolder> for Bluetooth {
540    /// <https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice>
541    fn RequestDevice(&self, cx: &mut CurrentRealm, option: &RequestDeviceOptions) -> Rc<Promise> {
542        let p = Promise::new_in_realm(cx);
543        // Step 1.
544        if (option.filters.is_some() && option.acceptAllDevices) ||
545            (option.filters.is_none() && !option.acceptAllDevices)
546        {
547            p.reject_error(Error::Type(OPTIONS_ERROR.to_owned()), CanGc::from_cx(cx));
548            return p;
549        }
550
551        // Step 2.
552        let sender = response_async(&p, self);
553        self.request_bluetooth_devices(cx, &p, &option.filters, &option.optionalServices, sender);
554        // Note: Step 3 - 4. in response function, Step 5. in handle_response function.
555        p
556    }
557
558    /// <https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-getavailability>
559    fn GetAvailability(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
560        let p = Promise::new_in_realm(cx);
561        // Step 1. We did not override the method
562        // Step 2 - 3. in handle_response
563        let sender = response_async(&p, self);
564        self.get_bluetooth_thread()
565            .send(BluetoothRequest::GetAvailability(sender))
566            .unwrap();
567        p
568    }
569
570    // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-onavailabilitychanged
571    event_handler!(
572        availabilitychanged,
573        GetOnavailabilitychanged,
574        SetOnavailabilitychanged
575    );
576}
577
578impl AsyncBluetoothListener for Bluetooth {
579    fn handle_response(
580        &self,
581        cx: &mut js::context::JSContext,
582        response: BluetoothResponse,
583        promise: &Rc<Promise>,
584    ) {
585        match response {
586            // https://webbluetoothcg.github.io/web-bluetooth/#request-bluetooth-devices
587            // Step 11, 13 - 14.
588            BluetoothResponse::RequestDevice(device) => {
589                let mut device_instance_map = self.device_instance_map.borrow_mut();
590                if let Some(existing_device) = device_instance_map.get(&device.id) {
591                    return promise.resolve_native(&**existing_device, CanGc::from_cx(cx));
592                }
593                let bt_device = BluetoothDevice::new(
594                    cx,
595                    &self.global(),
596                    DOMString::from(device.id.clone()),
597                    device.name.map(DOMString::from),
598                    self,
599                );
600                device_instance_map.insert(device.id.clone(), Dom::from_ref(&bt_device));
601
602                self.global()
603                    .as_window()
604                    .bluetooth_extra_permission_data()
605                    .add_new_allowed_device(AllowedBluetoothDevice {
606                        deviceId: DOMString::from(device.id),
607                        mayUseGATT: true,
608                    });
609                // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-requestdevice
610                // Step 5.
611                promise.resolve_native(&bt_device, CanGc::from_cx(cx));
612            },
613            // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetooth-getavailability
614            // Step 2 - 3.
615            BluetoothResponse::GetAvailability(is_available) => {
616                promise.resolve_native(&is_available, CanGc::from_cx(cx));
617            },
618            _ => promise.reject_error(
619                Error::Type(c"Something went wrong...".to_owned()),
620                CanGc::from_cx(cx),
621            ),
622        }
623    }
624}
625
626impl PermissionAlgorithm for Bluetooth {
627    type Descriptor = BluetoothPermissionDescriptor;
628    type Status = BluetoothPermissionResult;
629
630    fn create_descriptor(
631        cx: &mut js::context::JSContext,
632        permission_descriptor_obj: *mut JSObject,
633    ) -> Result<BluetoothPermissionDescriptor, Error> {
634        rooted!(&in(cx) let mut property = UndefinedValue());
635        property
636            .handle_mut()
637            .set(ObjectValue(permission_descriptor_obj));
638        match BluetoothPermissionDescriptor::new(cx.into(), property.handle(), CanGc::from_cx(cx)) {
639            Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
640            Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
641            Err(_) => Err(Error::Type(BT_DESC_CONVERSION_ERROR.into())),
642        }
643    }
644
645    /// <https://webbluetoothcg.github.io/web-bluetooth/#query-the-bluetooth-permission>
646    fn permission_query(
647        cx: &mut js::context::JSContext,
648        promise: &Rc<Promise>,
649        descriptor: &BluetoothPermissionDescriptor,
650        status: &BluetoothPermissionResult,
651    ) {
652        // Step 1: We are not using the `global` variable.
653
654        // Step 2.
655        status.set_state(descriptor_permission_state(status.get_query(), None));
656
657        // Step 3.
658        if let PermissionState::Denied = status.get_state() {
659            status.set_devices(Vec::new());
660            return promise.resolve_native(status, CanGc::from_cx(cx));
661        }
662
663        // Step 4.
664        rooted_vec!(let mut matching_devices);
665
666        // Step 5.
667        let global = status.global();
668        let allowed_devices = global
669            .as_window()
670            .bluetooth_extra_permission_data()
671            .get_allowed_devices();
672
673        let bluetooth = status.get_bluetooth();
674        let device_map = bluetooth.get_device_map().borrow();
675
676        // Step 6.
677        for allowed_device in allowed_devices.iter() {
678            // Step 6.1.
679            if let Some(ref id) = descriptor.deviceId &&
680                &allowed_device.deviceId != id
681            {
682                continue;
683            }
684            let device_id = String::from(allowed_device.deviceId.str());
685
686            // Step 6.2.
687            if let Some(ref filters) = descriptor.filters {
688                let mut scan_filters: Vec<BluetoothScanfilter> = Vec::new();
689
690                // Step 6.2.1.
691                for filter in filters {
692                    match canonicalize_filter(filter) {
693                        Ok(f) => scan_filters.push(f),
694                        Err(error) => return promise.reject_error(error, CanGc::from_cx(cx)),
695                    }
696                }
697
698                // Step 6.2.2.
699                // Instead of creating an internal slot we send an ipc message to the Bluetooth thread
700                // to check if one of the filters matches.
701                let (sender, receiver) =
702                    generic_channel::channel(global.time_profiler_chan().clone()).unwrap();
703                status
704                    .get_bluetooth_thread()
705                    .send(BluetoothRequest::MatchesFilter(
706                        device_id.clone(),
707                        BluetoothScanfilterSequence::new(scan_filters),
708                        sender,
709                    ))
710                    .unwrap();
711
712                match receiver.recv().unwrap() {
713                    Ok(true) => (),
714                    Ok(false) => continue,
715                    Err(error) => return promise.reject_error(error.convert(), CanGc::from_cx(cx)),
716                };
717            }
718
719            // Step 6.3.
720            // TODO: Implement this correctly, not just using device ids here.
721            // https://webbluetoothcg.github.io/web-bluetooth/#get-the-bluetoothdevice-representing
722            if let Some(device) = device_map.get(&device_id) {
723                matching_devices.push(Dom::from_ref(&**device));
724            }
725        }
726
727        // Step 7.
728        status.set_devices(std::mem::take(&mut matching_devices));
729
730        // https://w3c.github.io/permissions/#dom-permissions-query
731        // Step 7.
732        promise.resolve_native(status, CanGc::from_cx(cx));
733    }
734
735    /// <https://webbluetoothcg.github.io/web-bluetooth/#request-the-bluetooth-permission>
736    fn permission_request(
737        cx: &mut js::context::JSContext,
738        promise: &Rc<Promise>,
739        descriptor: &BluetoothPermissionDescriptor,
740        status: &BluetoothPermissionResult,
741    ) {
742        // Step 1.
743        if descriptor.filters.is_some() == descriptor.acceptAllDevices {
744            return promise.reject_error(Error::Type(OPTIONS_ERROR.to_owned()), CanGc::from_cx(cx));
745        }
746
747        // Step 2.
748        let sender = response_async(promise, status);
749        let bluetooth = status.get_bluetooth();
750        bluetooth.request_bluetooth_devices(
751            cx,
752            promise,
753            &descriptor.filters,
754            &descriptor.optionalServices,
755            sender,
756        );
757
758        // NOTE: Step 3. is in BluetoothPermissionResult's `handle_response` function.
759    }
760
761    /// <https://webbluetoothcg.github.io/web-bluetooth/#revoke-bluetooth-access>
762    fn permission_revoke(
763        cx: &mut js::context::JSContext,
764        _descriptor: &BluetoothPermissionDescriptor,
765        status: &BluetoothPermissionResult,
766    ) {
767        // Step 1.
768        let global = status.global();
769        let allowed_devices = global
770            .as_window()
771            .bluetooth_extra_permission_data()
772            .get_allowed_devices();
773        // Step 2.
774        let bluetooth = status.get_bluetooth();
775        let device_map = bluetooth.get_device_map().borrow();
776        for (id, device) in device_map.iter() {
777            let id = DOMString::from(id.clone());
778            // Step 2.1.
779            if allowed_devices.iter().any(|d| d.deviceId == id) &&
780                !device.is_represented_device_null()
781            {
782                // Note: We don't need to update the allowed_services,
783                // because we store it in the lower level
784                // where it is already up-to-date
785                continue;
786            }
787            // Step 2.2 - 2.4
788            let _ = device.get_gatt(cx).Disconnect(cx);
789        }
790    }
791}