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