1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use std::convert::TryFrom;
use std::sync::Arc;

use thiserror::Error;
use tokio::sync::{oneshot, Mutex};
use validator::Validate;

use crate::{
    component::ComponentName,
    global::{Global, InputMessage, InputMessageData, InputSourceHandle, Message},
    image::{RawImage, RawImageError},
    instance::{InstanceHandle, InstanceHandleError, StartEffectError},
};

/// Schema definitions as Serde serializable structures and enums
pub mod message;
use message::{HyperionCommand, HyperionMessage, HyperionResponse};

#[derive(Debug, Error)]
pub enum JsonApiError {
    #[error("error broadcasting update: {0}")]
    Broadcast(#[from] tokio::sync::broadcast::error::SendError<InputMessage>),
    #[error("request not implemented")]
    NotImplemented,
    #[error("error decoding image")]
    Image(#[from] RawImageError),
    #[error("error validating request: {0}")]
    Validation(#[from] validator::ValidationErrors),
    #[error("error receiving system response: {0}")]
    Recv(#[from] oneshot::error::RecvError),
    #[error("error accessing the current instance: {0}")]
    Instance(#[from] InstanceHandleError),
    #[error("no current instance found")]
    InstanceNotFound,
    #[error(transparent)]
    StartEffect(#[from] StartEffectError),
}

/// A client connected to the JSON endpoint
pub struct ClientConnection {
    source: InputSourceHandle<InputMessage>,
    current_instance: Option<i32>,
}

impl ClientConnection {
    pub fn new(source: InputSourceHandle<InputMessage>) -> Self {
        Self {
            source,
            current_instance: None,
        }
    }

    async fn current_instance(&mut self, global: &Global) -> Result<InstanceHandle, JsonApiError> {
        if let Some(current_instance) = self.current_instance {
            if let Some(instance) = global.get_instance(current_instance).await {
                return Ok(instance);
            } else {
                // Instance id now invalid, reset
                self.current_instance = None;
            }
        }

        if let Some((id, inst)) = global.default_instance().await {
            self.set_current_instance(id);
            return Ok(inst);
        }

        Err(JsonApiError::InstanceNotFound)
    }

    fn set_current_instance(&mut self, id: i32) {
        debug!("{}: switch to instance {}", &self.source.name(), id);
        self.current_instance = Some(id);
    }

    #[instrument(skip(request, global))]
    pub async fn handle_request(
        &mut self,
        request: HyperionMessage,
        global: &Global,
    ) -> Result<HyperionResponse, JsonApiError> {
        request.validate()?;

        match request.command {
            HyperionCommand::ClearAll => {
                // Update state
                self.source
                    .send(ComponentName::All, InputMessageData::ClearAll)?;
            }

            HyperionCommand::Clear(message::Clear { priority }) => {
                // Update state
                self.source
                    .send(ComponentName::All, InputMessageData::Clear { priority })?;
            }

            HyperionCommand::Color(message::Color {
                priority,
                duration,
                color,
                origin: _,
            }) => {
                // TODO: Handle origin field

                // Update state
                self.source.send(
                    ComponentName::Color,
                    InputMessageData::SolidColor {
                        priority,
                        duration: duration.map(|ms| chrono::Duration::milliseconds(ms as _)),
                        color,
                    },
                )?;
            }

            HyperionCommand::Image(message::Image {
                priority,
                duration,
                imagewidth,
                imageheight,
                imagedata,
                origin: _,
                format: _,
                scale: _,
                name: _,
            }) => {
                // TODO: Handle origin, format, scale, name fields

                let raw_image = RawImage::try_from((imagedata, imagewidth, imageheight))?;

                self.source.send(
                    ComponentName::Image,
                    InputMessageData::Image {
                        priority,
                        duration: duration.map(|ms| chrono::Duration::milliseconds(ms as _)),
                        image: Arc::new(raw_image),
                    },
                )?;
            }

            HyperionCommand::Effect(message::Effect {
                priority,
                duration,
                origin: _,
                effect,
                python_script: _,
                image_data: _,
            }) => {
                // TODO: Handle origin, python_script, image_data

                let instance = self.current_instance(global).await?;
                let (tx, rx) = oneshot::channel();

                instance
                    .send(InputMessage::new(
                        self.source.id(),
                        ComponentName::All,
                        InputMessageData::Effect {
                            priority,
                            duration: duration.map(|ms| chrono::Duration::milliseconds(ms as _)),
                            effect: effect.into(),
                            response: Arc::new(Mutex::new(Some(tx))),
                        },
                    ))
                    .await?;

                return Ok(rx.await?.map(|_| HyperionResponse::success())?);
            }

            HyperionCommand::ServerInfo(message::ServerInfoRequest { subscribe: _ }) => {
                // TODO: Handle subscribe field

                let (adjustments, priorities) =
                    if let Ok(handle) = self.current_instance(global).await {
                        (
                            handle
                                .config()
                                .await?
                                .color
                                .channel_adjustment
                                .iter()
                                .map(|adj| message::ChannelAdjustment::from(adj.clone()))
                                .collect(),
                            handle.current_priorities().await?,
                        )
                    } else {
                        Default::default()
                    };

                // Read effect info
                // TODO: Add per-instance effects
                let effects: Vec<message::EffectDefinition> = global
                    .read_effects(|effects| effects.iter().map(Into::into).collect())
                    .await;

                // Just answer the serverinfo request, no need to update state
                return Ok(global
                    .read_config(|config| {
                        let instances = config
                            .instances
                            .iter()
                            .map(|instance_config| (&instance_config.1.instance).into())
                            .collect();

                        HyperionResponse::server_info(priorities, adjustments, effects, instances)
                    })
                    .await);
            }

            HyperionCommand::Authorize(message::Authorize { subcommand, .. }) => match subcommand {
                message::AuthorizeCommand::AdminRequired => {
                    // TODO: Perform actual authentication flow
                    return Ok(HyperionResponse::admin_required(false));
                }
                message::AuthorizeCommand::TokenRequired => {
                    // TODO: Perform actual authentication flow
                    return Ok(HyperionResponse::token_required(false));
                }
                _ => {
                    return Err(JsonApiError::NotImplemented);
                }
            },

            HyperionCommand::SysInfo => {
                return Ok(HyperionResponse::sys_info(
                    global.read_config(|config| config.uuid()).await,
                ));
            }

            HyperionCommand::Instance(message::Instance {
                subcommand: message::InstanceCommand::SwitchTo,
                instance: Some(id),
                ..
            }) => {
                if global.get_instance(id).await.is_some() {
                    self.set_current_instance(id);
                    return Ok(HyperionResponse::switch_to(Some(id)));
                } else {
                    // Note: it's an "Ok" but should be an Err. Find out how to represent errors
                    // better
                    return Ok(HyperionResponse::switch_to(None));
                }
            }

            _ => return Err(JsonApiError::NotImplemented),
        };

        Ok(HyperionResponse::success())
    }
}

impl std::fmt::Debug for ClientConnection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientConnection")
            .field("source", &format!("{}", &*self.source))
            .finish()
    }
}