matrix_sdk/widget/machine/
to_widget.rsuse std::marker::PhantomData;
use ruma::{events::AnyTimelineEvent, serde::Raw};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue;
use tracing::error;
use super::{openid::OpenIdResponse, Action, ToWidgetRequestMeta, WidgetMachine};
use crate::widget::Capabilities;
pub(crate) struct ToWidgetRequestHandle<'m, T> {
request_meta: Option<&'m mut ToWidgetRequestMeta>,
_phantom: PhantomData<fn() -> T>,
}
impl<'m, T> ToWidgetRequestHandle<'m, T>
where
T: DeserializeOwned,
{
pub(crate) fn new(request_meta: &'m mut ToWidgetRequestMeta) -> Self {
Self { request_meta: Some(request_meta), _phantom: PhantomData }
}
pub(crate) fn null() -> Self {
Self { request_meta: None, _phantom: PhantomData }
}
pub(crate) fn then(
self,
response_handler: impl FnOnce(T, &mut WidgetMachine) -> Vec<Action> + Send + 'static,
) {
if let Some(request_meta) = self.request_meta {
request_meta.response_fn = Some(Box::new(move |raw_response_data, machine| {
match serde_json::from_str(raw_response_data.get()) {
Ok(response_data) => response_handler(response_data, machine),
Err(e) => {
error!("Failed to deserialize toWidget response: {e}");
Vec::new()
}
}
}));
}
}
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct ToWidgetResponse {
pub(super) action: String,
#[allow(dead_code)]
#[serde(rename = "data")]
pub(super) request_data: Box<RawJsonValue>,
#[serde(rename = "response")]
pub(super) response_data: Box<RawJsonValue>,
}
pub(crate) trait ToWidgetRequest: Serialize {
const ACTION: &'static str;
type ResponseData: DeserializeOwned;
}
#[derive(Serialize)]
pub(super) struct RequestCapabilities {}
impl ToWidgetRequest for RequestCapabilities {
const ACTION: &'static str = "capabilities";
type ResponseData = RequestCapabilitiesResponse;
}
#[derive(Deserialize)]
pub(super) struct RequestCapabilitiesResponse {
pub(super) capabilities: Capabilities,
}
#[derive(Serialize)]
pub(super) struct NotifyCapabilitiesChanged {
pub(super) requested: Capabilities,
pub(super) approved: Capabilities,
}
impl ToWidgetRequest for NotifyCapabilitiesChanged {
const ACTION: &'static str = "notify_capabilities";
type ResponseData = Empty;
}
#[derive(Serialize)]
pub(crate) struct NotifyOpenIdChanged(pub(crate) OpenIdResponse);
impl ToWidgetRequest for NotifyOpenIdChanged {
const ACTION: &'static str = "openid_credentials";
type ResponseData = OpenIdResponse;
}
#[derive(Serialize)]
#[serde(transparent)]
pub(crate) struct NotifyNewMatrixEvent(pub(crate) Raw<AnyTimelineEvent>);
impl ToWidgetRequest for NotifyNewMatrixEvent {
const ACTION: &'static str = "send_event";
type ResponseData = Empty;
}
#[derive(Deserialize)]
pub(crate) struct Empty {}