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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*
Copyright (C) 2020 Kunal Mehta <legoktm@member.fsf.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
//! # eventstreams
//!
//! The `eventstreams` crate provides a convenient, typed, wrapper around
//! Wikimedia's  [EventStreams](https://wikitech.wikimedia.org/wiki/Event_Platform/EventStreams)
//! live recent changes feed.
//!
//! Clients can add listeners for edit and log entry events:
//! ```no_run
//! use eventstreams::EventStream;
//!
//! let stream = EventStream::new();
//! stream.on_edit(|edit| {
//!     println!(
//!         "{}: {} edited {}",
//!         &edit.server_name, &edit.user, &edit.title
//!     );
//! });
//! ```
//!
//! It's straightforward to filter events if you only care about a single wiki:
//! ```no_run
//! # use eventstreams::EventStream;
//! let stream = EventStream::new();
//! stream.on_wiki_edit("en.wikipedia.org", |edit| {
//!     println!(
//!         "{}: {} edited {}",
//!         &edit.server_name, &edit.user, &edit.title
//!     );
//! });
//! ```
//!
//! # Optional features
//! An optional `mediawiki-api` feature provides tighter integration with the
//! [`mediawiki`](https://docs.rs/mediawiki/) crate.
#[cfg(feature = "mediawiki-api")]
use mediawiki::{api::Api, title::Title};
use serde::Deserialize;
use serde_json::Value;
use sse_client::EventSource;
use std::marker::Send;

/// Represents an edit
#[derive(Clone, Debug, Deserialize)]
pub struct EditEvent {
    #[serde(rename = "$schema")]
    schema: String,
    // TODO: figure out a better structure for this
    meta: EventMeta,
    /// Revision ID ([rev_id](https://www.mediawiki.org/wiki/Manual:Revision_table#rev_id))
    pub id: u32,
    #[serde(rename = "type")]
    type_: String,
    /// Namespace ID
    pub namespace: i32,
    /// Prefixed title (includes namespace name)
    pub title: String,
    /// Edit summary ([comment_text](https://www.mediawiki.org/wiki/Manual:Comment_table#comment_text))
    pub comment: String,
    /// HTML-parsed version of [`comment`](EditEvent#structfield.comment)
    pub parsedcomment: String,
    /// Unix timestamp
    pub timestamp: u32,
    /// Username ([actor_name](https://www.mediawiki.org/wiki/Manual:Actor_table#actor_name))
    pub user: String,
    /// Whether the edit was flagged as by a bot ([rc_bot](https://www.mediawiki.org/wiki/Manual:Recentchanges_table#rc_bot))
    pub bot: bool,
    minor: Option<bool>,
    patrolled: Option<bool>,
    /// Length in bytes of new revision, and potentially old revision
    pub length: EventLength,
    /// Revision ID of new revision, and potentially old revision
    pub revision: EventRevision,
    /// URL of wiki with protocol, e.g. `https://www.wikidata.org`
    pub server_url: String,
    /// Domain of wiki with no protocol, e.g. `www.wikidata.org` or `en.wikipedia.org`
    pub server_name: String,
    /// Base URL path of wiki ([$wgScriptPath](https://www.mediawiki.org/wiki/Manual:$wgScriptPath))
    pub server_script_path: String,
    /// Internal database name (usually [$wgDBname](https://www.mediawiki.org/wiki/Manual:$wgDBname))
    pub wiki: String,
}

impl EditEvent {
    /// Whether the edit is marked as minor
    pub fn is_minor(&self) -> bool {
        self.minor.unwrap_or(false)
    }

    /// Whether the edit has been marked as patrolled
    pub fn is_patrolled(&self) -> bool {
        self.patrolled.unwrap_or(false)
    }

    fn endpoint(&self, path: &str) -> String {
        format!(
            "{}{}/{}.php",
            self.server_url, self.server_script_path, path
        )
    }

    /// URL to the wiki's api.php ("[Action API](https://www.mediawiki.org/wiki/API:Main_page)") endpoint
    pub fn api_url(&self) -> String {
        self.endpoint("api")
    }

    fn title_for_url(&self) -> String {
        self.title.replace(" ", "_")
    }

    /// URL to the diff for this edit, formatted for human readability
    pub fn diff_url(&self) -> String {
        format!(
            "{}?title={}&diff={}",
            self.endpoint("index"),
            self.title_for_url(),
            self.revision.new
        )
    }

    /// URL to the diff for this edit, as short as possible
    pub fn short_diff_url(&self) -> String {
        format!("{}?diff={}", self.server_url, self.revision.new)
    }

    /// Get a [`mediawiki::api::Api`](https://docs.rs/mediawiki/latest/mediawiki/api/struct.Api.html) instance
    /// # Optional
    /// Requires `mediawiki-api` feature
    #[cfg(feature = "mediawiki-api")]
    pub fn api(&self) -> Api {
        Api::new(&self.api_url()).unwrap()
    }

    /// Get a [`mediawiki::title::Title`](https://docs.rs/mediawiki/latest/mediawiki/title/struct.Title.html) instance
    /// # Optional
    /// Requires `mediawiki-api` feature
    #[cfg(feature = "mediawiki-api")]
    pub fn get_title(&self) -> Title {
        Title::new_from_full(&self.title, &self.api())
    }
}

/// Represents a log entry
#[derive(Clone, Debug, Deserialize)]
pub struct LogEvent {
    #[serde(rename = "$schema")]
    schema: String,
    meta: EventMeta,
    #[serde(rename = "type")]
    type_: String,
    /// Namespace ID
    pub namespace: i32,
    /// Prefixed title (includes namespace name)
    pub title: String,
    /// Edit summary ([comment_text](https://www.mediawiki.org/wiki/Manual:Comment_table#comment_text))
    pub comment: String,
    /// HTML-parsed version of [`comment`](EditEvent#structfield.comment)
    pub parsedcomment: String,
    /// Unix timestamp
    pub timestamp: u32,
    /// Username ([actor_name](https://www.mediawiki.org/wiki/Manual:Actor_table#actor_name))
    pub user: String,
    /// Whether the edit was flagged as by a bot ([rc_bot](https://www.mediawiki.org/wiki/Manual:Recentchanges_table#rc_bot))
    pub bot: bool,
    pub log_id: u32,
    pub log_type: String,
    pub log_action: String,
    pub log_params: Value,
    pub log_action_comment: String,
    /// URL of wiki with protocol, e.g. `https://www.wikidata.org`
    pub server_url: String,
    /// Domain of wiki with no protocol, e.g. `www.wikidata.org` or `en.wikipedia.org`
    pub server_name: String,
    /// Base URL path of wiki ([$wgScriptPath](https://www.mediawiki.org/wiki/Manual:$wgScriptPath))
    pub server_script_path: String,
    /// Internal database name (usually [$wgDBname](https://www.mediawiki.org/wiki/Manual:$wgDBname))
    pub wiki: String,
}

impl LogEvent {
    /// URL to the wiki's api.php ("[Action API](https://www.mediawiki.org/wiki/API:Main_page)") endpoint
    pub fn api_url(&self) -> String {
        format!("{}{}/api.php", self.server_url, self.server_script_path)
    }

    /// Get a [`mediawiki::api::Api`](https://docs.rs/mediawiki/latest/mediawiki/api/struct.Api.html) instance
    /// # Optional
    /// Requires `mediawiki-api` feature
    #[cfg(feature = "mediawiki-api")]
    pub fn api(&self) -> Api {
        Api::new(&self.api_url()).unwrap()
    }

    /// Get a [`mediawiki::title::Title`](https://docs.rs/mediawiki/latest/mediawiki/title/struct.Title.html) instance
    /// # Optional
    /// Requires `mediawiki-api` feature
    #[cfg(feature = "mediawiki-api")]
    pub fn get_title(&self) -> Title {
        Title::new_from_full(&self.title, &self.api())
    }
}

/// Length in bytes of new revision, and potentially old revision
#[derive(Clone, Debug, Deserialize)]
pub struct EventLength {
    /// Length of old revision, in bytes
    pub old: Option<u32>,
    /// Length of new revision, in bytes
    pub new: u32,
}

#[derive(Clone, Debug, Deserialize)]
pub struct EventRevision {
    /// Revision ID for old revision
    pub old: Option<u32>,
    /// Revision ID for new revision
    pub new: u32,
}

#[derive(Clone, Debug, Deserialize)]
struct EventMeta {
    uri: String,
    request_id: String,
    id: String,
    dt: String,
    domain: String,
    stream: String,
    topic: String,
    partition: u32,
    offset: u32,
}

pub struct EventStream {
    /// Allows manipulation/control of upstream [`sse_client:EventSource`](https://docs.rs/sse-client/1/sse_client/struct.EventSource.html).
    pub source: EventSource,
}

fn handle_line(line: &str) -> Option<Value> {
    if line.is_empty() {
        return None;
    }

    match serde_json::from_str(line) {
        Ok(val) => Some(val),
        // TODO: figure out why we sometimes get truncated lines
        Err(_) => None,
    }
}

impl EventStream {
    /// Create new `EventStream` instance
    pub fn new() -> EventStream {
        EventStream {
            source: EventSource::new(
                "https://stream.wikimedia.org/v2/stream/recentchange",
            )
            .unwrap(),
        }
    }

    /// Set a listener for edits on a specific wiki using the server name
    ///
    /// # Example
    /// ```no_run
    /// # use eventstreams::EventStream;
    /// # let stream = EventStream::new();
    /// stream.on_wiki_edit("www.wikidata.org", |edit| {
    ///     dbg!(edit);
    /// });
    /// ```
    pub fn on_wiki_edit<F>(&self, wiki: &'static str, listener: F)
    where
        F: Fn(EditEvent) + Send + 'static,
    {
        self.on_edit(move |edit| {
            if edit.server_name == wiki {
                listener(edit);
            }
        })
    }

    /// Set a listener for all edits
    ///
    /// # Example
    /// ```no_run
    /// # use eventstreams::EventStream;
    /// # let stream = EventStream::new();
    /// stream.on_edit(|edit| {
    ///     dbg!(edit);
    /// });
    /// ```
    pub fn on_edit<F>(&self, listener: F)
    where
        F: Fn(EditEvent) + Send + 'static,
    {
        self.source.on_message(move |message| {
            let data = handle_line(&message.data);
            if let Some(value) = data {
                if value["type"] == "edit" {
                    let edit: EditEvent =
                        serde_json::from_value(value).unwrap();
                    listener(edit);
                }
            }
        });
    }

    pub fn on_wiki_log<F>(&self, wiki: &'static str, listener: F)
    where
        F: Fn(LogEvent) + Send + 'static,
    {
        self.on_log(move |log| {
            if log.server_name == wiki {
                listener(log);
            }
        })
    }

    pub fn on_log<F>(&self, listener: F)
    where
        F: Fn(LogEvent) + Send + 'static,
    {
        self.source.on_message(move |message| {
            let data = handle_line(&message.data);
            if let Some(value) = data {
                if value["type"] == "log" {
                    let log: LogEvent = serde_json::from_value(value).unwrap();
                    listener(log);
                }
            }
        })
    }

    /// Close the connection. Wrapper around [`sse_client::EventSource#close`](https://docs.rs/sse-client/1/sse_client/struct.EventSource.html#method.close).
    pub fn close(&self) {
        self.source.close();
    }
}

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

#[cfg(test)]
mod tests {
    use crate::handle_line;

    #[test]
    fn test_handle_line() {
        assert_eq!(None, handle_line(""));
        assert_eq!(None, handle_line("{invalid JSON"));
        assert_eq!(
            serde_json::json!({"foo": "bar"}),
            handle_line(r#"{"foo": "bar"}"#).unwrap()
        )
    }
}