muzzman_lib/
location.rs

1use bytes_kman::TBytes;
2use std::fmt::Debug;
3use std::hash::Hash;
4use std::net::{IpAddr, TcpStream};
5use std::ops::Range;
6use std::path::PathBuf;
7use std::str::FromStr;
8use std::sync::{Arc, Mutex, RwLock};
9use std::thread::JoinHandle;
10
11use serde::{Deserialize, Serialize};
12
13use crate::prelude::*;
14
15#[derive(Clone, Debug, Serialize, Deserialize, bytes_kman::Bytes)]
16pub enum LocationNotify {
17    ElementNotify(usize, ElementNotify),
18    ModuleChanged(Option<ModuleId>),
19    ElementsAllCompleted,
20    Completed,
21}
22
23impl_get_ref!(LocationNotify);
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct ServerLocation {
27    pub ip: IpAddr,
28    pub port: u16,
29    pub indentification: String,
30    pub server_cert: Option<String>,
31    #[serde(skip)]
32    pub conn: Option<Arc<Mutex<TcpStream>>>,
33}
34
35impl TBytes for ServerLocation {
36    fn size(&self) -> usize {
37        self.ip.to_string().size()
38            + self.port.size()
39            + self.indentification.size()
40            + self.server_cert.size()
41    }
42
43    fn to_bytes(&self) -> Vec<u8> {
44        let mut buff = Vec::with_capacity(self.size());
45
46        buff.append(&mut self.ip.to_string().to_bytes());
47        buff.append(&mut self.port.to_bytes());
48        buff.append(&mut self.indentification.to_bytes());
49        buff.append(&mut self.server_cert.to_bytes());
50
51        buff
52    }
53
54    fn from_bytes(buffer: &mut Vec<u8>) -> Option<Self>
55    where
56        Self: Sized,
57    {
58        let ip = String::from_bytes(buffer)?;
59        let port = u16::from_bytes(buffer)?;
60        let indentification = String::from_bytes(buffer)?;
61        let server_cert = <Option<String>>::from_bytes(buffer)?;
62
63        let ip = IpAddr::from_str(&ip).unwrap();
64
65        Some(Self {
66            ip,
67            port,
68            indentification,
69            server_cert,
70            conn: None,
71        })
72    }
73}
74
75impl Hash for ServerLocation {
76    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
77        self.ip.hash(state);
78        self.port.hash(state);
79        self.indentification.hash(state);
80        self.server_cert.hash(state);
81    }
82}
83
84#[derive(Debug, Clone, Serialize, Deserialize, Hash, bytes_kman::Bytes)]
85pub struct LocalLocation {
86    pub path: PathBuf,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize, Hash, bytes_kman::Bytes)]
90pub enum WhereIsLocation {
91    Server(ServerLocation),
92    Local(LocalLocation),
93}
94
95#[derive(
96    Default,
97    Debug,
98    Clone,
99    Serialize,
100    Deserialize,
101    PartialEq,
102    Eq,
103    PartialOrd,
104    Ord,
105    Hash,
106    bytes_kman::Bytes,
107)]
108pub struct LocationId(pub Vec<u64>);
109
110impl std::ops::Deref for LocationId {
111    type Target = Vec<u64>;
112
113    fn deref(&self) -> &Self::Target {
114        &self.0
115    }
116}
117
118impl std::ops::DerefMut for LocationId {
119    fn deref_mut(&mut self) -> &mut Self::Target {
120        &mut self.0
121    }
122}
123
124impl std::iter::IntoIterator for LocationId {
125    type Item = u64;
126
127    type IntoIter = std::vec::IntoIter<u64>;
128
129    fn into_iter(self) -> Self::IntoIter {
130        self.0.into_iter()
131    }
132}
133
134impl LocationId {
135    pub fn into_ref(self, session: Box<dyn TSession>) -> RefLocation {
136        RefLocation {
137            session: Some(session),
138            id: self,
139        }
140    }
141}
142
143#[derive(Serialize, Deserialize)]
144pub struct RefLocation {
145    #[serde(skip)]
146    pub session: Option<Box<dyn TSession>>,
147    pub id: LocationId,
148}
149
150impl Debug for RefLocation {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        f.debug_struct("LocatioInfo")
153            .field("uid", &self.id)
154            .finish()
155    }
156}
157
158impl Clone for RefLocation {
159    fn clone(&self) -> Self {
160        Self {
161            id: self.id.clone(),
162            session: if let Some(session) = &self.session {
163                Some(session.c())
164            } else {
165                None
166            },
167        }
168    }
169}
170
171impl PartialEq for RefLocation {
172    fn eq(&self, other: &Self) -> bool {
173        self.id.eq(&other.id)
174    }
175}
176
177pub struct Location {
178    pub name: String,
179    pub desc: String,
180    pub where_is: WhereIsLocation,
181    pub shoud_save: bool,
182    pub elements: Vec<ERow>,
183    pub locations: Vec<LRow>,
184    pub info: LRef,
185    pub path: PathBuf,
186    pub thread: Option<JoinHandle<()>>,
187    pub module: Option<MRef>,
188    pub events: Arc<RwLock<Events>>,
189}
190
191impl TLocation for LRef {
192    fn get_session(&self) -> Result<Box<dyn TSession>, SessionError> {
193        if let Some(session) = &self.read().unwrap().session {
194            return Ok(session.c());
195        }
196
197        Err(SessionError::InvalidSession)
198    }
199
200    fn get_path(&self) -> Result<PathBuf, SessionError> {
201        self.get_session()?.location_get_path(&self.id())
202    }
203
204    fn set_path(&self, path: PathBuf) -> Result<(), SessionError> {
205        self.get_session()?.location_set_path(&self.id(), path)
206    }
207
208    fn get_where_is(&self) -> Result<WhereIsLocation, SessionError> {
209        self.get_session()?.location_get_where_is(&self.id())
210    }
211
212    fn set_where_is(&self, where_is: WhereIsLocation) -> Result<(), SessionError> {
213        self.get_session()?
214            .location_set_where_is(&self.id(), where_is)
215    }
216
217    fn get_should_save(&self) -> Result<bool, SessionError> {
218        self.get_session()?.location_get_should_save(&self.id())
219    }
220
221    fn set_should_save(&self, should_save: bool) -> Result<(), SessionError> {
222        self.get_session()?
223            .location_set_should_save(&self.id(), should_save)
224    }
225
226    fn get_elements(&self, range: Range<usize>) -> Result<Vec<ERef>, SessionError> {
227        self.get_session()?.location_get_elements(&self.id(), range)
228    }
229
230    fn get_elements_len(&self) -> Result<usize, SessionError> {
231        self.get_session()?.location_get_elements_len(&self.id())
232    }
233
234    fn get_locations(&self, range: Range<usize>) -> Result<Vec<LRef>, SessionError> {
235        self.get_session()?.get_locations(&self.id(), range)
236    }
237
238    fn get_locations_len(&self) -> Result<usize, SessionError> {
239        self.get_session()?.get_locations_len(&self.id())
240    }
241
242    fn get_location_info(&self) -> Result<LocationInfo, SessionError> {
243        self.get_session()?.location_get_location_info(&self.id())
244    }
245
246    fn create_element(&self, name: &str) -> Result<ERef, SessionError> {
247        self.get_session()?.create_element(name, &self.id())
248    }
249
250    fn create_location(&self, name: &str) -> Result<LRef, SessionError> {
251        self.get_session()?.create_location(name, &self.id())
252    }
253
254    fn destroy(self) -> Result<LRow, SessionError> {
255        self.get_session()?.destroy_location(self.id())
256    }
257
258    fn _move(&self, to: &LocationId) -> Result<(), SessionError> {
259        self.get_session()?.move_location(&self.id(), to)
260    }
261
262    fn id(&self) -> LocationId {
263        self.read().unwrap().id.clone()
264    }
265}
266
267impl Common for LRef {
268    fn get_name(&self) -> Result<String, SessionError> {
269        self.get_session()?.location_get_name(&self.id())
270    }
271
272    fn set_name(&self, name: impl Into<String>) -> Result<(), SessionError> {
273        self.get_session()?
274            .location_set_name(&self.id(), &name.into())
275    }
276
277    fn get_desc(&self) -> Result<String, SessionError> {
278        self.get_session()?.location_get_desc(&self.id())
279    }
280
281    fn set_desc(&self, desc: impl Into<String>) -> Result<(), SessionError> {
282        self.get_session()?
283            .location_set_desc(&self.id(), &desc.into())
284    }
285
286    fn notify(&self, event: Event) -> Result<(), SessionError> {
287        self.get_session()?.location_notify(&self.id(), event)
288    }
289
290    fn emit(&self, event: Event) -> Result<(), SessionError> {
291        self.get_session()?.location_emit(&self.id(), event)
292    }
293
294    fn subscribe(&self, _ref: ID) -> Result<(), SessionError> {
295        self.get_session()?.location_subscribe(&self.id(), _ref)
296    }
297
298    fn unsubscribe(&self, _ref: ID) -> Result<(), SessionError> {
299        self.get_session()?.location_unsubscribe(&self.id(), _ref)
300    }
301}
302
303pub trait TLocation {
304    fn get_session(&self) -> Result<Box<dyn TSession>, SessionError>;
305
306    fn get_path(&self) -> Result<PathBuf, SessionError>;
307    fn set_path(&self, path: PathBuf) -> Result<(), SessionError>;
308
309    fn get_where_is(&self) -> Result<WhereIsLocation, SessionError>;
310    fn set_where_is(&self, where_is: WhereIsLocation) -> Result<(), SessionError>;
311
312    fn get_should_save(&self) -> Result<bool, SessionError>;
313    fn set_should_save(&self, should_save: bool) -> Result<(), SessionError>;
314
315    fn get_elements(&self, range: Range<usize>) -> Result<Vec<ERef>, SessionError>;
316    fn get_elements_len(&self) -> Result<usize, SessionError>;
317    fn get_locations(&self, range: Range<usize>) -> Result<Vec<LRef>, SessionError>;
318    fn get_locations_len(&self) -> Result<usize, SessionError>;
319
320    fn get_location_info(&self) -> Result<LocationInfo, SessionError>;
321
322    fn create_element(&self, name: &str) -> Result<ERef, SessionError>;
323    fn create_location(&self, name: &str) -> Result<LRef, SessionError>;
324
325    fn destroy(self) -> Result<LRow, SessionError>;
326    fn _move(&self, to: &LocationId) -> Result<(), SessionError>;
327
328    fn id(&self) -> LocationId;
329}
330
331#[derive(Clone, Debug, Serialize, Deserialize, Hash, bytes_kman::Bytes)]
332pub struct LocationInfo {
333    pub name: String,
334    pub desc: String,
335    // hash
336    pub id: LocationId,
337    pub where_is: WhereIsLocation,
338    pub shoud_save: bool,
339    pub elements: Vec<ElementInfo>,
340    pub locations: Vec<LocationInfo>,
341    pub path: PathBuf,
342    pub module: Option<ModuleInfo>,
343}
344
345impl TGetLogger for LRef {
346    fn get_logger(&self, dst: Option<Arc<Mutex<std::fs::File>>>) -> Logger {
347        Logger::for_location(dst, self.clone())
348    }
349}
350
351impl TGetLogger for LRow {
352    fn get_logger(&self, dst: Option<Arc<Mutex<std::fs::File>>>) -> Logger {
353        let info = self.read().unwrap().info.clone();
354        Logger::for_location(dst, info)
355    }
356}