use std::rc::Rc;
use dom_struct::dom_struct;
use embedder_traits::{self, EmbedderMsg, PermissionPrompt, PermissionRequest};
use ipc_channel::ipc;
use js::conversions::ConversionResult;
use js::jsapi::JSObject;
use js::jsval::{ObjectValue, UndefinedValue};
use servo_config::pref;
use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{
PermissionDescriptor, PermissionName, PermissionState, PermissionStatusMethods,
};
use crate::dom::bindings::codegen::Bindings::PermissionsBinding::PermissionsMethods;
use crate::dom::bindings::error::Error;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bluetooth::Bluetooth;
use crate::dom::bluetoothpermissionresult::BluetoothPermissionResult;
use crate::dom::globalscope::GlobalScope;
use crate::dom::permissionstatus::PermissionStatus;
use crate::dom::promise::Promise;
use crate::realms::{AlreadyInRealm, InRealm};
use crate::script_runtime::{CanGc, JSContext};
pub trait PermissionAlgorithm {
type Descriptor;
#[crown::unrooted_must_root_lint::must_root]
type Status;
fn create_descriptor(
cx: JSContext,
permission_descriptor_obj: *mut JSObject,
) -> Result<Self::Descriptor, Error>;
fn permission_query(
cx: JSContext,
promise: &Rc<Promise>,
descriptor: &Self::Descriptor,
status: &Self::Status,
);
fn permission_request(
cx: JSContext,
promise: &Rc<Promise>,
descriptor: &Self::Descriptor,
status: &Self::Status,
);
fn permission_revoke(descriptor: &Self::Descriptor, status: &Self::Status, can_gc: CanGc);
}
enum Operation {
Query,
Request,
Revoke,
}
#[dom_struct]
pub struct Permissions {
reflector_: Reflector,
}
impl Permissions {
pub fn new_inherited() -> Permissions {
Permissions {
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<Permissions> {
reflect_dom_object(Box::new(Permissions::new_inherited()), global)
}
#[allow(non_snake_case)]
fn manipulate(
&self,
op: Operation,
cx: JSContext,
permissionDesc: *mut JSObject,
promise: Option<Rc<Promise>>,
can_gc: CanGc,
) -> Rc<Promise> {
let p = match promise {
Some(promise) => promise,
None => {
let in_realm_proof = AlreadyInRealm::assert();
Promise::new_in_current_realm(InRealm::Already(&in_realm_proof), can_gc)
},
};
let root_desc = match Permissions::create_descriptor(cx, permissionDesc) {
Ok(descriptor) => descriptor,
Err(error) => {
p.reject_error(error);
return p;
},
};
let status = PermissionStatus::new(&self.global(), &root_desc);
match root_desc.name {
PermissionName::Bluetooth => {
let bluetooth_desc = match Bluetooth::create_descriptor(cx, permissionDesc) {
Ok(descriptor) => descriptor,
Err(error) => {
p.reject_error(error);
return p;
},
};
let result = BluetoothPermissionResult::new(&self.global(), &status);
match op {
Operation::Request => {
Bluetooth::permission_request(cx, &p, &bluetooth_desc, &result)
},
Operation::Query => {
Bluetooth::permission_query(cx, &p, &bluetooth_desc, &result)
},
Operation::Revoke => {
let globalscope = self.global();
globalscope
.permission_state_invocation_results()
.borrow_mut()
.remove(&root_desc.name.to_string());
Bluetooth::permission_revoke(&bluetooth_desc, &result, can_gc)
},
}
},
_ => {
match op {
Operation::Request => {
Permissions::permission_request(cx, &p, &root_desc, &status);
p.resolve_native(&status);
},
Operation::Query => {
Permissions::permission_query(cx, &p, &root_desc, &status);
p.resolve_native(&status);
},
Operation::Revoke => {
let globalscope = self.global();
globalscope
.permission_state_invocation_results()
.borrow_mut()
.remove(&root_desc.name.to_string());
Permissions::permission_revoke(&root_desc, &status, can_gc);
},
}
},
};
match op {
Operation::Revoke => {
self.manipulate(Operation::Query, cx, permissionDesc, Some(p), can_gc)
},
_ => p,
}
}
}
#[allow(non_snake_case)]
impl PermissionsMethods<crate::DomTypeHolder> for Permissions {
fn Query(&self, cx: JSContext, permissionDesc: *mut JSObject, can_gc: CanGc) -> Rc<Promise> {
self.manipulate(Operation::Query, cx, permissionDesc, None, can_gc)
}
fn Request(&self, cx: JSContext, permissionDesc: *mut JSObject, can_gc: CanGc) -> Rc<Promise> {
self.manipulate(Operation::Request, cx, permissionDesc, None, can_gc)
}
fn Revoke(&self, cx: JSContext, permissionDesc: *mut JSObject, can_gc: CanGc) -> Rc<Promise> {
self.manipulate(Operation::Revoke, cx, permissionDesc, None, can_gc)
}
}
impl PermissionAlgorithm for Permissions {
type Descriptor = PermissionDescriptor;
type Status = PermissionStatus;
fn create_descriptor(
cx: JSContext,
permission_descriptor_obj: *mut JSObject,
) -> Result<PermissionDescriptor, Error> {
rooted!(in(*cx) let mut property = UndefinedValue());
property
.handle_mut()
.set(ObjectValue(permission_descriptor_obj));
match PermissionDescriptor::new(cx, property.handle()) {
Ok(ConversionResult::Success(descriptor)) => Ok(descriptor),
Ok(ConversionResult::Failure(error)) => Err(Error::Type(error.into_owned())),
Err(_) => Err(Error::JSFailed),
}
}
fn permission_query(
_cx: JSContext,
_promise: &Rc<Promise>,
_descriptor: &PermissionDescriptor,
status: &PermissionStatus,
) {
status.set_state(get_descriptor_permission_state(status.get_query(), None));
}
fn permission_request(
cx: JSContext,
promise: &Rc<Promise>,
descriptor: &PermissionDescriptor,
status: &PermissionStatus,
) {
Permissions::permission_query(cx, promise, descriptor, status);
match status.State() {
PermissionState::Prompt => {
let perm_name = status.get_query();
let prompt =
PermissionPrompt::Request(embedder_traits::PermissionName::from(perm_name));
let globalscope = GlobalScope::current().expect("No current global object");
let state = prompt_user_from_embedder(prompt, &globalscope);
globalscope
.permission_state_invocation_results()
.borrow_mut()
.insert(perm_name.to_string(), state);
},
_ => return,
}
Permissions::permission_query(cx, promise, descriptor, status);
}
fn permission_revoke(
_descriptor: &PermissionDescriptor,
_status: &PermissionStatus,
_can_gc: CanGc,
) {
}
}
pub fn get_descriptor_permission_state(
permission_name: PermissionName,
env_settings_obj: Option<&GlobalScope>,
) -> PermissionState {
let globalscope = match env_settings_obj {
Some(env_settings_obj) => DomRoot::from_ref(env_settings_obj),
None => GlobalScope::current().expect("No current global object"),
};
let state = if allowed_in_nonsecure_contexts(&permission_name) {
PermissionState::Prompt
} else if pref!(dom.permissions.testing.allowed_in_nonsecure_contexts) {
PermissionState::Granted
} else {
globalscope
.permission_state_invocation_results()
.borrow_mut()
.remove(&permission_name.to_string());
prompt_user_from_embedder(
PermissionPrompt::Insecure(embedder_traits::PermissionName::from(permission_name)),
&globalscope,
)
};
if let Some(prev_result) = globalscope
.permission_state_invocation_results()
.borrow()
.get(&permission_name.to_string())
{
return *prev_result;
}
globalscope
.permission_state_invocation_results()
.borrow_mut()
.insert(permission_name.to_string(), state);
state
}
fn allowed_in_nonsecure_contexts(permission_name: &PermissionName) -> bool {
match *permission_name {
PermissionName::Geolocation => true,
PermissionName::Notifications => true,
PermissionName::Push => false,
PermissionName::Midi => true,
PermissionName::Camera => false,
PermissionName::Microphone => false,
PermissionName::Speaker => false,
PermissionName::Device_info => false,
PermissionName::Background_sync => false,
PermissionName::Bluetooth => false,
PermissionName::Persistent_storage => false,
}
}
fn prompt_user_from_embedder(prompt: PermissionPrompt, gs: &GlobalScope) -> PermissionState {
let (sender, receiver) = ipc::channel().expect("Failed to create IPC channel!");
gs.send_to_embedder(EmbedderMsg::PromptPermission(prompt, sender));
match receiver.recv() {
Ok(PermissionRequest::Granted) => PermissionState::Granted,
Ok(PermissionRequest::Denied) => PermissionState::Denied,
Err(e) => {
warn!(
"Failed to receive permission state from embedder ({:?}).",
e
);
PermissionState::Denied
},
}
}
impl From<PermissionName> for embedder_traits::PermissionName {
fn from(permission_name: PermissionName) -> Self {
match permission_name {
PermissionName::Geolocation => embedder_traits::PermissionName::Geolocation,
PermissionName::Notifications => embedder_traits::PermissionName::Notifications,
PermissionName::Push => embedder_traits::PermissionName::Push,
PermissionName::Midi => embedder_traits::PermissionName::Midi,
PermissionName::Camera => embedder_traits::PermissionName::Camera,
PermissionName::Microphone => embedder_traits::PermissionName::Microphone,
PermissionName::Speaker => embedder_traits::PermissionName::Speaker,
PermissionName::Device_info => embedder_traits::PermissionName::DeviceInfo,
PermissionName::Background_sync => embedder_traits::PermissionName::BackgroundSync,
PermissionName::Bluetooth => embedder_traits::PermissionName::Bluetooth,
PermissionName::Persistent_storage => {
embedder_traits::PermissionName::PersistentStorage
},
}
}
}