about summary refs log tree commit diff
path: root/kittybox-rs/src/database/memory.rs
blob: ce98d0533f666053cdf4658f5185885cadbb285f (plain) (blame)
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
#![allow(clippy::todo)]
use async_trait::async_trait;
use futures_util::FutureExt;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::database::{ErrorKind, MicropubChannel, Result, settings, Storage, StorageError};

#[derive(Clone, Debug)]
pub struct MemoryStorage {
    pub mapping: Arc<RwLock<HashMap<String, serde_json::Value>>>,
    pub channels: Arc<RwLock<HashMap<String, Vec<String>>>>,
}

#[async_trait]
impl Storage for MemoryStorage {
    async fn post_exists(&self, url: &str) -> Result<bool> {
        return Ok(self.mapping.read().await.contains_key(url));
    }

    async fn get_post(&self, url: &str) -> Result<Option<serde_json::Value>> {
        let mapping = self.mapping.read().await;
        match mapping.get(url) {
            Some(val) => {
                if let Some(new_url) = val["see_other"].as_str() {
                    match mapping.get(new_url) {
                        Some(val) => Ok(Some(val.clone())),
                        None => {
                            drop(mapping);
                            self.mapping.write().await.remove(url);
                            Ok(None)
                        }
                    }
                } else {
                    Ok(Some(val.clone()))
                }
            }
            _ => Ok(None),
        }
    }

    async fn put_post(&self, post: &'_ serde_json::Value, _user: &'_ str) -> Result<()> {
        let mapping = &mut self.mapping.write().await;
        let key: &str = match post["properties"]["uid"][0].as_str() {
            Some(uid) => uid,
            None => {
                return Err(StorageError::from_static(
                    ErrorKind::Other,
                    "post doesn't have a UID",
                ))
            }
        };
        mapping.insert(key.to_string(), post.clone());
        if post["properties"]["url"].is_array() {
            for url in post["properties"]["url"]
                .as_array()
                .unwrap()
                .iter()
                .map(|i| i.as_str().unwrap().to_string())
            {
                if url != key {
                    mapping.insert(url, json!({ "see_other": key }));
                }
            }
        }
        if post["type"]
            .as_array()
            .unwrap()
            .iter()
            .any(|i| i == "h-feed")
        {
            // This is a feed. Add it to the channels array if it's not already there.
            println!("{:#}", post);
            self.channels
                .write()
                .await
                .entry(
                    post["properties"]["author"][0]
                        .as_str()
                        .unwrap()
                        .to_string(),
                )
                .or_insert_with(Vec::new)
                .push(key.to_string())
        }
        Ok(())
    }

    async fn update_post(&self, url: &'_ str, update: crate::micropub::MicropubUpdate) -> Result<()> {
        todo!()
    }

    async fn get_channels(&self, user: &'_ str) -> Result<Vec<MicropubChannel>> {
        match self.channels.read().await.get(user) {
            Some(channels) => Ok(futures_util::future::join_all(
                channels
                    .iter()
                    .map(|channel| {
                        self.get_post(channel).map(|result| result.unwrap()).map(
                            |post: Option<serde_json::Value>| {
                                post.map(|post| MicropubChannel {
                                    uid: post["properties"]["uid"][0].as_str().unwrap().to_string(),
                                    name: post["properties"]["name"][0]
                                        .as_str()
                                        .unwrap()
                                        .to_string(),
                                })
                            },
                        )
                    })
                    .collect::<Vec<_>>(),
            )
            .await
            .into_iter()
            .flatten()
            .collect::<Vec<_>>()),
            None => Ok(vec![]),
        }
    }

    #[allow(unused_variables)]
    async fn read_feed_with_limit(
        &self,
        url: &'_ str,
        after: &'_ Option<String>,
        limit: usize,
        user: &'_ Option<String>,
    ) -> Result<Option<serde_json::Value>> {
        todo!()
    }

    #[allow(unused_variables)]
    async fn read_feed_with_cursor(
        &self,
        url: &'_ str,
        cursor: Option<&'_ str>,
        limit: usize,
        user: Option<&'_ str>
    ) -> Result<Option<(serde_json::Value, Option<String>)>> {
        todo!()
    }

    async fn delete_post(&self, url: &'_ str) -> Result<()> {
        self.mapping.write().await.remove(url);
        Ok(())
    }

    #[allow(unused_variables)]
    async fn get_setting<S: settings::Setting<'a>, 'a>(&'_ self, user: &'_ str) -> Result<S> {
        todo!()
    }

    #[allow(unused_variables)]
    async fn set_setting<S: settings::Setting<'a> + 'a, 'a>(&self, user: &'a str, value: S::Data) -> Result<()> {
        todo!()
    }

}

impl Default for MemoryStorage {
    fn default() -> Self {
        Self::new()
    }
}

impl MemoryStorage {
    pub fn new() -> Self {
        Self {
            mapping: Arc::new(RwLock::new(HashMap::new())),
            channels: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}