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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter};
use std::ops::DerefMut;

use regex::Regex;
use serde::{de, Deserialize};
use smallvec::{smallvec, SmallVec};

use crate::twitter::Tweet;

mod private {
    #[derive(Clone, Debug, serde::Deserialize, PartialEq, Eq, Hash)]
    pub enum Never {}
}

#[derive(Clone, Default)]
pub struct RuleMap {
    map: HashMap<TopicId, SmallVec<[Rule; 1]>>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum TopicId {
    Twitter(i64),
    #[doc(hidden)]
    _NonExhaustive(private::Never),
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Outbox {
    Twitter(i64),
    None,
    #[doc(hidden)]
    _NonExhaustive(private::Never),
}

#[derive(Clone, Debug, Deserialize)]
pub struct Rule {
    #[serde(default)]
    filter: Option<Filter>,
    #[serde(default)]
    exclude: Option<Filter>,
    #[serde(deserialize_with = "de_outbox")]
    outbox: SmallVec<[Outbox; 1]>,
}

#[derive(Clone, Debug)]
pub struct Filter {
    title: Regex,
    text: Option<Regex>,
}

impl RuleMap {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn with_capacity(cap: usize) -> Self {
        RuleMap {
            map: HashMap::with_capacity(cap),
        }
    }

    pub fn insert(&mut self, topic: TopicId, rule: Rule) {
        self.map
            .entry(topic)
            .or_insert_with(SmallVec::new)
            .push(rule);
    }

    pub fn get(&self, topic: &TopicId) -> Option<&[Rule]> {
        self.map.get(topic).map(|vec| &**vec)
    }

    pub fn get_mut(
        &mut self,
        topic: &TopicId,
    ) -> Option<&mut (impl Extend<Rule> + DerefMut<Target = [Rule]>)> {
        self.map.get_mut(topic)
    }

    pub fn contains_topic(&self, topic: &TopicId) -> bool {
        self.map.contains_key(topic)
    }

    pub fn remove(
        &mut self,
        topic: &TopicId,
    ) -> Option<impl IntoIterator<Item = Rule> + DerefMut<Target = [Rule]>> {
        self.map.remove(topic)
    }

    pub fn topics(&self) -> impl Iterator<Item = &TopicId> {
        self.map.keys()
    }

    pub fn twitter_topics<'a>(&'a self) -> impl Iterator<Item = i64> + 'a {
        self.topics().filter_map(|topic| match *topic {
            TopicId::Twitter(user) => Some(user),
            _ => None,
        })
    }

    pub fn rules(&self) -> impl Iterator<Item = &Rule> {
        self.map.values().flatten()
    }

    pub fn outboxes(&self) -> impl Iterator<Item = &Outbox> {
        self.rules().flat_map(|rule| &rule.outbox)
    }

    pub fn twitter_outboxes<'a>(&'a self) -> impl Iterator<Item = i64> + 'a {
        self.outboxes().filter_map(|outbox| match *outbox {
            Outbox::Twitter(user) => Some(user),
            _ => None,
        })
    }

    pub fn route_tweet<'a>(&'a self, tweet: &'a Tweet) -> impl Iterator<Item = &'a Outbox> {
        self.get(&TopicId::Twitter(tweet.user.id))
            .into_iter()
            .flatten()
            .filter(move |r| {
                r.filter.as_ref().map_or(true, |f| f.matches_tweet(tweet))
                    && r.exclude.as_ref().map_or(true, |e| !e.matches_tweet(tweet))
            })
            .flat_map(|r| &r.outbox)
    }
}

impl Debug for RuleMap {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        Debug::fmt(&self.map, f)
    }
}

impl<'de> Deserialize<'de> for RuleMap {
    fn deserialize<D: de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct Visitor;

        impl<'de> de::Visitor<'de> for Visitor {
            type Value = RuleMap;

            fn expecting(&self, f: &mut Formatter<'_>) -> fmt::Result {
                f.write_str("a sequence")
            }

            fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
                let map = HashMap::with_capacity(seq.size_hint().unwrap_or(0));
                let mut ret = RuleMap { map };

                #[derive(Deserialize)]
                struct RulePrototype {
                    topics: Vec<TopicId>,
                    #[serde(flatten)]
                    rule: Rule,
                }

                while let Some(RulePrototype { mut topics, rule }) = seq.next_element()? {
                    if let Some(last) = topics.pop() {
                        for topic in topics {
                            ret.insert(topic, rule.clone());
                        }
                        ret.insert(last, rule);
                    }
                }

                Ok(ret)
            }
        }

        d.deserialize_seq(Visitor)
    }
}

impl<'de> Deserialize<'de> for Outbox {
    fn deserialize<D: de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        i64::deserialize(d).map(|id| {
            if id == 0 {
                Outbox::None
            } else {
                Outbox::Twitter(id)
            }
        })
    }
}

impl Rule {
    pub fn new(filter: Option<Filter>, exclude: Option<Filter>) -> Self {
        Rule {
            filter,
            exclude,
            outbox: SmallVec::new(),
        }
    }

    pub fn filter(&self) -> Option<&Filter> {
        self.filter.as_ref()
    }

    pub fn filter_mut(&mut self) -> &mut Option<Filter> {
        &mut self.filter
    }

    pub fn exclude(&self) -> Option<&Filter> {
        self.exclude.as_ref()
    }

    pub fn exclude_mut(&mut self) -> &mut Option<Filter> {
        &mut self.exclude
    }

    pub fn outbox(&self) -> &[Outbox] {
        &self.outbox
    }

    pub fn outbox_mut(
        &mut self,
    ) -> &mut (impl Default + Extend<Outbox> + DerefMut<Target = [Outbox]>) {
        &mut self.outbox
    }
}

impl Filter {
    pub fn from_title(title: Regex) -> Self {
        Filter { title, text: None }
    }

    pub fn matches_tweet(&self, tweet: &Tweet) -> bool {
        self.title.is_match(&tweet.text)
            || self
                .text
                .as_ref()
                .map_or(false, |t| t.is_match(&tweet.text))
    }
}

impl<'de> Deserialize<'de> for Filter {
    fn deserialize<D: de::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Prototype {
            Title(#[serde(with = "serde_regex")] Regex),
            Composite {
                #[serde(with = "serde_regex")]
                title: Regex,
                #[serde(default)]
                #[serde(with = "serde_regex")]
                text: Option<Regex>,
            },
        }

        Prototype::deserialize(d).map(|p| match p {
            Prototype::Title(title) => Filter { title, text: None },
            Prototype::Composite { title, text } => Filter { title, text },
        })
    }
}

fn de_outbox<'de, D: de::Deserializer<'de>>(d: D) -> Result<SmallVec<[Outbox; 1]>, D::Error> {
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Prototype {
        One(Outbox),
        Seq(SmallVec<[Outbox; 1]>),
    }

    Prototype::deserialize(d).map(|p| match p {
        Prototype::One(o) => smallvec![o],
        Prototype::Seq(v) => v,
    })
}